diff --git a/CHANGELOG.txt b/CHANGELOG.txt deleted file mode 100644 index 5bb9658..0000000 --- a/CHANGELOG.txt +++ /dev/null @@ -1,8 +0,0 @@ -Version 3.3.1 - -* Cascading World Gen Lag issues that were known have been resolved -* Vein generator has been fixed to work properly -* Underfluid generator has been stubbed out and is in testing -* Various minor bugs fixed -* Some small performance improvements -* Most Current Release (something like build 169 or 170) fixes a logic error that saw the system refusing to spawn in any chunk with a negative X or Y coordinate. diff --git a/LICENSE b/LICENSE index e62ad12..b64bc64 100644 --- a/LICENSE +++ b/LICENSE @@ -1,494 +1,24 @@ -GNU Lesser General Public License -================================= +MIT License -_Version 2.1, February 1999_ -_Copyright © 1991, 1999 Free Software Foundation, Inc._ -_51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA_ +Copyright (c) 2023 NeoForged project -Everyone is permitted to copy and distribute verbatim copies -of this license document, but changing it is not allowed. +This license applies to the template files as supplied by github.com/NeoForged/MDK -_This is the first released version of the Lesser GPL. It also counts -as the successor of the GNU Library Public License, version 2, hence -the version number 2.1._ -### Preamble +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 licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - -When we speak of free software, we are referring to freedom of use, -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 this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - -To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - -For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - -We protect your rights with a two-step method: **(1)** we copyright the -library, and **(2)** we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - -To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - -Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - -Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - -When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - -We call this license the “Lesser” General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - -For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - -In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - -Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - -The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -“work based on the library” and a “work that uses the library”. The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - -### TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - -**0.** This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called “this License”). -Each licensee is addressed as “you”. - -A “library” means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - -The “Library”, below, refers to any such software library or work -which has been distributed under these terms. A “work based on the -Library” means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term “modification”.) - -“Source code” for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - -**1.** You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - -You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - -**2.** You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - -* **a)** The modified work must itself be a software library. -* **b)** You must cause the files modified to carry prominent notices -stating that you changed the files and the date of any change. -* **c)** You must cause the whole of the work to be licensed at no -charge to all third parties under the terms of this License. -* **d)** If a facility in the modified Library refers to a function or a -table of data to be supplied by an application program that uses -the facility, other than as an argument passed when the facility -is invoked, then you must make a good faith effort to ensure that, -in the event an application does not supply such function or -table, the facility still operates, and performs whatever part of -its purpose remains meaningful. -(For example, a function in a library to compute square roots has -a purpose that is entirely well-defined independent of the -application. Therefore, Subsection 2d requires that any -application-supplied function or table used by this function must -be optional: if the application does not supply it, the square -root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - -**3.** You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - -Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - -This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - -**4.** You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - -If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - -**5.** A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a “work that uses the Library”. Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - -However, linking a “work that uses the Library” with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a “work that uses the -library”. The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - -When a “work that uses the Library” uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - -If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - -Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - -**6.** As an exception to the Sections above, you may also combine or -link a “work that uses the Library” with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - -You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - -* **a)** Accompany the work with the complete corresponding -machine-readable source code for the Library including whatever -changes were used in the work (which must be distributed under -Sections 1 and 2 above); and, if the work is an executable linked -with the Library, with the complete machine-readable “work that -uses the Library”, as object code and/or source code, so that the -user can modify the Library and then relink to produce a modified -executable containing the modified Library. (It is understood -that the user who changes the contents of definitions files in the -Library will not necessarily be able to recompile the application -to use the modified definitions.) -* **b)** Use a suitable shared library mechanism for linking with the -Library. A suitable mechanism is one that (1) uses at run time a -copy of the library already present on the user's computer system, -rather than copying library functions into the executable, and (2) -will operate properly with a modified version of the library, if -the user installs one, as long as the modified version is -interface-compatible with the version that the work was made with. -* **c)** Accompany the work with a written offer, valid for at -least three years, to give the same user the materials -specified in Subsection 6a, above, for a charge no more -than the cost of performing this distribution. -* **d)** If distribution of the work is made by offering access to copy -from a designated place, offer equivalent access to copy the above -specified materials from the same place. -* **e)** Verify that the user has already received a copy of these -materials or that you have already sent this user a copy. - -For an executable, the required form of the “work that uses the -Library” must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - -It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - -**7.** You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - -* **a)** Accompany the combined library with a copy of the same work -based on the Library, uncombined with any other library -facilities. This must be distributed under the terms of the -Sections above. -* **b)** Give prominent notice with the combined library of the fact -that part of it is a work based on the Library, and explaining -where to find the accompanying uncombined form of the same work. - -**8.** You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - -**9.** You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - -**10.** Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - -**11.** If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -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 -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - -**12.** If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - -**13.** The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -“any later version”, you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - -**14.** If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - -### NO WARRANTY - -**15.** BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY “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 -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -**16.** IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY 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 -LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - -_END OF TERMS AND CONDITIONS_ - -### How to Apply These Terms to Your New Libraries - -If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - -To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey 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 library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a “copyright disclaimer” for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! +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. diff --git a/README.md b/README.md index 63a51fc..31baeae 100644 --- a/README.md +++ b/README.md @@ -1,152 +1,45 @@ -[![](https://img.shields.io/badge/Discord-MMD-green.svg?style=flat&logo=Discord)](https://discord.mcmoddev.com) -[![](http://cf.way2muchnoise.eu/full_mmd-orespawn_downloads.svg)](https://www.curseforge.com/minecraft/mc-mods/mmd-orespawn) -[![](http://cf.way2muchnoise.eu/versions/Minecraft_mmd-orespawn_all.svg)](https://www.curseforge.com/minecraft/mc-mods/mmd-orespawn) -[![Build Status](https://ci.mcmoddev.com/job/OreSpawn/job/OreSpawn%201.12/badge/icon)](https://ci.mcmoddev.com/job/OreSpawn/job/OreSpawn%201.12/) +# MMD OreSpawn 4.x +A re-imagining of an old MMD Mod for modern Minecraft. Now we just provide the feature placers and let the existing +datapack infrastruture handle the rest. -# OreSpawn -Minecraft library mod that provides better control over the spawning of ores in Minecraft. -If you're looking for a place to report bugs for the mod that adds extra mobs, the "DangerZone", etc... go [to the site for that mod](http://www.orespawn.com/) as this is not it. +Work Started: 19-AUG-2024 D. Hazelton +Beta Work Completed: 29-JUL-2025 D. Hazelton ## How it works -Ore Spawn parses all of the .json files found in `orespawn` and adds ore generators to the game based on those files. The JSON structure looks like this: - +This version of MMD OreSpawn adds a set of generators that can be used similar to the vanilla ones. In fact you use +them exactly the same, by putting the right ID in the right JSON file in a data pack. The following example replaced +the standard coal spawn as part of testing the code and uses the `vein` feature generator: ```json -[ - { - "dimension": -1, - "ores": [ - { - "block": "minecraft:quartz_ore", - "size": 15, - "variation": 4, - "frequency": 7, - "min_height": 0, - "max_height": 128 - } - ] - }, - { - "ores": [ - { - "block": "minecraft:coal_ore", - "size": 25, - "variation": 12, - "frequency": 20, - "min_height": 0, - "max_height": 128 - }, - { - "block": "minecraft:iron_ore", - "size": 8, - "variation": 4, - "frequency": 20, - "min_height": 0, - "max_height": 64 - }, - { - "block": "minecraft:gold_ore", - "size": 8, - "variation": 2, - "frequency": 2, - "min_height": 0, - "max_height": 32 - }, - { - "block": "minecraft:diamond_ore", - "size": 6, - "variation": 3, - "frequency": 8, - "min_height": 0, - "max_height": 16 - }, - { - "block": "minecraft:lapis_ore", - "size": 5, - "variation": 2, - "frequency": 1, - "min_height": 0, - "max_height": 32 - }, - { - "block": "minecraft:emerald_ore", - "size": 1, - "variation": 0, - "frequency": 8, - "min_height": 4, - "max_height": 32, - "biomes": [ - "minecraft:extreme_hills", - "minecraft:smaller_extreme_hills" - ] - }, - { - "block": "minecraft:dirt", - "size": 112, - "variation": 50, - "frequency": 10, - "min_height": 0, - "max_height": 255 - }, - { - "block": "minecraft:gravel", - "size": 112, - "variation": 50, - "frequency": 8, - "min_height": 0, - "max_height": 255 - }, - { - "block": "minecraft:stone", - "state": "variant=granite", - "size": 112, - "variation": 50, - "frequency": 10, - "min_height": 0, - "max_height": 255 - }, - { - "block": "minecraft:stone", - "state": "variant=diorite", - "size": 112, - "variation": 50, - "frequency": 10, - "min_height": 0, - "max_height": 255 - }, - { - "block": "minecraft:stone", - "state": "variant=andesite", - "size": 112, - "variation": 50, - "frequency": 10, - "min_height": 0, - "max_height": 255 +{ + "type": "mmdorespawn:mmdos4_vein", + "config": { + "discard_chance_on_air_exposure": 0.5, + "size": 17, + "min_length": 100, + "max_length": 200, + "frequency": 1.0, + "targets": [ + { + "state": { + "Name": "minecraft:coal_ore" + }, + "target": { + "predicate_type": "minecraft:tag_match", + "tag": "minecraft:stone_ore_replaceables" + } + }, + { + "state": { + "Name": "minecraft:deepslate_coal_ore" + }, + "target": { + "predicate_type": "minecraft:tag_match", + "tag": "minecraft:deepslate_ore_replaceables" + } } ] } -] +} ``` -### dimension -The number ID of a dimension. Don't specify any dimension to target all dimensions *that are not already specified*. -### ores -Array of JSON objects specifying ore generators for this dimension -### block -Text ID of a block (the same you would use in the /give command) -### state -The state of a block (typically used for colored blocks) -### size -The number of blocks to spawn. Unlike the default Minecraft world settings JSON, this is the actually number of blocks that will spawn. -### variation -How much to randomly vary the number of blocks spawned (I recommend making this value 50% of the *size* value) -### frequency -How often, per chunk, to attempt to spawn this ore block. This value can be a fraction less than 1. If this value is between 0 and 1, then not every chunk will have a spawn in it. For example, a frequency of 0.1 means that there will be one attempt to spawn the ore per 10 chunks. -### min_height -The lowest Y-coordinate that the ore is allowed to spawn at -### max_height -The highest Y-coordinate that the ore is allowed to spawn at -### biomes -If this array is not empty, then the biomes in which the ore will spawn is restricted to those specified by ID in this array. -# API -Adding OreSpawn support to your mod is not hard. Look at `VanillaOreSpawn.java` for an example. diff --git a/build.gradle b/build.gradle index aa37f0e..1d03b08 100644 --- a/build.gradle +++ b/build.gradle @@ -1,322 +1,168 @@ -def corePlugin = '' - -buildscript { - repositories { - jcenter() -// maven { -// url 'http://maven.aliyun.com/nexus/content/groups/public/' -// } - -// maven { -// url 'http://maven.aliyun.com/nexus/content/repositories/jcenter' -// } - maven { - name = 'forge' - url = 'http://files.minecraftforge.net/maven' - } - maven { - name = 'gradle' - url 'https://plugins.gradle.org/m2/' - } - maven { - name = 'sonatype' - url = 'https://oss.sonatype.org/content/groups/public' - } - } - dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT' - classpath 'gradle.plugin.com.matthewprenger:CurseGradle:1.4.0' - classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:3.0' - } -} - -apply plugin: 'net.minecraftforge.gradle.forge' -apply plugin: 'com.matthewprenger.cursegradle' -apply plugin: 'maven-publish' -apply plugin: 'org.sonarqube' - -javadoc { - failOnError = false -} - -description = 'OreSpawn' -def mod_file = getModFile() -def mc_version = "1.12" -def short_version = getVersion("VERSION", mod_file) -version = mc_version + "-" + short_version -if (System.getenv().BUILD_NUMBER) { - version += '.' + System.getenv().BUILD_NUMBER -} -group = "com.mcmoddev" -sourceCompatibility = targetCompatibility = "1.8" - -class Secrets { - def data = null - - def getProperty(String key) { - return data ? data[key] : '' - } -} - -import groovy.json.JsonSlurper - -def secretFile -if (System.getenv().SECRET_FILE) { - secretFile = file System.getenv().SECRET_FILE -} else { - secretFile = file 'secret.json' -} - -project.ext.secret = new Secrets() -if (secretFile.exists()) { - secretFile.withReader { - project.ext.secret.data = new JsonSlurper().parse it - } -} - -minecraft { - version = '1.12.2-14.23.5.2768' - runDir = 'run' - mappings = 'stable_39' -// coreMod = '' - makeObfSourceJar = false - - replace '@FINGERPRINT@', project.findProperty('signSHA1') -} - -repositories { - maven { // Mantle, TCon, JEI - name 'DVS1 Maven FS' - url 'http://dvs1.progwml6.com/files/maven' - } - maven { // CCL, CCC, NEI - name 'Chickenbones Repo' - url 'http://chickenbones.net/maven/' - } - maven { // The One Probe - name 'tterrag' - url 'http://maven.tterrag.com/' - } - maven { - name 'MMD' - url 'https://maven.mcmoddev.com/' - } - maven { // MCMultipart - name 'amadornes' - url 'http://maven.amadornes.com/' - } - maven { // Tesla - name 'epoxide' - url 'http://maven.epoxide.org' - } - maven { // CraftTweaker, ZenScript - name 'jared maven' - url 'http://blamejared.com/maven' - } - maven { // IC2 - name 'industrialcraft' - url 'http://maven.ic2.player.to' - } - maven { // WAILA/HWYLA - name 'tehnut' - url 'http://tehnut.info/maven' - } - maven { // CoFH - name 'Covers Maven' - url 'http://maven.covers1624.net' - } - maven { - name = 'CurseForge' - url = 'https://minecraft.curseforge.com/api/maven/' - } - maven { - name 'opencomputers' - url 'http://maven.cil.li/' - } - maven { // Mekanism, TAIGA - name 'jitpack' - url 'https://jitpack.io' - } -} - -dependencies { - // None -} - -processResources { - inputs.property 'version', project.version - inputs.property 'mcversion', project.minecraft.version - - from (sourceSets.main.resources.srcDirs) { - include 'mcmod.info' - expand 'version': short_version, 'mcversion': project.minecraft.version - } - - from (sourceSets.main.resources.srcDirs) { - exclude 'mcmod.info' - } -} - -jar { - manifest { -// attributes 'FMLCorePluginContainsFMLMod': 'true' -// attributes 'FMLCorePlugin': corePlugin -// attributes 'FMLAT' : '' - } -} - -task apiJar(type: Jar, dependsOn: classes) { - classifier = 'api' - from sourceSets.main.allSource - exclude('com/mcmoddev/orespawn/impl/**') - exclude('com/mcmoddev/orespawn/impl/features/**') - exclude('com/mcmoddev/orespawn/json/**') - exclude('com/mcmoddev/orespawn/world/**') - exclude('com/mcmoddev/orespawn/commands/**') - exclude('com/mcmoddev/orespawn/data/**') - exclude('com/mcmoddev/orespawn/*.java') -} - -task devJar(type: Jar) { - classifier = 'dev' - from sourceSets.main.output -} - -task deobfJar(type: Jar) { - classifier = 'deobf' - from sourceSets.main.output -} - -task signJar(type: SignJar, dependsOn: reobfJar) { - - // Skips if the keyStore property is missing. - onlyIf { - project.hasProperty('keyStore') - } - - // findProperty allows us to reference the property without it existing. - // Using project.propName would cause the script to fail validation if - // the property did not exist. - keyStore = project.findProperty('keyStore') - alias = project.findProperty('keyStoreAlias') - storePass = project.findProperty('keyStorePass') - keyPass = project.findProperty('keyStoreKeyPass') - inputFile = jar.archivePath - outputFile = jar.archivePath -} - -build.dependsOn signJar - -task javadocJar(type: Jar, dependsOn: javadoc) { - classifier = 'javadoc' - from javadoc.getDestinationDir() -} - -artifacts { - archives apiJar - archives devJar - archives deobfJar - archives sourceJar - archives javadocJar -} - -publishing { - publications { - mavenJava(MavenPublication) { - groupId project.group - artifactId project.archivesBaseName - version project.version - from components.java - artifact sourceJar { - classifier 'sources' - } - artifact apiJar { - classifier 'api' - } - artifact devJar { - classifier 'dev' - } - artifact deobfJar { - classifier 'deobf' - } - artifact javadocJar { - classifier 'javadoc' - } - } - } - repositories { - maven { - credentials { - username secret.username - password secret.password - } - url secret.url - } - } -} - -curseforge { - apiKey = secret.curseforgeAPIKey - project { - id = "245586" - changelog = file("CHANGELOG.txt") - releaseType = "release" - def projName = "OreSpawn" - def displayVersion = getVersion("VERSION", mod_file) - if (System.getenv().BUILD_NUMBER) { - displayVersion += '.' + System.getenv().BUILD_NUMBER - } - mainArtifact(jar) { - displayName = "$project.description $displayVersion" -// relations { -// } - } - addArtifact(apiJar) { - displayName = "$project.description $displayVersion API" - } - addArtifact(sourceJar) { - displayName = "$project.description $displayVersion Sources" - } - addArtifact(deobfJar) { - displayName = "$project.description $displayVersion Development" - } - addArtifact(javadocJar) { - displayName = "$project.description $displayVersion Javadoc" - } - } -} - -sonarqube { - properties { - property 'sonar.host.url', secret.sonarHost - property 'sonar.organization', secret.sonarOrganization - property 'sonar.login', secret.sonarToken - property 'sonar.projectName', project.archivesBaseName - property 'sonar.projectKey', "$project.group:$project.archivesBaseName" - } -} - -String getModFile() { - String path = 'src/main/java/com/mcmoddev/orespawn/data/Constants.java' - return path -} - -String getVersion(String type, String mod_file) { - String major = '0' - String revision = '0' - String patch = '0' - String prefix = "public static final String $type = \"" - File file = file(mod_file) - file.eachLine { String s -> - s = s.trim() - if (s.startsWith(prefix)) { - s = s.substring(prefix.length(), s.length() - 2) - String[] pts = s.split("\\.") - - major = pts[0] - revision = pts[1] - patch = pts[2] - } - } - return "$major.$revision.$patch" -} +plugins { + id 'java-library' + id 'eclipse' + id 'idea' + id 'maven-publish' + id 'net.neoforged.gradle.userdev' version '7.0.142' +} + +version = mod_version +group = mod_group_id + +repositories { + mavenLocal() + maven { + url = 'https://maven.blamejared.com' + name = 'BlameJared Maven' + } +} + +base { + archivesName = mod_id +} + +// Mojang ships Java 21 to end users starting in 1.20.5, so mods should target Java 21. +java.toolchain.languageVersion = JavaLanguageVersion.of(21) + +//minecraft.accessTransformers.file rootProject.file('src/main/resources/META-INF/accesstransformer.cfg') +//minecraft.accessTransformers.entry public net.minecraft.client.Minecraft textureManager # textureManager + +// Default run configurations. +// These can be tweaked, removed, or duplicated as needed. +runs { + // applies to all the run configs below + configureEach { + // Recommended logging data for a userdev environment + // The markers can be added/remove as needed separated by commas. + // "SCAN": For mods scan. + // "REGISTRIES": For firing of registry events. + // "REGISTRYDUMP": For getting the contents of all registries. + systemProperty 'forge.logging.markers', 'REGISTRIES' + + // Recommended logging level for the console + // You can set various levels here. + // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels + systemProperty 'forge.logging.console.level', 'debug' + + modSource project.sourceSets.main + } + + client { + // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. + systemProperty 'forge.enabledGameTestNamespaces', project.mod_id + } + + server { + systemProperty 'forge.enabledGameTestNamespaces', project.mod_id + programArgument '--nogui' + } + + // This run config launches GameTestServer and runs all registered gametests, then exits. + // By default, the server will crash when no gametests are provided. + // The gametest system is also enabled by default for other run configs under the /test command. + gameTestServer { + systemProperty 'forge.enabledGameTestNamespaces', project.mod_id + } + + data { + // example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it + // workingDirectory project.file('run-data') + + // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. + programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath() + } +} + +// Include resources generated by data generators. +sourceSets.main.resources { srcDir 'src/generated/resources' } + +// Sets up a dependency configuration called 'localRuntime'. +// This configuration should be used instead of 'runtimeOnly' to declare +// a dependency that will be present for runtime testing but that is +// "optional", meaning it will not be pulled by dependents of this mod. +configurations { + runtimeClasspath.extendsFrom localRuntime +} + +dependencies { + // Specify the version of Minecraft to use. + // Depending on the plugin applied there are several options. We will assume you applied the userdev plugin as shown above. + // The group for userdev is net.neoforged, the module name is neoforge, and the version is the same as the neoforge version. + // You can however also use the vanilla plugin (net.neoforged.gradle.vanilla) to use a version of Minecraft without the neoforge loader. + // And its provides the option to then use net.minecraft as the group, and one of; client, server or joined as the module name, plus the game version as version. + // For all intends and purposes: You can treat this dependency as if it is a normal library you would use. + implementation "net.neoforged:neoforge:${neo_version}" + compileOnly "com.blamejared.crafttweaker:CraftTweaker-neoforge-${minecraft_version}:${crafttweaker_version}" + // Example optional mod dependency with JEI + // The JEI API is declared for compile time use, while the full JEI artifact is used at runtime + // compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}" + // compileOnly "mezz.jei:jei-${mc_version}-neoforge-api:${jei_version}" + // We add the full version to localRuntime, not runtimeOnly, so that we do not publish a dependency on it + // localRuntime "mezz.jei:jei-${mc_version}-neoforge:${jei_version}" + + // Example mod dependency using a mod jar from ./libs with a flat dir repository + // This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar + // The group id is ignored when searching -- in this case, it is "blank" + // implementation "blank:coolmod-${mc_version}:${coolmod_version}" + + // Example mod dependency using a file as dependency + // implementation files("libs/coolmod-${mc_version}-${coolmod_version}.jar") + + // Example project dependency using a sister or child project: + // implementation project(":myproject") + + // For more info: + // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html + // http://www.gradle.org/docs/current/userguide/dependency_management.html +} + +// This block of code expands all declared replace properties in the specified resource targets. +// A missing property will result in an error. Properties are expanded using ${} Groovy notation. +// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments. +// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html +tasks.withType(ProcessResources).configureEach { + var replaceProperties = [ + minecraft_version : minecraft_version, + minecraft_version_range: minecraft_version_range, + neo_version : neo_version, + neo_version_range : neo_version_range, + loader_version_range : loader_version_range, + mod_id : mod_id, + mod_name : mod_name, + mod_license : mod_license, + mod_version : mod_version, + mod_authors : mod_authors, + mod_description : mod_description + ] + inputs.properties replaceProperties + + filesMatching(['META-INF/neoforge.mods.toml']) { + expand replaceProperties + } +} + +// Example configuration to allow publishing using the maven-publish plugin +publishing { + publications { + register('mavenJava', MavenPublication) { + from components.java + } + } + repositories { + maven { + url "file://${project.projectDir}/repo" + } + } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation +} + +// IDEA no longer automatically downloads sources/javadoc jars for dependencies, so we need to explicitly enable the behavior. +idea { + module { + downloadSources = true + downloadJavadoc = true + } +} diff --git a/gradle.properties b/gradle.properties index 3fb922e..4394fab 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,24 +1,45 @@ -archivesBaseName = OreSpawn +# Sets default memory used for gradle commands. Can be overridden by user or command line properties. +org.gradle.jvmargs=-Xmx1G +org.gradle.daemon=false +org.gradle.debug=false -mc_version=1.12 -top_mc_version=1.11 -ccl_version=2.4.3.165 -ccc_version=2.3.5.93 -nei_version=2.1.2.175 -//jei_version=3.10.0.268 -//jei_version=3.12.8.328 -//jei_version=3.13.6.389 -jei_version=+ -mantle_version=1.1.3.199 -tconstruct_version=2.6.1.464 -mcmp_version=1.2.1 -//mcmp_version=1.3.0 -mcmp_experimental_version=2.0.0_88 -top_version=1.3.3-46 -orespawn_version=3.1.0+ -tesla_version=1.2.1.50 -bme_version=2.5.0-beta1 -mme_version=0.11.0 -fme_version=0.11.0 -bmi_version=0.11.0 -pa_version=2.3.0 \ No newline at end of file +#read more on this at https://github.com/neoforged/NeoGradle/blob/NG_7.0/README.md#apply-parchment-mappings +# you can also find the latest versions at: https://parchmentmc.org/docs/getting-started +neogradle.subsystems.parchment.minecraftVersion=1.20.6 +neogradle.subsystems.parchment.mappingsVersion=2024.06.16 +# Environment Properties +# You can find the latest versions here: https://projects.neoforged.net/neoforged/neoforge +# The Minecraft version must agree with the Neo version to get a valid artifact +minecraft_version=1.20.6 +# The Minecraft version range can use any release version of Minecraft as bounds. +# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly +# as they do not follow standard versioning conventions. +minecraft_version_range=[1.20.6,1.21) +# The Neo version must agree with the Minecraft version to get a valid artifact +neo_version=20.6.119 +# The Neo version range can use any version of Neo as bounds +neo_version_range=[20.6,) +# The loader version range can only use the major version of FML as bounds +loader_version_range=[2,) + +## Mod Properties + +# The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63} +# Must match the String constant located in the main mod class annotated with @Mod. +mod_id=mmdorespawn +# The human-readable display name for the mod. +mod_name=MMD OreSpawn +# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default. +mod_license=All Rights Reserved +# The mod version. See https://semver.org/ +mod_version=4.0.0 +# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository. +# This should match the base package used for the mod sources. +# See https://maven.apache.org/guides/mini/guide-naming-conventions.html +mod_group_id=com.mcmoddev.orespawn +# The authors of the mod. This is a simple text string that is used for display purposes in the mod list. +mod_authors=DShadowWolf, jriwanek, Cyanobacterium +# The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list. +mod_description=Continuation (rewrite) of an old 1.12.2 mod, implements a batch of feature providers + +crafttweaker_version=19.0.12 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 0d4a951..2c35211 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index a95009c..cea7a79 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index cccdd3d..f5feea6 100755 --- a/gradlew +++ b/gradlew @@ -1,78 +1,130 @@ -#!/usr/bin/env sh +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -81,92 +133,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=$((i+1)) + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" fi +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index e95643d..9b42019 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,4 +1,22 @@ -@if "%DEBUG%" == "" @echo off +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -9,25 +27,29 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -35,48 +57,36 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/settings.gradle b/settings.gradle index 0e64f4a..ada876e 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1,11 @@ -rootProject.name = archivesBaseName -enableFeaturePreview('STABLE_PUBLISHING') +pluginManagement { + repositories { + mavenLocal() + gradlePluginPortal() + maven { url = 'https://maven.neoforged.net/releases' } + } +} + +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0' +} diff --git a/src/main/java/com/mcmoddev/orespawn/EventHandlers.java b/src/main/java/com/mcmoddev/orespawn/EventHandlers.java deleted file mode 100644 index bcaaadf..0000000 --- a/src/main/java/com/mcmoddev/orespawn/EventHandlers.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.mcmoddev.orespawn; - -import java.util.Arrays; -import java.util.Deque; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.TreeMap; -import java.util.concurrent.ConcurrentLinkedDeque; -import java.util.stream.Collectors; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.collect.MapDifference; -import com.google.common.collect.Maps; -import com.mcmoddev.orespawn.data.Config; -import com.mcmoddev.orespawn.data.Constants; -import com.mcmoddev.orespawn.worldgen.OreSpawnFeatureGenerator; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.Tuple; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.gen.ChunkProviderServer; -import net.minecraft.world.gen.IChunkGenerator; -import net.minecraftforge.event.terraingen.OreGenEvent; -import net.minecraftforge.event.terraingen.OreGenEvent.GenerateMinable.EventType; -import net.minecraftforge.event.world.ChunkDataEvent; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.ObfuscationReflectionHelper; -import net.minecraftforge.fml.common.eventhandler.Event; -import net.minecraftforge.fml.common.eventhandler.EventPriority; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; -import net.minecraftforge.fml.common.gameevent.TickEvent.WorldTickEvent; -import net.minecraftforge.fml.relauncher.Side; - -public class EventHandlers { - - private final Deque retroChunks; - private final Deque>> chunks; - // private Map> chunks - - EventHandlers() { - retroChunks = new ConcurrentLinkedDeque<>(); - chunks = new ConcurrentLinkedDeque<>(); - } - - private final List vanillaEvents = Arrays.asList(EventType.ANDESITE, EventType.COAL, - EventType.DIAMOND, EventType.DIORITE, EventType.DIRT, EventType.EMERALD, EventType.GOLD, - EventType.GRANITE, EventType.GRAVEL, EventType.IRON, EventType.LAPIS, - EventType.REDSTONE, EventType.QUARTZ, EventType.SILVERFISH); - - @SubscribeEvent(priority = EventPriority.HIGHEST, receiveCanceled = true) - public void onGenerateMinable(final OreGenEvent.GenerateMinable event) { - if (Config.getBoolean(Constants.REPLACE_VANILLA_OREGEN) - && vanillaEvents.contains(event.getType())) { - event.setResult(Event.Result.DENY); - } else if(Config.getBoolean(Constants.REPLACE_ALL) && !Loader.instance().activeModContainer().getModId().equals("orespawn")) { - event.setResult(Event.Result.DENY); - } - } - - @SubscribeEvent - public void onChunkSave(final ChunkDataEvent.Save ev) { - final NBTTagCompound dataTag = ev.getData().getCompoundTag(Constants.CHUNK_TAG_NAME); - final NBTTagCompound features = new NBTTagCompound(); - - // save a list of the spawns that were configured and available - in this dimension - when - // the chunk - // was first generated. - - // collect that data - final int thisDimension = ev.getWorld().provider.getDimension(); - final BlockPos thisPos = new BlockPos(ev.getChunk().x + 8, 128, ev.getChunk().z + 8); - final Biome thisBiome = ev.getChunk().getBiome(thisPos, ev.getWorld().getBiomeProvider()); - - OreSpawn.API.getAllSpawns().entrySet().stream() - .filter(ent -> ent.getValue().dimensionAllowed(thisDimension)) - .filter(ent -> ent.getValue().biomeAllowed(thisBiome)).forEach(ent -> features - .setString(ent.getKey(), ent.getValue().getFeature().getFeatureName())); - dataTag.setTag(Constants.FEATURES_TAG, features); - - ev.getData().setTag(Constants.CHUNK_TAG_NAME, dataTag); - } - - private boolean dequeContains(final ChunkPos cc) { - return chunks.stream().map(tup -> tup.getFirst().equals(cc)).collect(Collectors.toList()) - .contains(true); - } - - @SubscribeEvent - public void onChunkLoad(final ChunkDataEvent.Load ev) { - final World clWorld = ev.getWorld(); - final ChunkPos chunkCoords = new ChunkPos(ev.getChunk().x, ev.getChunk().z); - - doBedrockRetrogen(chunkCoords); - - if (dequeContains(chunkCoords)) { - return; - } - - if (Config.getBoolean(Constants.RETROGEN_KEY)) { - final NBTTagCompound chunkTag = ev.getData().getCompoundTag(Constants.CHUNK_TAG_NAME); - final int thisDimension = clWorld.provider.getDimension(); - final BlockPos thisPos = new BlockPos(ev.getChunk().x + 8, 128, ev.getChunk().z + 8); - final Biome thisBiome = ev.getChunk().getBiome(thisPos, clWorld.getBiomeProvider()); - - if (featuresAreDifferent(chunkTag, thisDimension, thisBiome) - || Config.getBoolean(Constants.FORCE_RETROGEN_KEY)) { - chunks.addLast(new Tuple<>(chunkCoords, - getDifferingTags(chunkTag, thisDimension, thisBiome))); - } - } - } - - private List getDifferingTags(final NBTTagCompound chunkTag, final int dim, - final Biome biome) { - final NBTTagCompound tagList = chunkTag.getCompoundTag(Constants.FEATURES_TAG); - final Map currentBits = new TreeMap<>(); - final Map oldBits = new TreeMap<>(); - - OreSpawn.API.getAllSpawns().entrySet().stream() - .filter(ent -> ent.getValue().dimensionAllowed(dim)) - .filter(ent -> ent.getValue().biomeAllowed(biome)).forEach(ent -> currentBits - .put(ent.getKey(), ent.getValue().getFeature().getFeatureName())); - - tagList.getKeySet().stream().forEach(tag -> oldBits.put(tag, tagList.getString(tag))); - - final MapDifference diff = Maps.difference(oldBits, currentBits); - - final List stuff = Lists.newLinkedList(); - stuff.addAll(diff.entriesDiffering().entrySet().stream().map(Map.Entry::getKey) - .collect(Collectors.toList())); - stuff.addAll(diff.entriesOnlyOnRight().entrySet().stream().map(Map.Entry::getKey) - .collect(Collectors.toList())); - return ImmutableList.copyOf(stuff); - } - - private boolean featuresAreDifferent(final NBTTagCompound chunkTag, final int dim, - final Biome biome) { - final NBTTagCompound tagList = chunkTag.getCompoundTag(Constants.FEATURES_TAG); - final Map currentBits = new TreeMap<>(); - final Map oldBits = new TreeMap<>(); - - OreSpawn.API.getAllSpawns().entrySet().stream() - .filter(ent -> ent.getValue().dimensionAllowed(dim)) - .filter(ent -> ent.getValue().biomeAllowed(biome)).forEach(ent -> currentBits - .put(ent.getKey(), ent.getValue().getFeature().getFeatureName())); - - tagList.getKeySet().stream().forEach(tag -> oldBits.put(tag, tagList.getString(tag))); - - final MapDifference diff = Maps.difference(oldBits, currentBits); - - return diff.entriesDiffering().size() == 0 && diff.entriesOnlyOnLeft().size() == 0 - && diff.entriesOnlyOnRight().size() == 0; - } - - private void doBedrockRetrogen(final ChunkPos chunkCoords) { - if (retroChunks.contains(chunkCoords)) { - return; - } - - if (Config.getBoolean(Constants.RETRO_BEDROCK)) { - retroChunks.addLast(chunkCoords); - } - } - - private static World world; - private static ChunkProviderServer chunkProvider; - private static IChunkGenerator chunkGenerator; - private static Random random; - - private static void setupData(final World nw) { - if (world == null || !world.equals(nw)) { - world = nw; - } - - if (chunkProvider == null || !chunkProvider.equals(nw.getChunkProvider())) { - chunkProvider = (ChunkProviderServer) nw.getChunkProvider(); - } - - if (chunkGenerator == null) { - chunkGenerator = ObfuscationReflectionHelper.getPrivateValue(ChunkProviderServer.class, - chunkProvider, "field_186029_c", "chunkGenerator"); - } - - if (random == null) { - random = new Random(world.getSeed()); - } - - } - - private OreSpawnFeatureGenerator findSpawn(final String spawnName) { - for (OreSpawnFeatureGenerator ofg : OreSpawn.API.getGenerators()) { - if (ofg.getSpawnName().matches(spawnName)) return ofg; - } - return null; - } - - private void runBits(final Tuple> tup, World world) { - final ChunkPos p = tup.getFirst(); - final List spawns = tup.getSecond(); - if(!world.isBlockLoaded(new BlockPos(p.getXStart(), 128, p.getZStart()))) { - chunks.add(tup); - return; - } - // re-seed with something totally new :P - random.setSeed((((random.nextLong() >> 4 + 1) + p.x) + ((random.nextLong() >> 2 + 1) + p.z)) - ^ world.getSeed()); - spawns.stream().forEach(s -> { - OreSpawnFeatureGenerator feature = findSpawn(s); - if (feature != null) feature.generate(random, p.x, p.z, world, chunkGenerator, chunkProvider); - }); - } - - @SubscribeEvent - public void worldTick(final WorldTickEvent ev) { - setupData(ev.world); - - if (ev.side != Side.SERVER) { - return; - } - - if (ev.phase == Phase.END) { - int chunkCount = chunks.size(); - for (int c = 0; c < 25 && !chunks.isEmpty(); c++) { - Tuple> pp = chunks.pop(); - if(ev.world.isBlockLoaded(new BlockPos(pp.getFirst().getXStart(), 128, pp.getFirst().getZStart()))) { - runBits(pp, ev.world); - } else { - chunks.add(pp); - c--; - } - chunkCount--; - if (chunkCount <= 0) { - break; - } - } - - chunkCount = retroChunks.size(); - for (int c = 0; c < 25 && !retroChunks.isEmpty(); c++) { - final ChunkPos p = retroChunks.pop(); - if(ev.world.isBlockLoaded(new BlockPos(p.getXStart(), 128, p.getZStart()))) { - OreSpawn.flatBedrock.retrogen(world, p.x, p.z); - } else { - c--; - retroChunks.add(p); - } - chunkCount--; - if (chunkCount <= 0) { - break; - } - } - } - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/OreSpawn.java b/src/main/java/com/mcmoddev/orespawn/OreSpawn.java index f0c6bad..f19a48b 100644 --- a/src/main/java/com/mcmoddev/orespawn/OreSpawn.java +++ b/src/main/java/com/mcmoddev/orespawn/OreSpawn.java @@ -1,100 +1,35 @@ package com.mcmoddev.orespawn; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import com.mcmoddev.orespawn.api.os3.OS3API; -import com.mcmoddev.orespawn.api.plugin.PluginLoader; -import com.mcmoddev.orespawn.commands.AddOreCommand; -import com.mcmoddev.orespawn.commands.ClearChunkCommand; -import com.mcmoddev.orespawn.commands.DumpBiomesCommand; -import com.mcmoddev.orespawn.commands.WriteConfigsCommand; -import com.mcmoddev.orespawn.data.Config; -import com.mcmoddev.orespawn.data.Constants; -import com.mcmoddev.orespawn.data.FeatureRegistry; -import com.mcmoddev.orespawn.impl.os3.OS3APIImpl; -import com.mcmoddev.orespawn.worldgen.FlatBedrock; -import com.mcmoddev.orespawn.worldgen.OreSpawnFeatureGenerator; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.common.Mod.EventHandler; -import net.minecraftforge.fml.common.Mod.Instance; -import net.minecraftforge.fml.common.event.FMLFingerprintViolationEvent; -import net.minecraftforge.fml.common.event.FMLInitializationEvent; -import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; -import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.fml.common.event.FMLServerStartingEvent; -import net.minecraftforge.fml.common.registry.GameRegistry; - -/** - * Main entry point for the mod, everything runs through this. - * - * @author DShadowWolf <dshadowwolf@gmail.com> - */ - -@Mod(modid = Constants.MODID, - name = Constants.NAME, - version = Constants.VERSION, - acceptedMinecraftVersions = "[1.12,)", - certificateFingerprint = "@FINGERPRINT@") - -public class OreSpawn { - - @Instance - public static OreSpawn instance; - - public static final Logger LOGGER = LogManager.getLogger(Constants.MODID); - public static final OS3API API = new OS3APIImpl(); - static final EventHandlers eventHandlers = new EventHandlers(); - public static final FeatureRegistry FEATURES = new FeatureRegistry(); - - static final FlatBedrock flatBedrock = new FlatBedrock(); - - @EventHandler - public void onFingerprintViolation(final FMLFingerprintViolationEvent event) { - LOGGER.warn("Invalid fingerprint detected!"); - } - - @EventHandler - public void preInit(final FMLPreInitializationEvent ev) { - Config.loadConfig(); - - PluginLoader.INSTANCE.load(ev); - - if (Config.getBoolean(Constants.FLAT_BEDROCK)) { - GameRegistry.registerWorldGenerator(flatBedrock, 100); - } - - if (Config.getBoolean(Constants.RETROGEN_KEY) - || Config.getBoolean(Constants.REPLACE_VANILLA_OREGEN) - || Config.getBoolean(Constants.RETRO_BEDROCK)) { - MinecraftForge.EVENT_BUS.register(eventHandlers); - MinecraftForge.ORE_GEN_BUS.register(eventHandlers); - } - } - - @EventHandler - public void init(final FMLInitializationEvent ev) { - PluginLoader.INSTANCE.register(); - - API.loadConfigFiles(); - } - - @EventHandler - public void postInit(final FMLPostInitializationEvent ev) { - Config.saveConfig(); - API.getAllSpawns().entrySet().stream() - .forEach(ent -> { - GameRegistry.registerWorldGenerator(new OreSpawnFeatureGenerator(ent.getValue(), ent.getKey()), 100); - }); - } - - @EventHandler - public void onServerStarting(final FMLServerStartingEvent ev) { - ev.registerServerCommand(new ClearChunkCommand()); - ev.registerServerCommand(new DumpBiomesCommand()); - ev.registerServerCommand(new AddOreCommand()); - ev.registerServerCommand(new WriteConfigsCommand()); - } +import com.mcmoddev.orespawn.features.NormalCloud; +import com.mcmoddev.orespawn.features.VeinFeature; +import net.minecraft.world.level.levelgen.feature.Feature; +import org.slf4j.Logger; + +import com.mojang.logging.LogUtils; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; + +// The value here should match an entry in the META-INF/neoforge.mods.toml file +@Mod(OreSpawn.MODID) +public class OreSpawn +{ + // Define mod id in a common place for everything to reference + public static final String MODID = "mmdorespawn"; + // Directly reference a slf4j logger + public static final Logger LOGGER = LogUtils.getLogger(); + public static final DeferredRegister> FEATURE = DeferredRegister.create(BuiltInRegistries.FEATURE, MODID); + public static final DeferredHolder, Feature> VEIN_FEATURE = FEATURE.register("mmdos4_vein", VeinFeature::new); + public static final DeferredHolder, Feature> NORMAL_CLOUD_FEATURE = FEATURE.register("mmdos4_normal_cloud", NormalCloud::new); + public static final DeferredHolder, Feature> CLUSTERS_FEATURE = FEATURE.register("mmdos4_clusters", NormalCloud::new); + + // The constructor for the mod class is the first code that is run when your mod is loaded. + // FML will recognize some parameter types like IEventBus or ModContainer and pass them in automatically. + public OreSpawn(IEventBus modEventBus, ModContainer modContainer) { + FEATURE.register(modEventBus); + } } diff --git a/src/main/java/com/mcmoddev/orespawn/api/BiomeLocation.java b/src/main/java/com/mcmoddev/orespawn/api/BiomeLocation.java deleted file mode 100644 index 6870c78..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/BiomeLocation.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.mcmoddev.orespawn.api; - -import com.google.common.collect.ImmutableList; -import com.google.gson.JsonElement; -import com.mcmoddev.orespawn.util.Collectors2; - -import net.minecraft.world.biome.Biome; -import net.minecraftforge.fml.common.registry.ForgeRegistries; - -public interface BiomeLocation { - - boolean matches(Biome biome); - - JsonElement serialize(); - - default ImmutableList getBiomes() { - return ForgeRegistries.BIOMES.getValuesCollection().stream().filter(this::matches) - .collect(Collectors2.toImmutableList()); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/FeatureBase.java b/src/main/java/com/mcmoddev/orespawn/api/FeatureBase.java deleted file mode 100644 index 5b067d6..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/FeatureBase.java +++ /dev/null @@ -1,314 +0,0 @@ -package com.mcmoddev.orespawn.api; - -import java.util.Collections; -import java.util.Deque; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Random; - -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.os3.ISpawnEntry; -import com.mcmoddev.orespawn.api.os3.OreSpawnBlockMatcher; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.init.Blocks; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.Vec3i; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; -import net.minecraftforge.registries.IForgeRegistryEntry; - -public class FeatureBase extends IForgeRegistryEntry.Impl { - - private static final int MAX_CACHE_SIZE = 2048; - /** - * overflow cache so that ores that spawn at edge of chunk can appear in the neighboring chunk - * without triggering a chunk-load. - */ - private static final Map> overflowCache = new HashMap<>( - MAX_CACHE_SIZE); - private static final Deque cacheOrder = new LinkedList<>(); - protected Random random; - - public FeatureBase(final Random rand) { - this.random = rand; - } - - public boolean isValidBlock(final IBlockState oreBlock) { - return oreBlock.getBlock() != Blocks.AIR; - } - - protected void runCache(final int chunkX, final int chunkZ, final World world, - final ISpawnEntry spawnData) { - final Vec3i chunkCoord = new Vec3i(chunkX, chunkZ, world.provider.getDimension()); - final Map cache = retrieveCache(chunkCoord); - - if (!cache.isEmpty()) { // if there is something in the cache, try to spawn it - for (final Entry ent : cache.entrySet()) { - spawnNoCheck(cache.get(ent.getKey()), world, ent.getKey(), - world.provider.getDimension(), spawnData); - } - } - } - - protected boolean spawn(final IBlockState oreBlock, final World world, final BlockPos coord, - final int dimension, final boolean cacheOverflow, final ISpawnEntry spawnData) { - if (oreBlock == null) { - OreSpawn.LOGGER.fatal("FeatureBase.spawn() called with a null ore!"); - return false; - } - - if (!isValidBlock(oreBlock)) { - return false; - } - - final Biome thisBiome = world.getBiome(coord); - - if (!spawnData.biomeAllowed(thisBiome.getRegistryName())) { - return false; - } - - final BlockPos np = mungeFixYcoord(coord); - - if (coord.getY() >= world.getHeight()) { - OreSpawn.LOGGER.warn("Asked to spawn {} above build limit at {}", oreBlock, coord); - return false; - } - - return spawnOrCache(world, np, spawnData.getMatcher(), oreBlock, cacheOverflow, dimension, - spawnData); - } - - private BlockPos mungeFixYcoord(final BlockPos coord) { - if (coord.getY() < 0) { - final int newYCoord = coord.getY() * -1; - return new BlockPos(coord.getX(), newYCoord, coord.getZ()); - } else { - return new BlockPos(coord); - } - } - - private boolean spawnOrCache(final World world, final BlockPos coord, - final OreSpawnBlockMatcher replacer, final IBlockState oreBlock, - final boolean cacheOverflow, final int dimension, final ISpawnEntry spawnData) { - if (world.isBlockLoaded(coord)) { - boolean x_bad = false; - boolean z_bad = false; - ChunkPos start = world.getChunk(coord).getPos(); - ChunkPos end = new ChunkPos(start.x+1, start.z+1); - if (coord.getX() < start.getXStart() || coord.getX() > end.getXEnd()) x_bad = true; - if (coord.getZ() < start.getZStart() || coord.getZ() > end.getZEnd()) z_bad = true; - - if(x_bad || z_bad) { - if(cacheOverflow) { - cacheOverflowBlock(oreBlock, coord, dimension); - return true; - } else { - return false; - } - } - if (!isValidBlock(oreBlock)) { - return false; - } - - final IBlockState targetBlock = world.getBlockState(coord); - final Biome thisBiome = world.getBiome(coord); - - if (replacer.test(targetBlock) && spawnData.biomeAllowed(thisBiome.getRegistryName())) { - // don't send block update, send to client, don't re-render, observers don't see the change - world.setBlockState(coord, oreBlock, 0x16); - return true; - } else { - return false; - } - } else if (cacheOverflow) { - cacheOverflowBlock(oreBlock, coord, dimension); - return true; - } - - return false; - } - - private void spawnNoCheck(final IBlockState oreBlock, final World world, final BlockPos coord, - final int dimension, final ISpawnEntry spawnData) { - if (oreBlock == null) { - OreSpawn.LOGGER.fatal("FeatureBase.spawn() called with a null ore!"); - return; - } - - final BlockPos np = mungeFixYcoord(coord); - - if (coord.getY() >= world.getHeight()) { - OreSpawn.LOGGER.warn("Asked to spawn {} above build limit at {}", oreBlock, coord); - return; - } - - spawnOrCache(world, np, spawnData.getMatcher(), oreBlock, false, dimension, spawnData); - } - - private void cacheOverflowBlock(final IBlockState bs, final BlockPos coord, - final int dimension) { - final Vec3i chunkCoord = new Vec3i(coord.getX() / 16, coord.getY() / 16, dimension); - - if (overflowCache.containsKey(chunkCoord)) { - cacheOrder.addLast(chunkCoord); - - if (cacheOrder.size() > MAX_CACHE_SIZE) { - final Vec3i drop = cacheOrder.removeFirst(); - overflowCache.get(drop).clear(); - overflowCache.remove(drop); - } - - overflowCache.put(chunkCoord, new HashMap<>()); - } - - final Map cache = overflowCache.getOrDefault(chunkCoord, - new HashMap<>()); - cache.put(coord, bs); - } - - private Map retrieveCache(final Vec3i chunkCoord) { - if (overflowCache.containsKey(chunkCoord)) { - final Map cache = overflowCache.get(chunkCoord); - cacheOrder.remove(chunkCoord); - overflowCache.remove(chunkCoord); - return cache; - } else { - return Collections.emptyMap(); - } - } - - protected void scramble(final int[] target, final Random prng) { - for (int i = target.length - 1; i > 0; i--) { - final int n = prng.nextInt(i); - final int temp = target[i]; - target[i] = target[n]; - target[n] = temp; - } - } - - protected static final Vec3i[] offsets_small = { - new Vec3i(0, 0, 0), new Vec3i(1, 0, 0), new Vec3i(0, 1, 0), new Vec3i(1, 1, 0), - - new Vec3i(0, 0, 1), new Vec3i(1, 0, 1), new Vec3i(0, 1, 1), new Vec3i(1, 1, 1) - }; - - protected static final Vec3i[] offsets = { - new Vec3i(-1, -1, -1), new Vec3i(0, -1, -1), new Vec3i(1, -1, -1), new Vec3i(-1, 0, -1), - new Vec3i(0, 0, -1), new Vec3i(1, 0, -1), new Vec3i(-1, 1, -1), new Vec3i(0, 1, -1), - new Vec3i(1, 1, -1), - - new Vec3i(-1, -1, 0), new Vec3i(0, -1, 0), new Vec3i(1, -1, 0), new Vec3i(-1, 0, 0), - new Vec3i(0, 0, 0), new Vec3i(1, 0, 0), new Vec3i(-1, 1, 0), new Vec3i(0, 1, 0), - new Vec3i(1, 1, 0), - - new Vec3i(-1, -1, 1), new Vec3i(0, -1, 1), new Vec3i(1, -1, 1), new Vec3i(-1, 0, 1), - new Vec3i(0, 0, 1), new Vec3i(1, 0, 1), new Vec3i(-1, 1, 1), new Vec3i(0, 1, 1), - new Vec3i(1, 1, 1) - }; - - protected static final int[] offsetIndexRef = { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26 - }; - protected static final int[] offsetIndexRef_small = { - 0, 1, 2, 3, 4, 5, 6, 7 - }; - - protected static void mergeDefaults(final JsonObject parameters, - final JsonObject defaultParameters) { - defaultParameters.entrySet().forEach(entry -> { - if (!parameters.has(entry.getKey())) { - parameters.add(entry.getKey(), entry.getValue()); - } - }); - } - - private double triangularDistribution(final double a, final double b, final double c) { - final double base = (c - a) / (b - a); - final double rand = this.random.nextDouble(); - - if (rand < base) { - return a + Math.sqrt(rand * (b - a) * (c - a)); - } else { - return b - Math.sqrt((1 - rand) * (b - a) * (b - c)); - } - } - - protected int getPoint(final int lowerBound, final int upperBound, final int median) { - final int t = (int) Math.round( - triangularDistribution((float) lowerBound, (float) upperBound, (float) median)); - return t - median; - } - - protected void spawnMungeInner(final Random prng, final int rSqr, int quantity, - final Vec3i vals, final ISpawnEntry spawnData, final World world, final BlockPos blockPos) { - int dx = vals.getX(); - int dy = vals.getY(); - int dz = vals.getZ(); - final IBlockList possibleOres = spawnData.getBlocks(); - final OreSpawnBlockMatcher replacer = spawnData.getMatcher(); - - if ((dx * dx + dy * dy + dz * dz) <= rSqr) { - final IBlockState oreBlock = possibleOres.getRandomBlock(prng); - if (oreBlock.getBlock().equals(net.minecraft.init.Blocks.AIR)) return; - spawnOrCache(world, blockPos.add(dx, dy, dz), replacer, oreBlock, true, - world.provider.getDimension(), spawnData); - quantity--; - } - } - - protected void spawnMungeSW(final World world, final BlockPos blockPos, final int rSqr, - final double radius, final ISpawnEntry spawnData, final int count) { - final Random prng = this.random; - int quantity = count; - for (int dy = (int) (-1 * radius); dy < radius; dy++) { - for (int dx = (int) (radius); dx >= (int) (-1 * radius); dx--) { - for (int dz = (int) (radius); dz >= (int) (-1 * radius); dz--) { - spawnMungeInner(prng, rSqr, quantity, new Vec3i(dx,dy,dz), spawnData, world, blockPos); - if (quantity <= 0) { - return; - } - } - } - } - } - - protected void spawnMungeNE(final World world, final BlockPos blockPos, final int rSqr, - final double radius, final ISpawnEntry spawnData, final int count) { - final Random prng = this.random; - int quantity = count; -// final IBlockList possibleOres = spawnData.getBlocks(); -// final OreSpawnBlockMatcher replacer = spawnData.getMatcher(); - for (int dy = (int) (-1 * radius); dy < radius; dy++) { - for (int dz = (int) (-1 * radius); dz < radius; dz++) { - for (int dx = (int) (-1 * radius); dx < radius; dx++) { - spawnMungeInner(prng, rSqr, quantity, new Vec3i(dx,dy,dz), spawnData, world, blockPos); - if (quantity <= 0) { - return; - } - } - } - } - } - - protected int getABC(final int dx, final int dy, final int dz) { - return (dx * dx + dy * dy + dz * dz); - } - - protected int countItem(final int dx, final boolean toPositive) { - return toPositive ? dx + 1 : dx - 1; - } - - protected boolean endCheck(final boolean toPositive, final int dx, final double radius) { - return toPositive ? (dx >= getStart(toPositive, radius)) : (dx < radius); - } - - protected int getStart(final boolean toPositive, final double radius) { - return ((int) (radius * (toPositive ? 1 : -1))); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/IBlockList.java b/src/main/java/com/mcmoddev/orespawn/api/IBlockList.java deleted file mode 100644 index 26e12bb..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/IBlockList.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.mcmoddev.orespawn.api; - -import java.util.Random; - -import com.mcmoddev.orespawn.api.os3.IBlockDefinition; - -import net.minecraft.block.state.IBlockState; - -public interface IBlockList { - - void addBlock(IBlockDefinition block); - - IBlockState getRandomBlock(Random rand); - - void startNewSpawn(); - - void dump(); - - int count(); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/IDimensionList.java b/src/main/java/com/mcmoddev/orespawn/api/IDimensionList.java deleted file mode 100644 index 1156481..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/IDimensionList.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.mcmoddev.orespawn.api; - -import com.google.gson.JsonObject; - -public interface IDimensionList { - - JsonObject serialize(); - - default boolean matches(int dimensionId) { - return false; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/IFeature.java b/src/main/java/com/mcmoddev/orespawn/api/IFeature.java deleted file mode 100644 index 82f04a6..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/IFeature.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.mcmoddev.orespawn.api; - -import java.util.Random; - -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.api.os3.ISpawnEntry; - -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; -import net.minecraftforge.registries.IForgeRegistryEntry; - -public interface IFeature extends IForgeRegistryEntry { - - void generate(World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider, - ISpawnEntry spawn, ChunkPos pos); - - void setRandom(Random rand); - - JsonObject getDefaultParameters(); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/exceptions/BadStateValueException.java b/src/main/java/com/mcmoddev/orespawn/api/exceptions/BadStateValueException.java deleted file mode 100755 index 0192989..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/exceptions/BadStateValueException.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.mcmoddev.orespawn.api.exceptions; - -public class BadStateValueException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 3826628238012469423L; - - public BadStateValueException(String msg) { - super(msg); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/exceptions/BadValueException.java b/src/main/java/com/mcmoddev/orespawn/api/exceptions/BadValueException.java deleted file mode 100644 index a71123f..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/exceptions/BadValueException.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.mcmoddev.orespawn.api.exceptions; - -import java.util.Locale; - -public class BadValueException extends Exception { - - private static final long serialVersionUID = 1143938140559149506L; - private final String keyName; - private final String keyValue; - - public BadValueException(final String keyName, final String keyValue) { - super(); - this.keyName = keyName; - this.keyValue = keyValue; - } - - @Override - public String getMessage() { - final String baseMessage = super.getMessage(); - return String.format(Locale.ENGLISH, "Unknown value %s for key %s%n%s", this.keyValue, this.keyName, - baseMessage); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/exceptions/MissingVersionException.java b/src/main/java/com/mcmoddev/orespawn/api/exceptions/MissingVersionException.java deleted file mode 100644 index 8c98fff..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/exceptions/MissingVersionException.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.mcmoddev.orespawn.api.exceptions; - -public class MissingVersionException extends Exception { - - /** - * - */ - private static final long serialVersionUID = -4306852267351590384L; - -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/exceptions/NotAProperConfigException.java b/src/main/java/com/mcmoddev/orespawn/api/exceptions/NotAProperConfigException.java deleted file mode 100644 index 2f31a43..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/exceptions/NotAProperConfigException.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.mcmoddev.orespawn.api.exceptions; - -public class NotAProperConfigException extends Exception { - - /** - * - */ - private static final long serialVersionUID = -7748241590958198482L; - -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/exceptions/OldVersionException.java b/src/main/java/com/mcmoddev/orespawn/api/exceptions/OldVersionException.java deleted file mode 100644 index 62b5fa7..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/exceptions/OldVersionException.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.mcmoddev.orespawn.api.exceptions; - -public class OldVersionException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 3760017140789193369L; - -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/exceptions/UnknownFieldException.java b/src/main/java/com/mcmoddev/orespawn/api/exceptions/UnknownFieldException.java deleted file mode 100644 index e6008d1..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/exceptions/UnknownFieldException.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.mcmoddev.orespawn.api.exceptions; - -import java.util.Locale; - -public class UnknownFieldException extends Exception { - - private static final long serialVersionUID = 1L; - private final String message; - - public UnknownFieldException(final String theField) { - super(); - this.message = String.format(Locale.ENGLISH, "Unkown field %s in config", theField); - } - - @Override - public String getMessage() { - final String baseMessage = super.getMessage(); - return String.format(Locale.ENGLISH, "%s%n%s", this.message, baseMessage); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/exceptions/UnknownNameException.java b/src/main/java/com/mcmoddev/orespawn/api/exceptions/UnknownNameException.java deleted file mode 100644 index 94bf09a..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/exceptions/UnknownNameException.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.mcmoddev.orespawn.api.exceptions; - -import java.util.Locale; - -public class UnknownNameException extends Exception { - - private static final long serialVersionUID = -3426121906665390773L; - private final String fieldName; - private final String fieldValue; - - public UnknownNameException(final String fieldName, final String fieldValue) { - super(); - this.fieldName = fieldName; - this.fieldValue = fieldValue; - } - - @Override - public String getMessage() { - final String baseMessage = super.getMessage(); - return String.format(Locale.ENGLISH, "Unknown %s name %s%n%s", this.fieldName, this.fieldValue, - baseMessage); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/exceptions/UnknownVersionException.java b/src/main/java/com/mcmoddev/orespawn/api/exceptions/UnknownVersionException.java deleted file mode 100644 index fa369ca..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/exceptions/UnknownVersionException.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.mcmoddev.orespawn.api.exceptions; - -public class UnknownVersionException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 3817238409227005355L; - -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/IBiomeBuilder.java b/src/main/java/com/mcmoddev/orespawn/api/os3/IBiomeBuilder.java deleted file mode 100644 index 1bda5db..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/IBiomeBuilder.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -import com.mcmoddev.orespawn.api.BiomeLocation; - -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.biome.Biome; - -public interface IBiomeBuilder { - - IBiomeBuilder addWhitelistEntry(Biome biome); - - IBiomeBuilder addWhitelistEntry(String biomeName); - - IBiomeBuilder addWhitelistEntry(ResourceLocation biomeResourceLocation); - - IBiomeBuilder addBlacklistEntry(Biome biome); - - IBiomeBuilder addBlacklistEntry(String biomeName); - - IBiomeBuilder addBlacklistEntry(ResourceLocation biomeResourceLocation); - - IBiomeBuilder setAcceptAll(); - - BiomeLocation create(); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/IBlockBuilder.java b/src/main/java/com/mcmoddev/orespawn/api/os3/IBlockBuilder.java deleted file mode 100644 index 54baec3..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/IBlockBuilder.java +++ /dev/null @@ -1,159 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.ResourceLocation; - -public interface IBlockBuilder { - - /** - * - * @param blockState - * @return - */ - IBlockBuilder setFromBlockState(IBlockState blockState); - - /** - * - * @param block - * @return - */ - IBlockBuilder setFromBlock(Block block); - - /** - * - * @param blockName - * @return - */ - IBlockBuilder setFromName(String blockName); - - /** - * - * @param blockName - * @param state - * @return - */ - IBlockBuilder setFromName(String blockName, String state); - - /** - * - * @param blockName - * @param metadata - * @return - * @deprecated - */ - @Deprecated - IBlockBuilder setFromName(String blockName, int metadata); - - /** - * - * @param blockResourceLocation - * @return - */ - IBlockBuilder setFromName(ResourceLocation blockResourceLocation); - - /** - * - * @param blockResourceLocation - * @param state - * @return - */ - IBlockBuilder setFromName(ResourceLocation blockResourceLocation, String state); - - /** - * - * @param blockResourceLocation - * @param metadata - * @return - * @deprecated - */ - @Deprecated - IBlockBuilder setFromName(ResourceLocation blockResourceLocation, int metadata); - - /** - * - * @param blockState - * @param chance - * @return - */ - IBlockBuilder setFromBlockStateWithChance(IBlockState blockState, int chance); - - /** - * - * @param block - * @param chance - * @return - */ - IBlockBuilder setFromBlockWithChance(Block block, int chance); - - /** - * - * @param blockName - * @param chance - * @return - */ - IBlockBuilder setFromNameWithChance(String blockName, int chance); - - /** - * - * @param blockName - * @param state - * @param chance - * @return - */ - IBlockBuilder setFromNameWithChance(String blockName, String state, int chance); - - /** - * - * @param blockName - * @param metadata - * @param chance - * @return - * @deprecated - */ - @Deprecated - IBlockBuilder setFromNameWithChance(String blockName, int metadata, int chance); - - /** - * - * @param blockResourceLocation - * @param chance - * @return - */ - IBlockBuilder setFromNameWithChance(ResourceLocation blockResourceLocation, int chance); - - /** - * - * @param blockResourceLocation - * @param state - * @param chance - * @return - */ - IBlockBuilder setFromNameWithChance(ResourceLocation blockResourceLocation, String state, - int chance); - - /** - * - * @param blockResourceLocation - * @param metadata - * @param chance - * @return - * @deprecated - */ - @Deprecated - IBlockBuilder setFromNameWithChance(ResourceLocation blockResourceLocation, int metadata, - int chance); - - /** - * - * @param chance - * @return - */ - IBlockBuilder setChance(int chance); - - /** - * - * @return - */ - IBlockDefinition create(); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/IBlockDefinition.java b/src/main/java/com/mcmoddev/orespawn/api/os3/IBlockDefinition.java deleted file mode 100644 index 03bec55..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/IBlockDefinition.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -import net.minecraft.block.state.IBlockState; - -public interface IBlockDefinition { - - IBlockState getBlock(); - - int getChance(); - - default boolean isValid() { - return true; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/IDimensionBuilder.java b/src/main/java/com/mcmoddev/orespawn/api/os3/IDimensionBuilder.java deleted file mode 100644 index 1fe97bb..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/IDimensionBuilder.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -import com.mcmoddev.orespawn.api.IDimensionList; - -public interface IDimensionBuilder { - - IDimensionBuilder addWhitelistEntry(int dimensionID); - - IDimensionBuilder addBlacklistEntry(int dimensionID); - - IDimensionBuilder setAcceptAll(); - - IDimensionBuilder setDenyAll(); - - IDimensionBuilder setAcceptAllOverworld(); - - IDimensionList create(); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/IFeatureBuilder.java b/src/main/java/com/mcmoddev/orespawn/api/os3/IFeatureBuilder.java deleted file mode 100644 index 20fefa2..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/IFeatureBuilder.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -import com.google.gson.JsonElement; -import com.mcmoddev.orespawn.api.IFeature; - -import net.minecraft.util.ResourceLocation; - -public interface IFeatureBuilder { - - IFeatureBuilder setFeature(String featureName); - - IFeatureBuilder setFeature(ResourceLocation featureResourceLocation); - - IFeatureBuilder setFeature(IFeature feature); - - IFeatureBuilder setParameter(String parameterName, String parameterValue); - - IFeatureBuilder setParameter(String parameterName, int parameterValue); - - IFeatureBuilder setParameter(String parameterName, float parameterValue); - - IFeatureBuilder setParameter(String parameterName, boolean parameterValue); - - IFeatureBuilder setParameter(String parameterName, JsonElement parameterValue); - - IFeatureBuilder setUseFeatureDefaults(); - - IFeatureEntry create(); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/IFeatureEntry.java b/src/main/java/com/mcmoddev/orespawn/api/os3/IFeatureEntry.java deleted file mode 100644 index 6f5fb06..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/IFeatureEntry.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.api.IFeature; - -public interface IFeatureEntry { - - IFeature getFeature(); - - String getFeatureName(); - - JsonObject getFeatureParameters(); - - void setParameter(String parameterName, String parameterValue); - - void setParameter(String parameterName, int parameterValue); - - void setParameter(String parameterName, boolean parameterValue); - - void setParameter(String parameterName, float parameterValue); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/IReplacementBuilder.java b/src/main/java/com/mcmoddev/orespawn/api/os3/IReplacementBuilder.java deleted file mode 100644 index ecf91e7..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/IReplacementBuilder.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.ResourceLocation; - -public interface IReplacementBuilder { - - /** - * - * @param entryName - * @return - */ - IReplacementBuilder setFromName(String entryName); - - /** - * - * @param name - * @return - */ - IReplacementBuilder setName(String name); - - /** - * - * @param blockState - * @return - */ - IReplacementBuilder addEntry(IBlockState blockState); - - /** - * - * @param blockName - * @return - */ - IReplacementBuilder addEntry(String blockName); - - /** - * - * @param blockName - * @param state - * @return - */ - IReplacementBuilder addEntry(String blockName, String state); - - /** - * - * @param blockName - * @param metadata - * @return - * @deprecated - */ - @Deprecated - IReplacementBuilder addEntry(String blockName, int metadata); - - /** - * - * @param blockResourceLocation - * @return - */ - IReplacementBuilder addEntry(ResourceLocation blockResourceLocation); - - /** - * - * @param blockResourceLocation - * @param state - * @return - */ - IReplacementBuilder addEntry(ResourceLocation blockResourceLocation, String state); - - /** - * - * @param blockResourceLocation - * @param metadata - * @return - * @deprecated - */ - @Deprecated - IReplacementBuilder addEntry(ResourceLocation blockResourceLocation, int metadata); - - boolean hasEntries(); - - IReplacementEntry create(); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/IReplacementEntry.java b/src/main/java/com/mcmoddev/orespawn/api/os3/IReplacementEntry.java deleted file mode 100644 index e9f03f9..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/IReplacementEntry.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -import java.util.List; - -import net.minecraft.block.state.IBlockState; -import net.minecraftforge.registries.IForgeRegistryEntry; - -public interface IReplacementEntry extends IForgeRegistryEntry { - - OreSpawnBlockMatcher getMatcher(); - - List getEntries(); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/ISpawnBuilder.java b/src/main/java/com/mcmoddev/orespawn/api/os3/ISpawnBuilder.java deleted file mode 100644 index 3808d61..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/ISpawnBuilder.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -import com.mcmoddev.orespawn.api.BiomeLocation; -import com.mcmoddev.orespawn.api.IDimensionList; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.ResourceLocation; - -public interface ISpawnBuilder { - - ISpawnBuilder setName(String name); - - ISpawnBuilder setDimensions(IDimensionList dimensions); - - ISpawnBuilder setBiomes(BiomeLocation biomes); - - ISpawnBuilder setEnabled(boolean enabled); - - ISpawnBuilder setRetrogen(boolean retrogen); - - ISpawnBuilder setReplacement(IReplacementEntry replacements); - - ISpawnBuilder setFeature(IFeatureEntry feature); - - ISpawnBuilder addBlock(String blockName); - - ISpawnBuilder addBlock(String blockName, String blockState); - - ISpawnBuilder addBlock(String blockName, int blockMetadata); - - ISpawnBuilder addBlock(ResourceLocation blockResourceLocation); - - ISpawnBuilder addBlock(ResourceLocation blockResourceLocation, String blockState); - - ISpawnBuilder addBlock(ResourceLocation blockResourceLocation, int blockMetadata); - - ISpawnBuilder addBlock(Block block); - - ISpawnBuilder addBlock(IBlockState block); - - ISpawnBuilder addBlockWithChance(String blockName, int chance); - - ISpawnBuilder addBlockWithChance(String blockName, String blockState, int chance); - - ISpawnBuilder addBlockWithChance(String blockName, int blockMetadata, int chance); - - ISpawnBuilder addBlockWithChance(ResourceLocation blockResourceLocation, int chance); - - ISpawnBuilder addBlockWithChance(ResourceLocation blockResourceLocation, String blockState, - int chance); - - ISpawnBuilder addBlockWithChance(ResourceLocation blockResourceLocation, int blockMetadata, - int chance); - - ISpawnBuilder addBlockWithChance(Block block, int chance); - - ISpawnBuilder addBlockWithChance(IBlockState block, int chance); - - ISpawnEntry create(); - - ISpawnBuilder addBlock(IBlockDefinition block); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/ISpawnEntry.java b/src/main/java/com/mcmoddev/orespawn/api/os3/ISpawnEntry.java deleted file mode 100644 index 7fdaceb..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/ISpawnEntry.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -import java.util.Random; - -import com.mcmoddev.orespawn.api.BiomeLocation; -import com.mcmoddev.orespawn.api.IBlockList; -import com.mcmoddev.orespawn.api.IDimensionList; - -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; - -public interface ISpawnEntry { - - default boolean isEnabled() { - return false; - } - - default boolean isRetrogen() { - return false; - } - - String getSpawnName(); - - boolean dimensionAllowed(int dimension); - - boolean biomeAllowed(ResourceLocation biomeName); - - boolean biomeAllowed(Biome biome); - - IFeatureEntry getFeature(); - - OreSpawnBlockMatcher getMatcher(); - - IBlockList getBlocks(); - - void generate(Random random, World world, IChunkGenerator chunkGenerator, - IChunkProvider chunkProvider, ChunkPos pos); - - IDimensionList getDimensions(); - - BiomeLocation getBiomes(); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/OS3API.java b/src/main/java/com/mcmoddev/orespawn/api/os3/OS3API.java deleted file mode 100644 index cc421f8..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/OS3API.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -import java.nio.file.Path; -import java.util.List; -import java.util.Map; - -import com.mcmoddev.orespawn.api.IFeature; -import com.mcmoddev.orespawn.data.PresetsStorage; -import com.mcmoddev.orespawn.worldgen.OreSpawnFeatureGenerator; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.ResourceLocation; - -public interface OS3API { - - void addSpawn(ISpawnEntry spawnEntry); - - void addFeature(String featureName, IFeature feature); - - void addReplacement(IReplacementEntry replacementEntry); - - Map getReplacements(); - - IReplacementEntry getReplacement(String replacementName); - - List getSpawns(int dimensionID); - - ISpawnEntry getSpawn(String spawnName); - - Map getAllSpawns(); - - List getDimensionDefaultReplacements(int dimensionID); - - ISpawnBuilder getSpawnBuilder(); - - IDimensionBuilder getDimensionBuilder(); - - IFeatureBuilder getFeatureBuilder(); - - IBlockBuilder getBlockBuilder(); - - IBiomeBuilder getBiomeBuilder(); - - IReplacementBuilder getReplacementBuilder(); - - boolean featureExists(String featureName); - - boolean featureExists(ResourceLocation featureName); - - IFeature getFeature(String featureName); - - IFeature getFeature(ResourceLocation featureName); - - PresetsStorage copyPresets(); - - void loadConfigFiles(); - - boolean hasReplacement(ResourceLocation resourceLocation); - - boolean hasReplacement(String name); - - void mapEntryToFile(Path p, String entryName); - - List getSpawnsForFile(String fileName); - - Map> getSpawnsByFile(); - - void addGenerator(final OreSpawnFeatureGenerator generator); - - List getGenerators(); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/OS3FeatureGenerator.java b/src/main/java/com/mcmoddev/orespawn/api/os3/OS3FeatureGenerator.java deleted file mode 100644 index d803f9d..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/OS3FeatureGenerator.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -public interface OS3FeatureGenerator { - public ISpawnEntry getSpawnData(); - public String getSpawnName(); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/OreSpawnBlockMatcher.java b/src/main/java/com/mcmoddev/orespawn/api/os3/OreSpawnBlockMatcher.java deleted file mode 100644 index 0c71641..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/OreSpawnBlockMatcher.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.mcmoddev.orespawn.api.os3; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.function.Predicate; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.data.Constants; -import com.mcmoddev.orespawn.util.StateUtil; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.init.Blocks; - -public class OreSpawnBlockMatcher implements Predicate { - - private final List possibles; - - public OreSpawnBlockMatcher(final IBlockState... matches) { - this.possibles = Arrays.asList(matches); - } - - public OreSpawnBlockMatcher(final List matches) { - this.possibles = new ArrayList<>(); - this.possibles.addAll(matches); - } - - private boolean has(final IBlockState bs) { - return this.possibles.stream().filter(bs::equals).count() > 0; - } - - public boolean test(final IBlockState other) { - return (!other.getBlock().equals(Blocks.AIR)) && this.has(other); - } - - public JsonArray serialize() { - final JsonArray rv = new JsonArray(); - - possibles.stream().forEach(bs -> { - final JsonObject t = new JsonObject(); - t.addProperty(Constants.ConfigNames.NAME, bs.getBlock().getRegistryName().toString()); - if (!bs.equals(bs.getBlock().getDefaultState())) { - final String state = StateUtil.serializeState(bs); - t.addProperty(Constants.ConfigNames.STATE, state); - } - rv.add(t); - }); - - return rv; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/os3/package-info.java b/src/main/java/com/mcmoddev/orespawn/api/os3/package-info.java deleted file mode 100644 index 3db5c1b..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/os3/package-info.java +++ /dev/null @@ -1,2 +0,0 @@ -@javax.annotation.ParametersAreNonnullByDefault -package com.mcmoddev.orespawn.api.os3; diff --git a/src/main/java/com/mcmoddev/orespawn/api/plugin/IOreSpawnPlugin.java b/src/main/java/com/mcmoddev/orespawn/api/plugin/IOreSpawnPlugin.java deleted file mode 100644 index d3b0bf7..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/plugin/IOreSpawnPlugin.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.mcmoddev.orespawn.api.plugin; - -import com.mcmoddev.orespawn.api.os3.OS3API; - -public interface IOreSpawnPlugin { - - void register(OS3API apiInterface); -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/plugin/OreSpawnPlugin.java b/src/main/java/com/mcmoddev/orespawn/api/plugin/OreSpawnPlugin.java deleted file mode 100644 index 7120c8b..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/plugin/OreSpawnPlugin.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.mcmoddev.orespawn.api.plugin; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -@Retention(RUNTIME) -@Target(TYPE) -public @interface OreSpawnPlugin { - - // the Mod this is for - will be used for - // generating the name of the json the config - // will get saved to and should also be the - // actual mod-id we can use for creating a - // resource location - String modid(); - - // resource location segment to look in - // for registered config files - - String resourcePath() default "orespawn"; -} diff --git a/src/main/java/com/mcmoddev/orespawn/api/plugin/PluginLoader.java b/src/main/java/com/mcmoddev/orespawn/api/plugin/PluginLoader.java deleted file mode 100644 index 7af04f4..0000000 --- a/src/main/java/com/mcmoddev/orespawn/api/plugin/PluginLoader.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.mcmoddev.orespawn.api.plugin; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.file.FileSystem; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.stream.Stream; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; - -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.data.Config; -import com.mcmoddev.orespawn.data.Constants; - -import net.minecraft.crash.CrashReport; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; -import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; - -public enum PluginLoader { - - INSTANCE; - - private class PluginData { - - public final String modId; - public final String resourcePath; - public final IOreSpawnPlugin plugin; - - PluginData(final String modId, final String resourcePath, final IOreSpawnPlugin plugin) { - this.modId = modId; - this.resourcePath = resourcePath; - this.plugin = plugin; - } - } - - private static List dataStore = new ArrayList<>(); - - private String getAnnotationItem(final String item, final ASMData asmData) { - if (asmData.getAnnotationInfo().get(item) != null) { - return asmData.getAnnotationInfo().get(item).toString(); - } else { - return ""; - } - } - - public void load(final FMLPreInitializationEvent event) { - for (final ASMData asmDataItem : event.getAsmData() - .getAll(OreSpawnPlugin.class.getCanonicalName())) { - final String modId = getAnnotationItem("modid", asmDataItem); - final String resourceBase = getAnnotationItem("resourcePath", asmDataItem); - final String clazz = asmDataItem.getClassName(); - IOreSpawnPlugin integration; - - try { - integration = Class.forName(clazz).asSubclass(IOreSpawnPlugin.class).newInstance(); - final PluginData pd = new PluginData(modId, resourceBase, integration); - OreSpawn.LOGGER.fatal("Loading Integration For {}", modId); - dataStore.add(pd); - } catch (final Exception ex) { - OreSpawn.LOGGER.error("Couldn't load integrations for " + modId, ex); - } - } - } - - public void register() { - dataStore.forEach(pd -> { - scanResources(pd); - pd.plugin.register(OreSpawn.API); - }); - } - - public void scanResources(final PluginData pd) { - if (Config.getKnownMods().contains(pd.modId)) { - return; - } - - final String base = String.format(Locale.ENGLISH, "assets/%s/%s", pd.modId, pd.resourcePath); - final URL resURL = getClass().getClassLoader().getResource(base); - - if (resURL == null) { - OreSpawn.LOGGER.warn("Unable to access file {}: got 'null' when trying to resolve it", - base); - return; - } - - URI uri; - - try { - uri = resURL.toURI(); - } catch (URISyntaxException ex) { - CrashReport report = CrashReport.makeCrashReport(ex, - String.format(Locale.ENGLISH, "Failed to get URI for %s", - (new ResourceLocation(pd.modId, pd.resourcePath)).toString())); - report.getCategory().addCrashSection(Constants.CRASH_SECTION, Constants.VERSION); - return; - } - - if (uri.getScheme().equals("jar")) { - try (FileSystem fileSystem = FileSystems.newFileSystem(uri, - Collections.emptyMap())) { - copyout(fileSystem.getPath(base), pd.modId); - } catch (IOException exc) { - CrashReport report = CrashReport.makeCrashReport(exc, String.format( - Locale.ENGLISH, "Failed in getting FileSystem handler set up for %s", uri.getPath())); - report.getCategory().addCrashSection(Constants.CRASH_SECTION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - } else { - copyout(Paths.get(uri), pd.modId); - } - - Config.addKnownMod(pd.modId); - } - - private void copyout(final Path myPath, final String modId) { - try (Stream walk = Files.walk(myPath, 1)) { - for (final Iterator it = walk.iterator(); it.hasNext();) { - final Path p = it.next(); - final String name = p.getFileName().toString(); - - if ("json".equals(FilenameUtils.getExtension(name))) { - InputStream reader = null; - Path target; - - if ("_features".equals(FilenameUtils.getBaseName(name))) { - target = Paths.get(Constants.FileBits.CONFIG_DIR, Constants.FileBits.OS3, - Constants.FileBits.SYSCONF, - String.format(Locale.ENGLISH, "features-%s.json", modId)); - } else if ("_replacements".equals(FilenameUtils.getBaseName(name))) { - target = Paths.get(Constants.FileBits.CONFIG_DIR, Constants.FileBits.OS3, - Constants.FileBits.SYSCONF, - String.format(Locale.ENGLISH, "replacements-%s.json", modId)); - } else { - target = Paths.get(Constants.FileBits.CONFIG_DIR, Constants.FileBits.OS3, - String.format(Locale.ENGLISH, "%s.json", modId)); - } - - if (!target.toFile().exists()) { - reader = Files.newInputStream(p); - FileUtils.copyInputStreamToFile(reader, target.toFile()); - IOUtils.closeQuietly(reader); - } - } - } - } catch (IOException exc) { - CrashReport report = CrashReport.makeCrashReport(exc, String.format( - Locale.ENGLISH, "Faulted while iterating %s for config files or copying them out", myPath)); - report.getCategory().addCrashSection(Constants.CRASH_SECTION, Constants.VERSION); - OreSpawn.LOGGER.error(report.getCompleteReport()); - } - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/commands/AddOreCommand.java b/src/main/java/com/mcmoddev/orespawn/commands/AddOreCommand.java deleted file mode 100644 index 9219dbc..0000000 --- a/src/main/java/com/mcmoddev/orespawn/commands/AddOreCommand.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.mcmoddev.orespawn.commands; - -import org.apache.commons.io.FilenameUtils; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.data.Constants.ConfigNames; -import com.mcmoddev.orespawn.json.OreSpawnReader; -import com.mcmoddev.orespawn.json.OreSpawnWriter; -import com.mcmoddev.orespawn.util.StateUtil; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.command.CommandBase; -import net.minecraft.command.CommandException; -import net.minecraft.command.ICommand; -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.EnumHand; - -public class AddOreCommand extends CommandBase { - - @Override - public String getName() { - return "addore"; - } - - @Override - public String getUsage(final ICommandSender sender) { - return "/addore "; - } - - @Override - public void execute(final MinecraftServer server, final ICommandSender sender, - final String[] args) throws CommandException { - if (!(sender instanceof EntityPlayer)) { - throw new CommandException("Only players can use this command"); - } - - final EntityPlayer player = (EntityPlayer) sender; - final ItemStack stack = player.getHeldItem(EnumHand.MAIN_HAND); - - if (stack == null) { - throw new CommandException("You have no item in your main hand"); - } else if (!(stack.getItem() instanceof ItemBlock)) { - throw new CommandException("The item in your main hand isn't a block"); - } else if (args.length < 1) { - throw new CommandException(this.getUsage(sender)); - } - - final String file = args[0]; - @SuppressWarnings("deprecation") - final IBlockState state = Block.getBlockFromItem(stack.getItem()) - .getStateFromMeta(stack.getItemDamage()); - - final String rawData = getChatComponentFromNthArg(sender, args, 1).getUnformattedText(); - final JsonParser p = new JsonParser(); - final JsonElement parsed; - if(rawData != null && rawData.length() > 0) { - parsed = mergeDefaults(p.parse(rawData), state); - } else { - parsed = mergeDefaults(p.parse("{}"), state); - } - OreSpawnReader.loadFromJson(FilenameUtils.getBaseName(file), parsed); - OreSpawnWriter.saveSingle(FilenameUtils.getBaseName(file)); - } - - private JsonElement mergeDefaults(final JsonElement parse, final IBlockState state) { - final JsonObject work = parse.getAsJsonObject(); - final JsonObject emptyBlacklist = new JsonObject(); - emptyBlacklist.add("excludes", new JsonArray()); - - if (!work.has(ConfigNames.ENABLED)) { - work.addProperty(ConfigNames.ENABLED, true); - } - if (!work.has(ConfigNames.RETROGEN)) { - work.addProperty(ConfigNames.RETROGEN, false); - } - if (!work.has(ConfigNames.FEATURE)) { - work.addProperty(ConfigNames.FEATURE, "orespawn:default"); - } - if (!work.has(ConfigNames.REPLACEMENT)) { - work.addProperty(ConfigNames.REPLACEMENT, "orespawn:default"); - } - if (!work.has(ConfigNames.PARAMETERS)) { - work.add(ConfigNames.PARAMETERS, - OreSpawn.API.getFeature(work.get(ConfigNames.FEATURE).getAsString()) - .getDefaultParameters()); - } - if (!work.has(ConfigNames.DIMENSIONS)) { - work.add(ConfigNames.DIMENSIONS, emptyBlacklist); - } - if (!work.has(ConfigNames.BIOMES)) { - work.add(ConfigNames.BIOMES, emptyBlacklist); - } - - final JsonObject block = new JsonObject(); - block.addProperty(ConfigNames.CHANCE, 100); - block.addProperty(ConfigNames.NAME, state.getBlock().getRegistryName().toString()); - block.addProperty(ConfigNames.STATE, StateUtil.serializeState(state)); - final JsonArray blocks = new JsonArray(); - blocks.add(block); - work.add(ConfigNames.BLOCK, blocks); - - return work; - } - - @Override - public int compareTo(final ICommand command) { - return this.getName().compareTo(command.getName()); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/commands/ClearChunkCommand.java b/src/main/java/com/mcmoddev/orespawn/commands/ClearChunkCommand.java deleted file mode 100644 index f994de9..0000000 --- a/src/main/java/com/mcmoddev/orespawn/commands/ClearChunkCommand.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.mcmoddev.orespawn.commands; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import com.mcmoddev.orespawn.OreSpawn; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.command.CommandBase; -import net.minecraft.command.CommandException; -import net.minecraft.command.ICommand; -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.world.chunk.Chunk; -import net.minecraftforge.fml.common.registry.ForgeRegistries; -import net.minecraftforge.oredict.OreDictionary; - -public class ClearChunkCommand extends CommandBase { - - private static final String STONE_ID = "minecraft:stone"; - private static final List stoneVariants = Arrays.asList(STONE_ID, "minecraft:diorite", - "minecraft:andesite", "minecraft:granite", "minecraft:sandstone", - "minecraft:red_sandstone", "minecraft:netherrack", "minecraft:end_stone"); - private static final List baseStones = Arrays.asList(STONE_ID, "minecraft:netherrack", - "minecraft:end_stone", "minecraft:cobblestone", "minecraft:obsidian", "minecraft:magma", - "minecraft:soul_sand"); - - private static final List dirtVariants = Arrays.asList("minecraft:dirt", - "minecraft:grass"); - private static final List otherVariants = Arrays.asList("minecraft:gravel", - "minecraft:sand"); - - @Override - public String getName() { - return "clearchunk"; - } - - @Override - public String getUsage(final ICommandSender sender) { - return "/clearchunk "; - } - - @Override - public void execute(final MinecraftServer server, final ICommandSender sender, - final String[] args) throws CommandException { - if (!(sender instanceof EntityPlayer)) { - throw new CommandException("Only players can use this command"); - } - - final EntityPlayer player = (EntityPlayer) sender; - final Chunk chunk = player.getEntityWorld().getChunk(player.getPosition()); - final ChunkPos chunkPos = chunk.getPos(); - final List blocks; - - final boolean flagClassic = args.length > 0 && args[0].toLowerCase().equalsIgnoreCase("classic"); - - final List blockNames = new LinkedList<>(); - getBlocks(args, blockNames); - - blocks = blockNames.stream() - .map(blockName -> ForgeRegistries.BLOCKS.getValue(new ResourceLocation(blockName))) - .map(Block::getDefaultState).collect(Collectors.toList()); - - blocks.addAll(OreSpawn.API - .getDimensionDefaultReplacements(player.getEntityWorld().provider.getDimension()) - .stream().collect(Collectors.toList())); - final List overburden = Arrays - .asList("minecraft:dirt", "minecraft:sand", "minecraft:gravel", "minecraft:grass", - "minecraft:sandstone", "minecraft:red_sandstone") - .stream() - .map(blockName -> ForgeRegistries.BLOCKS.getValue(new ResourceLocation(blockName))) - .map(Block::getDefaultState).collect(Collectors.toList()); - - clearBlocks(chunkPos, blocks, overburden, flagClassic, player); - - player.sendStatusMessage( - new TextComponentString("chunk " + chunkPos.toString() + " cleared"), true); - } - - private void clearBlocks(final ChunkPos chunkPos, final List blocks, - final List overburden, final boolean flagClassic, - final EntityPlayer player) { - for (int x = chunkPos.getXStart(); x <= chunkPos.getXEnd(); x++) { - for (int y = 256; y >= 0; y--) { - for (int z = chunkPos.getZStart(); z <= chunkPos.getZEnd(); z++) { - final BlockPos pos = new BlockPos(x, y, z); - final IBlockState block = player.getEntityWorld().getBlockState(pos); - removeIfBlocks(player, pos, block, blocks, overburden, !flagClassic); - removeIfFluid(pos, player); - } - } - } - } - - private void removeIfFluid(final BlockPos pos, final EntityPlayer player) { - if (player.getEntityWorld().getBlockState(pos).getMaterial().isLiquid()) { - final IBlockState bs = player.getEntityWorld().getBlockState(pos); - - if (bs.getMaterial().isLiquid()) { - player.getEntityWorld().setBlockToAir(pos); - } - } - } - - private void removeIfBlocks(final EntityPlayer player, final BlockPos pos, - final IBlockState block, final List blocks, - final List overburden, final boolean flagClassic) { - if (blocks.contains(block) - || ((pos.getY() >= 64 && overburden.contains(block)) && flagClassic)) { - player.getEntityWorld().setBlockToAir(pos); - } - } - - private void getBlocks(final String[] args, final List blockNames) { - if (args.length > 0) { - switch (args[0].toLowerCase()) { - case "viewores": - blockNames.addAll(stoneVariants); - blockNames.addAll(dirtVariants); - blockNames.addAll(otherVariants); - break; - - case "dirtandgravel": - blockNames.add(STONE_ID); - blockNames.addAll(dirtVariants); - blockNames.addAll(otherVariants); - break; - - case "classic": - blockNames.add(Blocks.STONE.getRegistryName().toString()); - blockNames.add(Blocks.NETHERRACK.getRegistryName().toString()); - blockNames.add(Blocks.END_STONE.getRegistryName().toString()); - blockNames - .addAll(OreDictionary.getOres("stone").stream().map(ItemStack::getItem) - .map(Block::getBlockFromItem).map(Block::getRegistryName) - .map(ResourceLocation::toString).collect(Collectors.toList())); - break; - - default: - blockNames.addAll(baseStones); - } - } else { - blockNames.addAll(baseStones); - } - } - - @Override - public int compareTo(final ICommand command) { - return this.getName().compareTo(command.getName()); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/commands/DumpBiomesCommand.java b/src/main/java/com/mcmoddev/orespawn/commands/DumpBiomesCommand.java deleted file mode 100644 index fa9f2cc..0000000 --- a/src/main/java/com/mcmoddev/orespawn/commands/DumpBiomesCommand.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.mcmoddev.orespawn.commands; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringEscapeUtils; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonPrimitive; - -import net.minecraft.command.CommandBase; -import net.minecraft.command.CommandException; -import net.minecraft.command.ICommand; -import net.minecraft.command.ICommandSender; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.world.biome.Biome; -import net.minecraftforge.fml.common.registry.ForgeRegistries; - -public class DumpBiomesCommand extends CommandBase { - - @Override - public String getName() { - return "dumpbiomes"; - } - - @Override - public String getUsage(final ICommandSender sender) { - return "/dumpbiomes"; - } - - @Override - public void execute(final MinecraftServer server, final ICommandSender sender, - final String[] args) throws CommandException { - JsonArray array = new JsonArray(); - - for (final Biome biome : ForgeRegistries.BIOMES) { - array.add(new JsonPrimitive(biome.getRegistryName().toString())); - } - - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - final String json = gson.toJson(array); - - try { - FileUtils.writeStringToFile(new File(".", "biome_dump.json"), - StringEscapeUtils.unescapeJson(json), StandardCharsets.UTF_8); - } catch (final IOException e) { - throw new CommandException("Failed to save the json file"); - } - - sender.sendMessage(new TextComponentString("Done")); - } - - @Override - public int compareTo(final ICommand command) { - return this.getName().compareTo(command.getName()); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/commands/WriteConfigsCommand.java b/src/main/java/com/mcmoddev/orespawn/commands/WriteConfigsCommand.java deleted file mode 100644 index 4d1dc06..0000000 --- a/src/main/java/com/mcmoddev/orespawn/commands/WriteConfigsCommand.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.mcmoddev.orespawn.commands; - -import com.mcmoddev.orespawn.json.OreSpawnWriter; - -import net.minecraft.command.CommandBase; -import net.minecraft.command.CommandException; -import net.minecraft.command.ICommandSender; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.text.TextComponentString; - -public class WriteConfigsCommand extends CommandBase { - - @Override - public String getName() { - return "osSaveConfigs"; - } - - @Override - public String getUsage(final ICommandSender sender) { - return "/osSaveConfigs"; - } - - @Override - public void execute(final MinecraftServer server, final ICommandSender sender, - final String[] args) throws CommandException { - sender.sendMessage(new TextComponentString( - "Forcing configs as OreSpawn sees them to be written to disk")); - OreSpawnWriter.saveConfigs(); - } - -} diff --git a/src/main/java/com/mcmoddev/orespawn/crafttweaker/CrTConstants.java b/src/main/java/com/mcmoddev/orespawn/crafttweaker/CrTConstants.java new file mode 100644 index 0000000..61412e7 --- /dev/null +++ b/src/main/java/com/mcmoddev/orespawn/crafttweaker/CrTConstants.java @@ -0,0 +1,5 @@ +package com.mcmoddev.orespawn.crafttweaker; + +public class CrTConstants { + public static final String LOADER_NAME = "orespawn4"; +} diff --git a/src/main/java/com/mcmoddev/orespawn/crafttweaker/OreSpawnPlugin.java b/src/main/java/com/mcmoddev/orespawn/crafttweaker/OreSpawnPlugin.java new file mode 100644 index 0000000..1d00219 --- /dev/null +++ b/src/main/java/com/mcmoddev/orespawn/crafttweaker/OreSpawnPlugin.java @@ -0,0 +1,56 @@ +package com.mcmoddev.orespawn.crafttweaker; +import com.blamejared.crafttweaker.api.plugin.*; +import com.blamejared.crafttweaker.api.zencode.scriptrun.IScriptRunModuleConfigurator; +import com.mcmoddev.orespawn.OreSpawn; + +/* +TODO: Find docs on how to actually register a loader and work out the various @ZenClass/@ZenMethod requirements for + making things work. + */ +@CraftTweakerPlugin(OreSpawn.MODID+":crt_plugin") +public class OreSpawnPlugin implements ICraftTweakerPlugin { + @Override + public void registerLoaders(final ILoaderRegistrationHandler handler) { + handler.registerLoader(CrTConstants.LOADER_NAME); + } + + @Override + public void registerModuleConfigurators(final IScriptRunModuleConfiguratorRegistrationHandler handler) { + final IScriptRunModuleConfigurator defaultConfig = IScriptRunModuleConfigurator.createDefault(OreSpawn.MODID); + handler.registerConfigurator(CrTConstants.LOADER_NAME, defaultConfig); + } + + @Override + public void manageJavaNativeIntegration(final IJavaNativeIntegrationRegistrationHandler handler) { +/* + this.zenGatherer.listProviders(); + this.zenGatherer.onCandidates(candidate -> this.zenClassRegistrationManager.attemptRegistration(candidate.loader(), candidate.clazz(), handler)); + this.zenClassRegistrationManager.attemptDeferredRegistration(handler); */ + } + + @Override + public void registerLoadSource(final IScriptLoadSourceRegistrationHandler handler) { +/* + handler.registerLoadSource(CraftTweakerConstants.RELOAD_LISTENER_SOURCE_ID); + handler.registerLoadSource(CraftTweakerConstants.CLIENT_RECIPES_UPDATED_SOURCE_ID);*/ + } + + // last step, load scripts: + /* + final ScriptRunConfiguration configuration = new ScriptRunConfiguration( + CraftTweakerConstants.TAGS_LOADER_NAME, + CraftTweakerConstants.RELOAD_LISTENER_SOURCE_ID, // TODO("Custom load source?") + ScriptRunConfiguration.RunKind.EXECUTE + ); + + try { + CraftTweakerAPI.getScriptRunManager() + .createScriptRun(configuration) + .execute(); + } catch(final Throwable e) { + CraftTweakerCommon.logger().error("Unable to run tag scripts due to an error", e); + } + */ + @Override + public void initialize() {} +} diff --git a/src/main/java/com/mcmoddev/orespawn/crafttweaker/TODO.md b/src/main/java/com/mcmoddev/orespawn/crafttweaker/TODO.md new file mode 100644 index 0000000..156f0bd --- /dev/null +++ b/src/main/java/com/mcmoddev/orespawn/crafttweaker/TODO.md @@ -0,0 +1,23 @@ +# TODO +## CraftTweaker Integration Specific +### Goals +Provide for simplified interface so pack creators can add new forms of ore-body generation +without needing to have it added in a hard-coded manner to MMD OreSpawn. + +### Items +1) Do Initialization Tasks, if any +2) Register Loader +3) Register block and blockstate brackets as needed +4) Add generics and interfaces to vanilla world-gen classes and types related + +### Notes +The last item on the above list is the most complex, overall. What to do about it is a +major question, as I'm unsure of a way to actually manage the creation of a +`public static final` for the CODEC, though I am going to attempt to make this happen, overall. + +That and the generic that wraps the Configuration containing the codec and provides the actual +ore-placement code are the most complex items. It might be best to just provide a basic setup +that wraps the vanilla class -- or perhaps one that wraps a custom class that provides for a +couple extra generically named values -- and then let the generation code provided by the +user be a lambda or similar ? + diff --git a/src/main/java/com/mcmoddev/orespawn/data/Config.java b/src/main/java/com/mcmoddev/orespawn/data/Config.java deleted file mode 100644 index 7f4f2c5..0000000 --- a/src/main/java/com/mcmoddev/orespawn/data/Config.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.mcmoddev.orespawn.data; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.FileSystems; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import org.apache.commons.io.FileUtils; - -import com.google.common.collect.ImmutableList; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonParser; -import com.mcmoddev.orespawn.OreSpawn; - -import net.minecraft.crash.CrashReport; -import net.minecraftforge.common.config.Configuration; - -public class Config { - - private static Configuration configuration; - - private Config() { - } - - public static void loadConfig() { - configuration = new Configuration(new File(Constants.CONFIG_FILE)); - - // Load our Boolean Values - boolVals.put(Constants.RETROGEN_KEY, configuration.getBoolean(Constants.RETROGEN_KEY, - Configuration.CATEGORY_GENERAL, false, - "Do we have Retrogen active and generating anything different from the last run in already existing chunks ?")); - boolVals.put(Constants.FORCE_RETROGEN_KEY, - configuration.getBoolean(Constants.FORCE_RETROGEN_KEY, - Configuration.CATEGORY_GENERAL, false, - "Force all chunks to retrogen regardless of anything else")); - boolVals.put(Constants.REPLACE_VANILLA_OREGEN, - configuration.getBoolean(Constants.REPLACE_VANILLA_OREGEN, - Configuration.CATEGORY_GENERAL, false, - "Replace vanilla ore-generation entirely")); - boolVals.put(Constants.FLAT_BEDROCK, - configuration.getBoolean(Constants.FLAT_BEDROCK, Configuration.CATEGORY_GENERAL, - false, "Flatten the bedrock during world generation")); - boolVals.put(Constants.RETRO_BEDROCK, configuration.getBoolean(Constants.RETRO_BEDROCK, - Configuration.CATEGORY_GENERAL, false, "Retroactively flatten bedrock")); - boolVals.put(Constants.REPLACE_ALL, configuration.getBoolean(Constants.REPLACE_ALL, Configuration.CATEGORY_GENERAL, false, "Replace all ore generation")); - intVals.put(Constants.BEDROCK_LAYERS, - configuration.getInt(Constants.BEDROCK_LAYERS, Configuration.CATEGORY_GENERAL, 1, 1, - 4, "How thick should the shell of bedrock be?")); - knownKeys.add(Constants.RETROGEN_KEY); - knownKeys.add(Constants.FORCE_RETROGEN_KEY); - knownKeys.add(Constants.REPLACE_VANILLA_OREGEN); - knownKeys.add(Constants.KNOWN_MODS); - knownKeys.add(Constants.FLAT_BEDROCK); - knownKeys.add(Constants.RETRO_BEDROCK); - knownKeys.add(Constants.BEDROCK_LAYERS); - - loadExtractedConfigs(); - } - - private static void loadExtractedConfigs() { - final Path p = FileSystems.getDefault().getPath("config", "orespawn3", "sysconf", - "known-configs.json"); - - if (!p.toFile().exists()) { - return; - } - - final File in = p.toFile(); - String rawData; - - try { - rawData = FileUtils.readFileToString(in, Charset.defaultCharset()); - } catch (IOException e) { - return; - } - - if (rawData.isEmpty()) { - return; - } - - final JsonArray data = new JsonParser().parse(rawData).getAsJsonArray(); - data.forEach(item -> addKnownMod(item.getAsString())); - } - - public static List getKnownMods() { - return ImmutableList.copyOf(extractedConfigs); - } - - public static void addKnownMod(final String modId) { - extractedConfigs.add(modId); - } - - public static boolean getBoolean(final String keyname) { - if (knownKeys.contains(keyname) && boolVals.containsKey(keyname)) { - return boolVals.get(keyname); - } - - return false; - } - - public static String getString(final String keyname) { - if (knownKeys.contains(keyname) && stringVals.containsKey(keyname)) { - return stringVals.get(keyname); - } - - return ""; - } - - public static int getInt(final String keyname) { - if (knownKeys.contains(keyname) && intVals.containsKey(keyname)) { - return intVals.get(keyname); - } - - return 0; - } - - public static float getFloat(final String keyname) { - if (knownKeys.contains(keyname) && floatVals.containsKey(keyname)) { - return floatVals.get(keyname); - } - - return 0.0f; - } - - public static void saveConfig() { - if (!extractedConfigs.isEmpty()) { - saveKnownConfigs(); - } - - configuration.save(); - } - - private static void saveKnownConfigs() { - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - final Path p = FileSystems.getDefault().getPath("config", "orespawn3", "sysconf", - "known-configs.json"); - - if (!p.toFile().getParentFile().exists()) { - p.toFile().mkdirs(); - } - - final File in = p.toFile(); - - final JsonArray data = new JsonArray(); - - extractedConfigs.forEach(data::add); - - try { - FileUtils.writeStringToFile(in, gson.toJson(data), Charset.defaultCharset()); - } catch (final IOException e) { - CrashReport report = CrashReport.makeCrashReport(e, - "Failed saving list of already extracted mod configs"); - report.getCategory().addCrashSection("OreSpawn Version", Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - } - - private static final HashMap boolVals = new HashMap<>(); - private static final HashMap stringVals = new HashMap<>(); - private static final HashMap intVals = new HashMap<>(); - private static final HashMap floatVals = new HashMap<>(); - private static final List knownKeys = new ArrayList<>(); - private static final List extractedConfigs = new ArrayList<>(); -} diff --git a/src/main/java/com/mcmoddev/orespawn/data/Constants.java b/src/main/java/com/mcmoddev/orespawn/data/Constants.java deleted file mode 100644 index 5509dde..0000000 --- a/src/main/java/com/mcmoddev/orespawn/data/Constants.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.mcmoddev.orespawn.data; - -import java.nio.file.Path; -import java.nio.file.Paths; - -public class Constants { - - public static final String MODID = "orespawn"; - public static final String NAME = "MMD OreSpawn"; - public static final String VERSION = "3.3.1"; - public static final String RETROGEN_KEY = "Retrogen"; - public static final String CONFIG_FILE = "config/orespawn.cfg"; - public static final String FORCE_RETROGEN_KEY = "Force Retrogen"; - public static final String CHUNK_TAG_NAME = "MMD OreSpawn Data"; - public static final String ORE_TAG = "ores"; - public static final String FEATURES_TAG = "features"; - public static final String REPLACE_VANILLA_OREGEN = "Replace Vanilla Oregen"; - public static final String OVERWORLD = "overworld"; - public static final String THE_OVERWORLD = "the overworld"; - public static final String NETHER = "nether"; - public static final String THE_NETHER = "the nether"; - public static final String END = "end"; - public static final String THE_END = "the end"; - public static final String DEFAULT_GEN = "default"; - public static final String VEIN_GEN = "vein"; - public static final String NORMAL_CLOUD = "normal-cloud"; - public static final String CLUSTERS = "clusters"; - public static final String CRASH_SECTION = "OreSpawn Version"; - public static final String KNOWN_MODS = "already-extracted"; - public static final String RETRO_BEDROCK = "Retrogen Flat Bedrock"; - public static final String FLAT_BEDROCK = "Flatten Bedrock"; - public static final String RETRO_BEDROCK_TAG = "retro-bedrock"; - public static final String BEDROCK_LAYERS = "Bedrock Thickness"; - public static final String ORESPAWN_VERSION_CRASH_MESSAGE = "OreSpawn Version"; - public static final String PRECISION = "precision"; - public static final Path CONFDIR = Paths.get(FileBits.CONFIG_DIR, FileBits.OS3); - public static final Path SYSCONF = Paths.get(FileBits.CONFIG_DIR, FileBits.OS3, FileBits.SYSCONF); - public static final String REPLACE_ALL = "Replace All Generation"; - - public final class FormatBits { - - private FormatBits() { - } - - public static final String MAX_SPREAD = "maxSpread"; - public static final String MEDIAN_SIZE = "medianSize"; - public static final String MIN_HEIGHT = "minHeight"; - public static final String MAX_HEIGHT = "maxHeight"; - public static final String VARIATION = "variation"; - public static final String FREQUENCY = "frequency"; - public static final String NODE_SIZE = "size"; - public static final String ATTEMPTS = "attempts"; - public static final String LENGTH = "length"; - public static final String NODE_COUNT = "numObjects"; - public static final String ATTEMPTS_MIN = "minAttempts"; - public static final String ATTEMPTS_MAX = "maxAttempts"; - public static final String STARTINGFACE = "startFacing"; - public static final String FLUID = "fluid"; - } - - public final class FileBits { - - private FileBits() { - } - - public static final String CONFIG_DIR = "config"; - public static final String OS3 = "orespawn3"; - public static final String SYSCONF = "sysconf"; - public static final String PRESETS = "presets.json"; - } - - public final class ConfigNames { - - private ConfigNames() { - } - - public static final String DEFAULT = "default"; - public static final String STATE_NORMAL = "normal"; - public static final String DIMENSIONS = "dimensions"; - public static final String CHANCE = "chance"; - public static final String METADATA = "metaData"; - public static final String BIOMES = "biomes"; - public static final String STATE = "state"; - public static final String REPLACEMENT = "replaces"; - public static final String FEATURE = "feature"; - public static final String PARAMETERS = "parameters"; - public static final String FILE_VERSION = "version"; - public static final String BLOCK = "blocks"; - public static final String SPAWNS = "spawns"; - public static final String RETROGEN = "retrogen"; - public static final String ENABLED = "enabled"; - public static final String NAME = "name"; - public static final String WHITELIST = "includes"; - public static final String BLACKLIST = "excludes"; - public static final String PRESETS = "presets"; - - public final class DefaultFeatureProperties { - - private DefaultFeatureProperties() { - } - - public static final String SIZE = "size"; - public static final String VARIATION = "variation"; - public static final String FREQUENCY = "frequency"; - public static final String MAXHEIGHT = "maxHeight"; - public static final String MINHEIGHT = "minHeight"; - } - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/data/FeatureRegistry.java b/src/main/java/com/mcmoddev/orespawn/data/FeatureRegistry.java deleted file mode 100644 index 603ef37..0000000 --- a/src/main/java/com/mcmoddev/orespawn/data/FeatureRegistry.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.mcmoddev.orespawn.data; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.Map; -import java.util.TreeMap; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringEscapeUtils; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.IFeature; - -import net.minecraft.crash.CrashReport; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.registries.IForgeRegistry; -import net.minecraftforge.registries.RegistryBuilder; - -public class FeatureRegistry { - - private static final String ORE_SPAWN_VERSION = "OreSpawn Version"; - private static final IForgeRegistry registry = new RegistryBuilder() - .setName(new ResourceLocation("orespawn", "feature_registry")).setType(IFeature.class) - .setMaxID(4096) // 12 bits should be enough... hell, 8 bits would be, IMNSHO - .create(); - - public FeatureRegistry() { - // - } - - public Map getFeatures() { - final Map tempMap = new TreeMap<>(); - registry.getEntries().stream() - .forEach(e -> tempMap.put(e.getKey().toString(), e.getValue())); - - return Collections.unmodifiableMap(tempMap); - } - - public String getFeatureName(final IFeature feature) { - return feature.getRegistryName().toString(); - } - - public IFeature getFeature(final String name) { - return getFeature(new ResourceLocation(name)); - } - - public IFeature getFeature(final ResourceLocation featureResourceLocation) { - final ResourceLocation defaultGen = new ResourceLocation(Constants.DEFAULT_GEN); - if (registry.containsKey(featureResourceLocation)) { - return registry.getValue(featureResourceLocation); - } else { - return registry.getValue(defaultGen); - } - } - - public boolean hasFeature(final String name) { - return hasFeature(new ResourceLocation(name)); - } - - public boolean hasFeature(final ResourceLocation featureResourceLocation) { - return registry.containsKey(featureResourceLocation); - } - - public boolean hasFeature(final IFeature feature) { - return registry.containsKey(feature.getRegistryName()); - } - - public void addFeature(final String name, final IFeature feature) { - feature.setRegistryName(new ResourceLocation("orespawn", name)); - registry.register(feature); - } - - public void addFeature(final JsonObject entry) { - addFeature(entry.get("name").getAsString(), entry.get("class").getAsString()); - } - - public void addFeature(final String name, final String className) { - final IFeature feature = getInstance(className); - - if (feature != null && !hasFeature(name)) { - addFeature(name, feature); - } - } - - private static IFeature getInstance(final String className) { - Class featureClazz; - Constructor featureCons; - IFeature feature; - - try { - featureClazz = Class.forName(className); - featureCons = featureClazz.getConstructor(); - feature = (IFeature) featureCons.newInstance(); - } catch (final Exception e) { - final CrashReport report = CrashReport.makeCrashReport(e, - "Failed to load and instantiate an instance of the feature generator named " - + className + " that was specified as a feature generator"); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - return null; - } - - return feature; - } - - public void loadFeaturesFile(final File file) { - final JsonParser parser = new JsonParser(); - String rawJson; - JsonArray elements; - - try { - rawJson = FileUtils.readFileToString(file, Charset.defaultCharset()); - } catch (final IOException e) { - final CrashReport report = CrashReport.makeCrashReport(e, - "Failed reading config " + file.getName()); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - return; - } - - elements = parser.parse(rawJson).getAsJsonArray(); - - for (final JsonElement elem : elements) { - addFeature(elem.getAsJsonObject()); - } - } - - public void writeFeatures(final File file) { - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - final JsonArray root = new JsonArray(); - - registry.getEntries().stream().map(ent -> { - final JsonObject e = new JsonObject(); - e.addProperty("name", ent.getKey().getPath()); - e.addProperty("class", ent.getValue().getClass().getName()); - return e; - }).forEach(root::add); - - final String json = gson.toJson(root); - - try { - FileUtils.writeStringToFile(file, StringEscapeUtils.unescapeJson(json), - StandardCharsets.UTF_8); - } catch (final IOException e) { - final CrashReport report = CrashReport.makeCrashReport(e, - "Failed writing config " + file.getName()); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/data/PresetsStorage.java b/src/main/java/com/mcmoddev/orespawn/data/PresetsStorage.java deleted file mode 100644 index d0d948c..0000000 --- a/src/main/java/com/mcmoddev/orespawn/data/PresetsStorage.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.mcmoddev.orespawn.data; - -import java.io.BufferedReader; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.google.gson.JsonElement; -import com.google.gson.JsonIOException; -import com.google.gson.JsonParser; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSyntaxException; -import com.mcmoddev.orespawn.OreSpawn; - -import net.minecraft.crash.CrashReport; - -public class PresetsStorage { - - private final Map> storage; - private static final String ORE_SPAWN_VERSION = "OreSpawn Version"; - - public PresetsStorage() { - storage = new TreeMap<>(); - } - - public void setSymbolSection(final String sectionName, final String itemName, - final JsonElement value) { - final Map temp = storage.getOrDefault(sectionName, - new HashMap()); - temp.put(itemName, value); - storage.put(sectionName, temp); - } - - public JsonElement getSymbolSection(final String sectionName, final String itemName) { - if (storage.containsKey(sectionName) && storage.get(sectionName).containsKey(itemName)) { - return storage.get(sectionName).get(itemName); - } else { - return new JsonPrimitive(itemName); - } - } - - public void copy(final PresetsStorage dest) { - storage.entrySet().stream().forEach(ensm -> { - final String section = ensm.getKey(); - ensm.getValue().entrySet().forEach( - ensje -> dest.setSymbolSection(section, ensje.getKey(), ensje.getValue())); - }); - } - - public void clear() { - this.storage.clear(); - } - - public void load(final Path inputFile) { - final JsonParser p = new JsonParser(); - JsonElement parsed = null; - - try (BufferedReader r = Files.newBufferedReader(inputFile)) { - parsed = p.parse(r); - } catch (final IOException e) { - CrashReport report = CrashReport.makeCrashReport(e, - "Failed reading presets from" + inputFile.toString()); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } catch (final JsonIOException | JsonSyntaxException e) { - CrashReport report = CrashReport.makeCrashReport(e, - "JSON Parsing Error in " + inputFile.toString()); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - - if (parsed != null) { - parsed.getAsJsonObject().entrySet().stream().forEach(entry -> { - final String section = entry.getKey(); - entry.getValue().getAsJsonObject().entrySet().stream().forEach( - sect -> this.setSymbolSection(section, sect.getKey(), sect.getValue())); - }); - } - } - - public JsonElement get(final String asString) { - final Pattern p = Pattern.compile("\\$\\.(\\w+)\\.(\\w+)"); - final Matcher m = p.matcher(asString); - if (m.matches()) { - return this.getSymbolSection(m.group(1), m.group(2)); - } - return new JsonPrimitive("Unknown Variable " + asString); - } - -} diff --git a/src/main/java/com/mcmoddev/orespawn/data/ReplacementsRegistry.java b/src/main/java/com/mcmoddev/orespawn/data/ReplacementsRegistry.java deleted file mode 100644 index 657ae61..0000000 --- a/src/main/java/com/mcmoddev/orespawn/data/ReplacementsRegistry.java +++ /dev/null @@ -1,265 +0,0 @@ -package com.mcmoddev.orespawn.data; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.TreeMap; -import org.apache.commons.io.FileUtils; - -import com.google.common.collect.ImmutableMap; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.os3.IReplacementEntry; -import com.mcmoddev.orespawn.impl.os3.ReplacementEntry; -import com.mcmoddev.orespawn.util.StateUtil; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.crash.CrashReport; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.common.registry.ForgeRegistries; -import net.minecraftforge.oredict.OreDictionary; -import net.minecraftforge.registries.IForgeRegistryModifiable; -import net.minecraftforge.registries.RegistryBuilder; - -public class ReplacementsRegistry { - - private static final String ORE_SPAWN_VERSION = "OreSpawn Version"; - private static final IForgeRegistryModifiable registry = (IForgeRegistryModifiable) new RegistryBuilder() - .setName(new ResourceLocation("orespawn", "replacements_registry")).allowModification() - .setType(IReplacementEntry.class).setMaxID(65535) // 16 bits should be enough... - .create(); - - public ReplacementsRegistry() { - // - } - - public Map getReplacements() { - return ImmutableMap.copyOf(registry.getEntries()); - } - - /** - * - * @param dimension - * @return - */ - /* - * @deprecated (no, it isn't - why was it flagged this to begin with ?) - */ - // @Deprecated - @SuppressWarnings("deprecation") - public List getDimensionDefault(final int dimension) { - final String[] names = { - "minecraft:netherrack", "minecraft:stone", "minecraft:end_stone" - }; - - final List baseRv = new ArrayList<>(); - - if (dimension < -1 || dimension > 1 || dimension == 0) { - for (final ItemStack iS : OreDictionary.getOres("stone")) { - baseRv.add(Block.getBlockFromItem(iS.getItem()).getStateFromMeta(iS.getMetadata())); - } - - return baseRv; - } - - baseRv.addAll(Arrays.asList(ForgeRegistries.BLOCKS - .getValue(new ResourceLocation(names[dimension + 1])).getDefaultState())); - return baseRv; - } - - public IReplacementEntry getReplacement(final String name) { - final ResourceLocation act = new ResourceLocation( - name.contains(":") ? name : String.format(Locale.ENGLISH, "orespawn:%s", name)); - - if (registry.containsKey(act)) { - return registry.getValue(act); - } else { - return registry.getValue(new ResourceLocation("orespawn:default")); - } - } - - public void addBlock(final String name, final String blockName, final String blockState) { - IBlockState b; - try { - b = StateUtil.deserializeState( - ForgeRegistries.BLOCKS.getValue(new ResourceLocation(blockName)), blockState); - } catch (Exception e) { - StringBuilder p = new StringBuilder(); - for(StackTraceElement elem: e.getStackTrace()) p.append(String.format("%s.%s (%s:%u)\n", elem.getClassName(), elem.getMethodName(), elem.getFileName(), elem.getLineNumber())); - OreSpawn.LOGGER.error(String.format("Exception: %s\n%s", e.getMessage(), p.toString())); - b = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(blockName)).getDefaultState(); - } - addBlock(name, b); - } - - public Map> getBlocks() { - final Map> tempMap = new TreeMap<>(); - registry.getEntries().stream() - .forEach(e -> tempMap.put(e.getKey().toString(), e.getValue().getEntries())); - - return Collections.unmodifiableMap(tempMap); - } - - public void addReplacement(final IReplacementEntry replacement) { - registry.register(replacement); - } - - public void addBlock(final String name, final IBlockState state) { - ResourceLocation regName = new ResourceLocation(name); - if (registry.containsKey(regName)) { - final IReplacementEntry old = registry.getValue(regName); - IReplacementEntry newRE; - List oldList = old.getEntries(); - oldList.add(state); - newRE = new ReplacementEntry(name, oldList); - registry.remove(regName); - newRE.setRegistryName(regName); - registry.register(newRE); - return; - } - - final IReplacementEntry r = new ReplacementEntry(name, state); - registry.register(r); - } - - @SuppressWarnings("deprecation") - public void loadFile(final Path file) { - final JsonParser parser = new JsonParser(); - JsonObject elements; - String rawJson; - - - try { - rawJson = FileUtils.readFileToString(file.toFile(), Charset.defaultCharset()); - } catch (IOException e) { - CrashReport report = CrashReport.makeCrashReport(e, - "Failed reading config " + file.getFileName()); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - return; - } - - elements = parser.parse(rawJson).getAsJsonObject(); - elements.entrySet().stream().forEach(elem -> { - final String entName = elem.getKey(); - final JsonArray entries = elem.getValue().getAsJsonArray(); - final List blocks = new LinkedList<>(); - entries.forEach( e -> { - final JsonObject asObj = e.getAsJsonObject(); - final String blockName = asObj.get(Constants.ConfigNames.NAME).getAsString() - .toLowerCase(); - - // is this an OreDictionary entry ? - if (blockName.startsWith("ore:")) { - loadOreDict(blockName, blocks); - } else { - final ResourceLocation blockRL = new ResourceLocation(blockName); - final Block theBlock = ForgeRegistries.BLOCKS.getValue(blockRL); - if (asObj.has(Constants.ConfigNames.METADATA)) { - // has metadata - final int meta = asObj.get(Constants.ConfigNames.METADATA).getAsInt(); - blocks.add(theBlock.getStateFromMeta(meta)); - } else if (asObj.has(Constants.ConfigNames.STATE)) { - // has a state - loadBlockState(blockName, asObj, blocks); - } else { - // use the default state - blocks.add(theBlock.getDefaultState()); - } - } - }); - - final ResourceLocation checkName= new ResourceLocation("orespawn", entName); - if (registry.containsKey(checkName)) { - final List existingReps = getReplacement(checkName.toString()).getEntries(); - blocks.addAll(existingReps); - } - final IReplacementEntry replacer = new ReplacementEntry(checkName.toString(), blocks); - registry.register(replacer); - }); - } - - private void loadBlockState(String blockName, JsonObject asObj, List blocks) { - final ResourceLocation blockRL = new ResourceLocation(blockName); - final Block theBlock = ForgeRegistries.BLOCKS.getValue(blockRL); - final String state = asObj.get(Constants.ConfigNames.STATE).getAsString(); - IBlockState b; - try { - b = StateUtil.deserializeState(theBlock, state); - } catch (Exception e1) { - StringBuilder p = new StringBuilder(); - for(StackTraceElement elem1: e1.getStackTrace()) p.append(String.format("%s.%s (%s:%d)\n", elem1.getClassName(), elem1.getMethodName(), elem1.getFileName(), elem1.getLineNumber())); - OreSpawn.LOGGER.error(String.format("Exception loading block with state [%s]: %s\n%s", state, e1.getMessage(), p.toString())); - b = theBlock.getDefaultState(); - } - blocks.add(b); - } - - @SuppressWarnings("deprecation") - private void loadOreDict(String blockName, List blocks) { - // yes, it is - final String oreDictName = blockName.split(":")[1]; - OreDictionary.getOres(oreDictName).forEach(iS -> { - if (iS.getMetadata() != 0) { - blocks.add(Block.getBlockFromItem(iS.getItem()) - .getStateFromMeta(iS.getMetadata())); - } else { - blocks.add(Block.getBlockFromItem(iS.getItem()).getDefaultState()); - } - }); - } - - public void saveFile(final String modName) { - final JsonObject outs = new JsonObject(); - - registry.getEntries().stream().filter(ent -> ent.getKey().getNamespace().equals(modName)) - .forEach(ent -> { - final JsonArray entry = new JsonArray(); - final IReplacementEntry workVal = ent.getValue(); - workVal.getEntries().stream().forEach(bs -> { - final JsonObject block = new JsonObject(); - block.addProperty(Constants.ConfigNames.BLOCK, - bs.getBlock().getRegistryName().toString()); - if (!bs.toString().matches("\\[normal\\]")) { - block.addProperty(Constants.ConfigNames.STATE, - bs.toString().replaceAll("[\\[\\]]", "")); - } - entry.add(block); - }); - outs.add(ent.getKey().toString(), entry); - }); - final Path p = Paths.get("config", "orespawn3", "sysconfig", - String.format(Locale.ENGLISH, "replacements-%s.json", modName)); - try (final BufferedWriter w = Files.newBufferedWriter(p)) { - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - final String ov = gson.toJson(outs); - w.write(ov); - } catch (final IOException e) { - CrashReport report = CrashReport.makeCrashReport(e, String - .format(Locale.ENGLISH, "Failed writing replacements file %s", p.toAbsolutePath().toString())); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - } - - public boolean has(final ResourceLocation resourceLocation) { - return registry.containsKey(resourceLocation); - } - -} diff --git a/src/main/java/com/mcmoddev/orespawn/data/VanillaOres.java b/src/main/java/com/mcmoddev/orespawn/data/VanillaOres.java deleted file mode 100644 index e04934b..0000000 --- a/src/main/java/com/mcmoddev/orespawn/data/VanillaOres.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.mcmoddev.orespawn.data; - -import com.mcmoddev.orespawn.api.os3.OS3API; -import com.mcmoddev.orespawn.api.plugin.IOreSpawnPlugin; -import com.mcmoddev.orespawn.api.plugin.OreSpawnPlugin; - -@OreSpawnPlugin(modid = "orespawn", resourcePath = "configs") -public class VanillaOres implements IOreSpawnPlugin { - - @Override - public void register(final OS3API apiInterface) { - // nothing for us to do - all of our ores are in the - // jar and the code handles that - } - -} diff --git a/src/main/java/com/mcmoddev/orespawn/features/Clusters.java b/src/main/java/com/mcmoddev/orespawn/features/Clusters.java new file mode 100644 index 0000000..44ad811 --- /dev/null +++ b/src/main/java/com/mcmoddev/orespawn/features/Clusters.java @@ -0,0 +1,71 @@ +package com.mcmoddev.orespawn.features; + +import com.mcmoddev.orespawn.features.configs.ClusterConfiguration; +import com.mcmoddev.orespawn.misc.M; +import net.minecraft.core.BlockPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; + +/** + * Generates clusters of ores or custom blocks within a circular area. + *

+ * For each cluster, picks a random position within a radius around the origin, + * checks the existing block at that position against the configured targets, + * and replaces it if it matches. + */ +public class Clusters extends Feature { + public Clusters() { + super(ClusterConfiguration.CODEC); + } + + /** + * Places clusters according to the provided configuration. + * + * @param context Contextual information for feature placement, including world, origin, and configuration. + * @return true if placement completed (Minecraft ignores this return value for features). + */ + @Override + public boolean place(FeaturePlaceContext context) { + ClusterConfiguration config = context.config(); + WorldGenLevel world = (WorldGenLevel) context.level(); + RandomSource random = context.random(); + BlockPos origin = context.origin(); + + // Compute radius and number of attempts based on config + int radius = config.spread / 2; + int maxClusters = (int) (Math.PI * radius * radius); + int clustersToPlace = Math.min(config.size, maxClusters); + + // World height bounds + int minBuildY = world.getMinBuildHeight(); + int maxBuildY = world.getMaxBuildHeight(); // exclusive + + // Generate each cluster + for (int i = 0; i < clustersToPlace; i++) { + // Pick a random offset within the circular spread + int offsetX = M.getPoint(0, config.spread, radius, random); + int offsetZ = M.getPoint(0, config.spread, radius, random); + int offsetY = random.nextInt(maxBuildY - minBuildY) + minBuildY; + + BlockPos targetPos = new BlockPos( + origin.getX() + offsetX, + offsetY, + origin.getZ() + offsetZ + ); + + // Check existing block and replace if it matches any target state + BlockState existingState = world.getBlockState(targetPos); + for (var targetState : config.targetStates) { + if (targetState.target.test(existingState, random)) { + // Use flag 2: no physics and no neighbor updates for performance + world.setBlock(targetPos, targetState.state, 2); + } + } + } + + return true; + } +} diff --git a/src/main/java/com/mcmoddev/orespawn/features/NormalCloud.java b/src/main/java/com/mcmoddev/orespawn/features/NormalCloud.java new file mode 100644 index 0000000..cb10669 --- /dev/null +++ b/src/main/java/com/mcmoddev/orespawn/features/NormalCloud.java @@ -0,0 +1,90 @@ +package com.mcmoddev.orespawn.features; + +import com.mcmoddev.orespawn.features.configs.NormalCloudConfiguration; +import com.mcmoddev.orespawn.misc.M; +import net.minecraft.core.BlockPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; + +import java.util.HashSet; +import java.util.Set; + +/** + * Generates "cloud" formations of ores or custom blocks scattered within a circular area. + *

+ * Attempts up to size placements, skipping duplicates and positions outside range, + * replacing matching blocks without physics or neighbor updates for performance. + */ +public class NormalCloud extends Feature { + public NormalCloud() { + super(NormalCloudConfiguration.CODEC); + } + + /** + * Places scattered blocks (cloud) based on configuration parameters. + *

+ * For each placement attempt, picks a random offset within the configured spread, + * clamps Y to world bounds, skips duplicates, and replaces the block if it matches any target. + * Stops early if maxAttempts reached (twice the desired count) to avoid infinite loops. + * + * @param context Placement context including world, random, origin, and config + * @return true always (feature return value is ignored) + */ + @Override + public boolean place(FeaturePlaceContext context) { + NormalCloudConfiguration config = context.config(); + WorldGenLevel world = (WorldGenLevel) context.level(); + RandomSource random = context.random(); + BlockPos origin = context.origin(); + + // Compute half of configured spread as radius + int radius = config.spread / 2; + // Maximum distinct positions within circle + int desiredCount = (int) (Math.PI * radius * radius); + // Actual number of placements to attempt + int placementsNeeded = Math.min(config.size, desiredCount); + + // World height constraints + int minY = world.getMinBuildHeight(); + int maxY = world.getMaxBuildHeight(); // exclusive + + // Track positions already processed to avoid duplicates + Set seenPositions = new HashSet<>(); + int attempts = 0; + int maxAttempts = placementsNeeded * 2; + + while (seenPositions.size() < placementsNeeded && attempts < maxAttempts) { + attempts++; + + // Random offset within circular spread + int offsetX = M.getPoint(0, config.spread, radius, random); + int offsetZ = M.getPoint(0, config.spread, radius, random); + int offsetY = random.nextInt(maxY - minY) + minY; + + BlockPos targetPos = new BlockPos( + origin.getX() + offsetX, + offsetY, + origin.getZ() + offsetZ + ); + + // Skip duplicates + if (!seenPositions.add(targetPos)) { + continue; + } + + // Check existing block and replace if it matches any target state + BlockState existingState = world.getBlockState(targetPos); + for (var targetState : config.targetStates) { + if (targetState.target.test(existingState, random)) { + // Flag=2: no physics, no neighbor updates + world.setBlock(targetPos, targetState.state, 2); + } + } + } + + return true; + } +} diff --git a/src/main/java/com/mcmoddev/orespawn/features/VeinFeature.java b/src/main/java/com/mcmoddev/orespawn/features/VeinFeature.java new file mode 100644 index 0000000..1271ef8 --- /dev/null +++ b/src/main/java/com/mcmoddev/orespawn/features/VeinFeature.java @@ -0,0 +1,273 @@ +package com.mcmoddev.orespawn.features; + +import com.mcmoddev.orespawn.OreSpawn; +import com.mcmoddev.orespawn.features.configs.VeinConfiguration; +import net.minecraft.core.BlockPos; +import net.minecraft.core.SectionPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.BulkSectionAccess; +import net.minecraft.world.level.chunk.LevelChunkSection; +import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; +import org.apache.commons.lang3.tuple.Pair; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +public class VeinFeature extends Feature { + private static final String eMess = "Value %d out of range (1-6)"; + + public VeinFeature() { + super(VeinConfiguration.CODEC); + OreSpawn.LOGGER.info("VeinFeature created"); + } + + @Override + public boolean place(FeaturePlaceContext pContext) { + RandomSource randomsource = pContext.random(); + BlockPos blockpos = pContext.origin(); + WorldGenLevel worldgenlevel = pContext.level(); + VeinConfiguration veinconfiguration = pContext.config(); + + double startX = blockpos.getX(); + double startY = blockpos.getY(); + double startZ = blockpos.getZ(); + int length = randomsource.nextInt(veinconfiguration.minLength, veinconfiguration.maxLength); + return doPlacement(worldgenlevel, randomsource, veinconfiguration, startX, startY, startZ, length); + } + + private boolean doPlacement(WorldGenLevel pLevel, RandomSource pRandom, VeinConfiguration pConfig, double startX, double startY, double startZ, int length) { + OreSpawn.LOGGER.info("VeinFeature called to spawn a vein at {}, {}, {}", startX, startY, startZ); + int cn = 0; + int ls = -1; + int ns = -1; + BlockPos curpos = new BlockPos((int) startX, (int) startY, (int) startZ); + List> seen = new ArrayList<>(); + while (cn <= length) { + ns = pRandom.nextInt(1, 6); + if (ns == ls) + while (ns == ls) + ns = pRandom.nextInt(1, 6); + + if (ls == -1) + seen.add(Pair.of(curpos, ns)); + curpos = switch (ns) { + case 1 -> curpos.above(); + case 2 -> curpos.below(); + case 3 -> curpos.east(); + case 4 -> curpos.west(); + case 5 -> curpos.north(); + case 6 -> curpos.south(); + default -> throw new RuntimeException(String.format(eMess, ns)); + }; + + ls = ns; + if (seen.contains(Pair.of(curpos, ls))) break; // early exit, we've crossed our previous track + cn += 1; + } + seen.add(Pair.of(curpos, ns)); + seen.forEach(bp -> makeNodeAt(pLevel, pConfig, bp, pRandom)); + return true; + } + + private void makeNodeAt(WorldGenLevel pLevel, VeinConfiguration pConfig, Pair pLoc, RandomSource pRandom) { + // the right side of each loc determines if the node generates vertical or horizontal + switch (pLoc.getRight()) { + case 1: + case 2: + makeHorizontal(pLevel, pLoc.getLeft(), pConfig, pRandom); + break; + case 3: + case 4: + makeVertical(pLevel, pLoc.getLeft(), pConfig, pRandom, true); + break; + case 5: + case 6: + makeVertical(pLevel, pLoc.getLeft(), pConfig, pRandom, false); + break; + default: + throw new RuntimeException(String.format(eMess, pLoc.getRight())); + } + } + + private static double getRadiusOfArea(int area) { + double base = (double)area/Math.PI; + double res = Math.sqrt(base); + return res; + } + + private static Pair paraCirc(double r, double curT) { + return Pair.of(r * Math.sin(curT), r * Math.cos(curT)); + } + + private static Pair paraCircCoords(int cx, int cy, double r, double curT) { + Pair base = paraCirc(r, curT); + return Pair.of((int) (cx + base.getLeft()), (int) (cy + base.getRight())); + } + + private void makeHorizontal(WorldGenLevel pLevel, BlockPos pos, VeinConfiguration pConfig, RandomSource pRandom) { + OreSpawn.LOGGER.debug("[Vein] makeHorizontal start at {} size={} maxR={}", pos, pConfig.size, getRadiusOfArea(pConfig.size)); + try (BulkSectionAccess bulksectionaccess = new BulkSectionAccess(pLevel)) { + List> placed = new LinkedList<>(); + + BlockPos.MutableBlockPos accessPos = pos.mutable(); + //OreSpawn.LOGGER.info("VeinFeature starting at {}", accessPos); + + if (pLevel.ensureCanWrite(accessPos)) { + LevelChunkSection section = bulksectionaccess.getSection(accessPos); + if (section != null) { + //OreSpawn.LOGGER.info("section != null"); + int relX = SectionPos.sectionRelative(accessPos.getX()); + int relY = SectionPos.sectionRelative(accessPos.getY()); + int relZ = SectionPos.sectionRelative(accessPos.getZ()); + BlockState blockstate = section.getBlockState(relX, relY, relZ); + if (!placed.contains(Pair.of(accessPos.getX(), accessPos.getZ()))) { + //OreSpawn.LOGGER.info("!placed.contains(Pair.of(...)) targets: {}", pConfig.targetStates.size()); + for (VeinConfiguration.TargetBlockState tgt : pConfig.targetStates) { + //OreSpawn.LOGGER.info("Target state: {} ({})-- test: {}", tgt, blockstate, tgt.target.test(blockstate, pRandom)); + if (tgt.target.test(blockstate, pRandom)) { + placed.add(Pair.of(accessPos.getX(), accessPos.getZ())); + //OreSpawn.LOGGER.info("calling setBlock (pLevel.setBlock(...))"); + //pLevel.setBlock(accessPos, tgt.state, 2); + + int rx = SectionPos.sectionRelative(accessPos.getX()); + int ry = SectionPos.sectionRelative(accessPos.getY()); + int rz = SectionPos.sectionRelative(accessPos.getZ()); + OreSpawn.LOGGER.info("section.setBlockState({}, {}, {}, {}, false)", rx, ry, rz, tgt.state); + section.setBlockState(rx, ry, rz, tgt.state, false); + } + } + } + } + } + //double maxRadius = Math.min(getRadiusOfArea(pConfig.size), 8); // TODO: make this configurable - added for now for testing + //for (double r = 1; r <= maxRadius; r++) { // maxRadius=getRadiusOfArea(pConfig.size) + + + for (double r = 1; r <= getRadiusOfArea(pConfig.size); r++) { + double div = Math.pow(r*2+1, 2); + double step = Math.TAU / div; + for (double c = 0; c <= Math.TAU; c += step) { + int left = pos.getX(); + int right = pos.getZ(); + Pair tl = paraCircCoords(left, right, r, c); + accessPos.set(tl.getLeft(), pos.getY(), tl.getRight()); + if (pLevel.ensureCanWrite(accessPos)) { + LevelChunkSection section = bulksectionaccess.getSection(accessPos); + if (section != null) { + //OreSpawn.LOGGER.info("section != null"); + int relX = SectionPos.sectionRelative(accessPos.getX()); + int relY = SectionPos.sectionRelative(accessPos.getY()); + int relZ = SectionPos.sectionRelative(accessPos.getZ()); + BlockState blockstate = section.getBlockState(relX, relY, relZ); + if (!placed.contains(tl)) { + //OreSpawn.LOGGER.info("!placed.contains(tl)"); + for (VeinConfiguration.TargetBlockState tgt : pConfig.targetStates) { + //OreSpawn.LOGGER.info("Target state: {} ({})-- test: {}", tgt, blockstate, tgt.target.test(blockstate, pRandom)); + if (tgt.target.test(blockstate, pRandom)) { + placed.add(tl); + //OreSpawn.LOGGER.info("calling setBlock (pLevel.setBlock(...))"); + //pLevel.setBlock(accessPos, tgt.state, 2); + + int rx = SectionPos.sectionRelative(accessPos.getX()); + int ry = SectionPos.sectionRelative(accessPos.getY()); + int rz = SectionPos.sectionRelative(accessPos.getZ()); + OreSpawn.LOGGER.info("section.setBlockState({}, {}, {}, {}, false)", rx, ry, rz, tgt.state); + section.setBlockState(rx, ry, rz, tgt.state, false); + } + } + } + } + } + } + } + } + OreSpawn.LOGGER.debug("[Vein] makeHorizontal done at {}", pos); + } + + private void makeVertical(WorldGenLevel pLevel, BlockPos pos, VeinConfiguration pConfig, RandomSource pRandom, boolean northSouth) { + OreSpawn.LOGGER.debug("[Vein] makeVertical start at {} size={} maxR={}", pos, pConfig.size, getRadiusOfArea(pConfig.size)); + // northsouth == true, manipulate XY else manipulate ZY + try (BulkSectionAccess bulksectionaccess = new BulkSectionAccess(pLevel)) { + List> placed = new LinkedList<>(); + BlockPos.MutableBlockPos accessPos = pos.mutable(); + OreSpawn.LOGGER.info("VeinFeature starting at {} **{}", accessPos, northSouth); + + if (pLevel.ensureCanWrite(accessPos)) { + LevelChunkSection section = bulksectionaccess.getSection(accessPos); + if (section != null) { + //OreSpawn.LOGGER.info("section != null"); + int relX = SectionPos.sectionRelative(accessPos.getX()); + int relY = SectionPos.sectionRelative(accessPos.getY()); + int relZ = SectionPos.sectionRelative(accessPos.getZ()); + BlockState blockstate = section.getBlockState(relX, relY, relZ); + if (!placed.contains(Pair.of(accessPos.getX(), northSouth?accessPos.getY():accessPos.getZ()))) { + //OreSpawn.LOGGER.info("!placed.contains(Pair.of(...))"); + for (VeinConfiguration.TargetBlockState tgt : pConfig.targetStates) { + //OreSpawn.LOGGER.info("Target state: {} ({})-- test: {}", tgt, blockstate, tgt.target.test(blockstate, pRandom)); + if (tgt.target.test(blockstate, pRandom)) { + placed.add(Pair.of(accessPos.getX(), northSouth?accessPos.getY():accessPos.getZ())); + //OreSpawn.LOGGER.info("calling setBlock (pLevel.setBlock(...))"); + //pLevel.setBlock(accessPos, tgt.state, 2); + + int rx = SectionPos.sectionRelative(accessPos.getX()); + int ry = SectionPos.sectionRelative(accessPos.getY()); + int rz = SectionPos.sectionRelative(accessPos.getZ()); + OreSpawn.LOGGER.info("section.setBlockState({}, {}, {}, {}, false)", rx, ry, rz, tgt.state); + section.setBlockState(rx, ry, rz, tgt.state, false); + } + } + } + } + } + + for (double r = 1; r <= getRadiusOfArea(pConfig.size); r++) { + double div = Math.pow(r*2+1, 2); + double step = Math.TAU / div; + for (double c = 0; c <= Math.TAU; c += step) { + int left = pos.getX(); + int right = northSouth?pos.getY():pos.getZ(); + Pair tl = paraCircCoords(left, right, r, c); + if (northSouth) { + accessPos.set(tl.getLeft(), tl.getRight(), pos.getZ()); + } else { + accessPos.set(pos.getX(), tl.getRight(), tl.getLeft()); + } + + if (pLevel.ensureCanWrite(accessPos)) { + LevelChunkSection section = bulksectionaccess.getSection(accessPos); + if (section != null) { + //OreSpawn.LOGGER.info("section != null"); + int relX = SectionPos.sectionRelative(accessPos.getX()); + int relY = SectionPos.sectionRelative(accessPos.getY()); + int relZ = SectionPos.sectionRelative(accessPos.getZ()); + BlockState blockstate = section.getBlockState(relX, relY, relZ); + if (!placed.contains(tl)) { + //OreSpawn.LOGGER.info("!placed.contains(tl)"); + for (VeinConfiguration.TargetBlockState tgt : pConfig.targetStates) { + //OreSpawn.LOGGER.info("Target state: {} ({})-- test: {}", tgt, blockstate, tgt.target.test(blockstate, pRandom)); + if (tgt.target.test(blockstate, pRandom)) { + placed.add(tl); + //OreSpawn.LOGGER.info("calling setBlock (pLevel.setBlock(...))"); + //pLevel.setBlock(accessPos, tgt.state, 2); + + int rx = SectionPos.sectionRelative(accessPos.getX()); + int ry = SectionPos.sectionRelative(accessPos.getY()); + int rz = SectionPos.sectionRelative(accessPos.getZ()); + OreSpawn.LOGGER.info("section.setBlockState({}, {}, {}, {}, false)", rx, ry, rz, tgt.state); + section.setBlockState(rx, ry, rz, tgt.state, false); + } + } + } + } + } + } + } + } + + OreSpawn.LOGGER.debug("[Vein] makeVertical done at {}", pos); + } +} diff --git a/src/main/java/com/mcmoddev/orespawn/features/configs/ClusterConfiguration.java b/src/main/java/com/mcmoddev/orespawn/features/configs/ClusterConfiguration.java new file mode 100644 index 0000000..128c52e --- /dev/null +++ b/src/main/java/com/mcmoddev/orespawn/features/configs/ClusterConfiguration.java @@ -0,0 +1,36 @@ +package com.mcmoddev.orespawn.features.configs; + +import com.google.common.collect.ImmutableList; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; +import net.minecraft.world.level.levelgen.structure.templatesystem.RuleTest; + +import java.util.List; + +public class ClusterConfiguration implements FeatureConfiguration { + public final List targetStates; + public final int size; + public final int spread; + public final int nodeSize; + + public static final Codec CODEC = RecordCodecBuilder.create( + (builder) -> builder.group( + Codec.list(VeinConfiguration.TargetBlockState.CODEC).fieldOf("targets").forGetter((config) -> config.targetStates ), + Codec.INT.fieldOf("size").forGetter((config) -> config.size), + Codec.INT.fieldOf("spread").forGetter((config) -> config.spread), + Codec.INT.fieldOf("node_size").forGetter((config) -> config.nodeSize)) + .apply(builder, ClusterConfiguration::new)); + + public ClusterConfiguration(List targetStates, int size, int spread, int nodeSize) { + this.targetStates = targetStates; + this.size = size; + this.spread = spread; + this.nodeSize = nodeSize; + } + + public ClusterConfiguration(RuleTest target, BlockState state, int size, int spread, int nodeSize) { + this(ImmutableList.of(new VeinConfiguration.TargetBlockState(target, state)), size, spread, nodeSize); + } +} diff --git a/src/main/java/com/mcmoddev/orespawn/features/configs/NormalCloudConfiguration.java b/src/main/java/com/mcmoddev/orespawn/features/configs/NormalCloudConfiguration.java new file mode 100644 index 0000000..1285ee7 --- /dev/null +++ b/src/main/java/com/mcmoddev/orespawn/features/configs/NormalCloudConfiguration.java @@ -0,0 +1,33 @@ +package com.mcmoddev.orespawn.features.configs; + +import com.google.common.collect.ImmutableList; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; +import net.minecraft.world.level.levelgen.structure.templatesystem.RuleTest; + +import java.util.List; + +public class NormalCloudConfiguration implements FeatureConfiguration { + public final List targetStates; + public final int size; + public final int spread; + + public static final Codec CODEC = RecordCodecBuilder.create( + (builder) -> builder.group( + Codec.list(VeinConfiguration.TargetBlockState.CODEC).fieldOf("targets").forGetter((config) -> config.targetStates ), + Codec.INT.fieldOf("size").forGetter((config) -> config.size), + Codec.INT.fieldOf("spread").forGetter((config) -> config.spread) ).apply(builder, NormalCloudConfiguration::new)); + + + public NormalCloudConfiguration(List targetStates, int size, int spread) { + this.targetStates = targetStates; + this.size = size; + this.spread = spread; + } + + public NormalCloudConfiguration(RuleTest target, BlockState state, int size, int spread) { + this(ImmutableList.of(new VeinConfiguration.TargetBlockState(target, state)), size, spread); + } +} diff --git a/src/main/java/com/mcmoddev/orespawn/features/configs/VeinConfiguration.java b/src/main/java/com/mcmoddev/orespawn/features/configs/VeinConfiguration.java new file mode 100644 index 0000000..3139690 --- /dev/null +++ b/src/main/java/com/mcmoddev/orespawn/features/configs/VeinConfiguration.java @@ -0,0 +1,60 @@ +package com.mcmoddev.orespawn.features.configs; + +import com.google.common.collect.ImmutableList; +import com.mcmoddev.orespawn.OreSpawn; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; +import net.minecraft.world.level.levelgen.structure.templatesystem.RuleTest; + +import java.util.List; + +public class VeinConfiguration implements FeatureConfiguration { + public final List targetStates; + public final int size; + public final int maxLength; + public final int minLength; + public final float frequency; + + public static final Codec CODEC = RecordCodecBuilder.create( + (builder) -> builder.group( + Codec.list(TargetBlockState.CODEC).fieldOf("targets").forGetter((config) -> config.targetStates ), + Codec.INT.fieldOf("size").forGetter((config) -> config.size), + Codec.INT.fieldOf("max_length").forGetter((config) -> config.maxLength), + Codec.INT.fieldOf("min_length").forGetter((config) -> config.minLength), + Codec.FLOAT.fieldOf("frequency").forGetter((config) -> config.frequency) + ).apply(builder, VeinConfiguration::new) + ); + + public VeinConfiguration(List targets, int size, int maxlength, int minlength, float frequency) { + this.targetStates = targets; + this.size = size; + this.maxLength = maxlength; + this.minLength = minlength; + this.frequency = frequency; + } + + public VeinConfiguration(RuleTest target, BlockState state, int size, int maxlength, int minlength, float frequency) { + this(ImmutableList.of(new TargetBlockState(target, state)), size, maxlength, minlength, frequency); + OreSpawn.LOGGER.info("Vein of size {} and a length between {} and {} configured", size, minlength, maxlength); + } + + + public static class TargetBlockState { + public static final Codec CODEC = RecordCodecBuilder.create( + p_161039_ -> p_161039_.group( + RuleTest.CODEC.fieldOf("target").forGetter(p_161043_ -> p_161043_.target), + BlockState.CODEC.fieldOf("state").forGetter(p_161041_ -> p_161041_.state) + ) + .apply(p_161039_, VeinConfiguration.TargetBlockState::new) + ); + public final RuleTest target; + public final BlockState state; + + TargetBlockState(RuleTest pRule, BlockState pState) { + this.target = pRule; + this.state = pState; + } + } +} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/features/ClusterGenerator.java b/src/main/java/com/mcmoddev/orespawn/impl/features/ClusterGenerator.java deleted file mode 100644 index e6b8d54..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/features/ClusterGenerator.java +++ /dev/null @@ -1,214 +0,0 @@ -package com.mcmoddev.orespawn.impl.features; - -import java.util.Random; - -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.FeatureBase; -import com.mcmoddev.orespawn.api.IFeature; -import com.mcmoddev.orespawn.api.os3.ISpawnEntry; -import com.mcmoddev.orespawn.data.Constants; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.Vec3i; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; - -public class ClusterGenerator extends FeatureBase implements IFeature { - - private ClusterGenerator(final Random rand) { - super(rand); - } - - public ClusterGenerator() { - this(new Random()); - } - - private class SpawnParameters { - public final int clusterSize; - public final int variance; - public final int clusterCount; - public final int maxSpread; - public final int minHeight; - public final int maxHeight; - - SpawnParameters(final int clusterSize, final int variance, final int clusterCount, - final int maxSpread, final int minHeight, final int maxHeight) { - this.clusterSize = clusterSize; - this.variance = variance; - this.clusterCount = clusterCount; - this.maxSpread = maxSpread; - this.minHeight = minHeight; - this.maxHeight = maxHeight; - } - } - @Override - public void generate(final World world, final IChunkGenerator chunkGenerator, - final IChunkProvider chunkProvider, final ISpawnEntry spawnData, final ChunkPos posIn) { - final ChunkPos pos = posIn; - final JsonObject params = spawnData.getFeature().getFeatureParameters(); - - // First, load cached blocks for neighboring chunk ore spawns - final int chunkX = pos.x; - final int chunkZ = pos.z; - - mergeDefaults(params, getDefaultParameters()); - - runCache(chunkX, chunkZ, world, spawnData); - - // now to ore spawn - - final int blockX = chunkX * 16 + 8; - final int blockZ = chunkZ * 16 + 8; - - final int maxSpread = params.get(Constants.FormatBits.MAX_SPREAD).getAsInt(); - final int minHeight = params.get(Constants.FormatBits.MIN_HEIGHT).getAsInt(); - final int maxHeight = params.get(Constants.FormatBits.MAX_HEIGHT).getAsInt(); - final int variance = params.get(Constants.FormatBits.VARIATION).getAsInt(); - final int frequency = params.get(Constants.FormatBits.FREQUENCY).getAsInt(); - final int triesMin = params.get(Constants.FormatBits.ATTEMPTS_MIN).getAsInt(); - final int triesMax = params.get(Constants.FormatBits.ATTEMPTS_MAX).getAsInt(); - final int clusterSize = params.get(Constants.FormatBits.NODE_SIZE).getAsInt(); - final int clusterCount = params.get(Constants.FormatBits.NODE_COUNT).getAsInt(); - - int tries; - - if (triesMax == triesMin) { - tries = triesMax; - } else { - tries = random.nextInt(triesMax - triesMin) + triesMin; - } - - while (tries > 0) { - if (this.random.nextInt(100) <= frequency) { - final int xRand = random.nextInt(16); - final int zRand = random.nextInt(16); - - final int x = blockX + xRand - (maxSpread / 2); - final int y = random.nextInt(maxHeight - minHeight) + minHeight; - final int z = blockZ + zRand - (maxSpread / 2); - - spawnCluster(new SpawnParameters(clusterSize, variance, clusterCount, maxSpread, minHeight, maxHeight), - spawnData, world, new BlockPos(x, y, z)); - } - - tries--; - } - } - - private void spawnCluster(final SpawnParameters params, - final ISpawnEntry spawnData, final World world, final BlockPos pos) { - // spawn a cluster at the center, then a bunch around the outside... - int r = params.clusterSize - params.variance; - - if (params.variance > 0) { - r += this.random.nextInt(2 * params.variance) - params.variance; - } - - spawnChunk(world, pos, spawnData, r); - - int count = this.random.nextInt(params.clusterCount - 1); // always at least the first, but vary - // inside that - - if (params.variance > 0) { - count += this.random.nextInt(2 * params.variance) - params.variance; - } - - while (count >= 0) { - r = params.clusterSize - params.variance; - - if (params.variance > 0) { - r += this.random.nextInt(2 * params.variance) - params.variance; - } - - final int radius = params.maxSpread / 2; - - final int xp = getPoint(-radius, radius, 0); - final int yp = getPoint(params.minHeight, params.maxHeight, (params.maxHeight - params.minHeight) / 2); - final int zp = getPoint(-radius, radius, 0); - - final BlockPos p = pos.add(xp, yp, zp); - spawnChunk(world, p, spawnData, r); - - count -= r; - } - } - - private void spawnChunk(final World world, final BlockPos pos, final ISpawnEntry spawnData, - final int quantity) { - int count = quantity; - final int lutType = (quantity < 8) ? offsetIndexRef_small.length : offsetIndexRef.length; - final int[] lut = (quantity < 8) ? offsetIndexRef_small : offsetIndexRef; - final Vec3i[] offs = new Vec3i[lutType]; - - System.arraycopy((quantity < 8) ? offsets_small : offsets, 0, offs, 0, lutType); - - final int dimension = world.provider.getDimension(); - - if (quantity < 27) { - final int[] scrambledLUT = new int[lutType]; - System.arraycopy(lut, 0, scrambledLUT, 0, scrambledLUT.length); - scramble(scrambledLUT, this.random); - int z = 0; - - while (count > 0) { - final IBlockState oreBlock = spawnData.getBlocks().getRandomBlock(random); - if (oreBlock.getBlock().equals(net.minecraft.init.Blocks.AIR)) return; - - if (!spawn(oreBlock, world, pos.add(offs[scrambledLUT[--count]]), dimension, true, - spawnData)) { - count++; - z++; - scramble(scrambledLUT, this.random); // rescramble the LUT - } else { - z = 0; - } - - if (z > 5) { - count--; - z = 0; - OreSpawn.LOGGER.warn("Unable to place block for chunk after 5 tries"); - } - } - - return; - } - - doSpawnFill(this.random.nextBoolean(), count, spawnData, world, pos); - } - - private void doSpawnFill(final boolean nextBoolean, final int quantity, - final ISpawnEntry spawnData, final World world, final BlockPos pos) { - final int count = quantity; - final double radius = Math.pow(quantity, 1.0 / 3.0) * (3.0 / 4.0 / Math.PI) + 2; - final int rSqr = (int) (radius * radius); - if (nextBoolean) { - spawnMungeNE(world, pos, rSqr, radius, spawnData, count); - } else { - spawnMungeSW(world, pos, rSqr, radius, spawnData, count); - } - } - - @Override - public void setRandom(final Random rand) { - this.random = rand; - } - - @Override - public JsonObject getDefaultParameters() { - final JsonObject defParams = new JsonObject(); - defParams.addProperty(Constants.FormatBits.MAX_SPREAD, 16); - defParams.addProperty(Constants.FormatBits.NODE_SIZE, 8); - defParams.addProperty(Constants.FormatBits.NODE_COUNT, 8); - defParams.addProperty(Constants.FormatBits.MIN_HEIGHT, 8); - defParams.addProperty(Constants.FormatBits.MAX_HEIGHT, 24); - defParams.addProperty(Constants.FormatBits.VARIATION, 4); - defParams.addProperty(Constants.FormatBits.FREQUENCY, 25); - defParams.addProperty(Constants.FormatBits.ATTEMPTS_MIN, 4); - defParams.addProperty(Constants.FormatBits.ATTEMPTS_MAX, 8); - return defParams; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/features/DefaultFeatureGenerator.java b/src/main/java/com/mcmoddev/orespawn/impl/features/DefaultFeatureGenerator.java deleted file mode 100644 index 37cfcab..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/features/DefaultFeatureGenerator.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.mcmoddev.orespawn.impl.features; - -import java.util.Random; - -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.api.FeatureBase; -import com.mcmoddev.orespawn.api.IFeature; -import com.mcmoddev.orespawn.api.os3.ISpawnEntry; -import com.mcmoddev.orespawn.data.Constants; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.Vec3i; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; - -public class DefaultFeatureGenerator extends FeatureBase implements IFeature { - - public DefaultFeatureGenerator() { - super(new Random()); - } - - @Override - public void generate(final World world, final IChunkGenerator chunkGenerator, - final IChunkProvider chunkProvider, final ISpawnEntry spawnData, final ChunkPos chunkPos) { - final ChunkPos pos = chunkPos; - final JsonObject params = spawnData.getFeature().getFeatureParameters(); - - // First, load cached blocks for neighboring chunk ore spawns - final int chunkX = pos.x; - final int chunkZ = pos.z; - - mergeDefaults(params, getDefaultParameters()); - - runCache(chunkX, chunkZ, world, spawnData); - - // now to ore spawn - - final int blockX = chunkX * 16 + 8; - final int blockZ = chunkZ * 16 + 8; - - final int minY = params.get(Constants.FormatBits.MIN_HEIGHT).getAsInt(); - final int maxY = params.get(Constants.FormatBits.MAX_HEIGHT).getAsInt(); - final int vari = params.get(Constants.FormatBits.VARIATION).getAsInt(); - final float freq = params.get(Constants.FormatBits.FREQUENCY).getAsFloat(); - final int size = params.get(Constants.FormatBits.NODE_SIZE).getAsInt(); - - if (freq >= 1) { - for (int i = 0; i < freq; i++) { - final int x = blockX + random.nextInt(16); - final int y = random.nextInt(maxY - minY) + minY; - final int z = blockZ + random.nextInt(16); - - final int r; - - if (vari > 0) { - r = random.nextInt(2 * vari) - vari; - } else { - r = 0; - } - spawnOre(world, spawnData, new BlockPos(x, y, z), size + r); - } - } else if (random.nextFloat() < freq) { - final int x = blockX + random.nextInt(8); - final int y = random.nextInt(maxY - minY) + minY; - final int z = blockZ + random.nextInt(8); - final int r; - - if (vari > 0) { - r = random.nextInt(2 * vari) - vari; - } else { - r = 0; - } - - spawnOre(world, spawnData, new BlockPos(x, y, z), size + r); - } - - } - - private void spawnOre(final World world, final ISpawnEntry spawnData, final BlockPos pos, - final int quantity) { - int count = quantity; - final int lutType = (quantity < 8) ? offsetIndexRef_small.length : offsetIndexRef.length; - final int[] lut = (quantity < 8) ? offsetIndexRef_small : offsetIndexRef; - final Vec3i[] offs = new Vec3i[lutType]; - - System.arraycopy((quantity < 8) ? offsets_small : offsets, 0, offs, 0, lutType); - - if (quantity < 27) { - final int[] scrambledLUT = new int[lutType]; - System.arraycopy(lut, 0, scrambledLUT, 0, scrambledLUT.length); - scramble(scrambledLUT, this.random); - - while (count > 0) { - final IBlockState oreBlock = spawnData.getBlocks().getRandomBlock(random); - if (oreBlock.getBlock().equals(net.minecraft.init.Blocks.AIR)) return; - final BlockPos target = pos.add(offs[scrambledLUT[--count]]); - spawn(oreBlock, world, target, world.provider.getDimension(), true, spawnData); - } - - return; - } - - doSpawnFill(this.random.nextBoolean(), count, world, spawnData, pos); - } - - private void doSpawnFill(final boolean nextBoolean, final int quantity, final World world, - final ISpawnEntry spawnData, final BlockPos pos) { - final int count = quantity; - final double radius = Math.pow(quantity, 1.0 / 3.0) * (3.0 / 4.0 / Math.PI) + 2; - final int rSqr = (int) (radius * radius); - if (nextBoolean) { - spawnMungeNE(world, pos, rSqr, radius, spawnData, count); - } else { - spawnMungeSW(world, pos, rSqr, radius, spawnData, count); - } - } - - @Override - public JsonObject getDefaultParameters() { - final JsonObject defParams = new JsonObject(); - defParams.addProperty(Constants.FormatBits.MIN_HEIGHT, 0); - defParams.addProperty(Constants.FormatBits.MAX_HEIGHT, 256); - defParams.addProperty(Constants.FormatBits.VARIATION, 16); - defParams.addProperty(Constants.FormatBits.FREQUENCY, 0.5); - defParams.addProperty(Constants.FormatBits.NODE_SIZE, 8); - return defParams; - } - - @Override - public void setRandom(final Random rand) { - this.random = rand; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/features/NormalCloudGenerator.java b/src/main/java/com/mcmoddev/orespawn/impl/features/NormalCloudGenerator.java deleted file mode 100644 index bd18dd3..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/features/NormalCloudGenerator.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.mcmoddev.orespawn.impl.features; - -import java.util.Random; - -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.FeatureBase; -import com.mcmoddev.orespawn.api.IFeature; -import com.mcmoddev.orespawn.api.os3.ISpawnEntry; -import com.mcmoddev.orespawn.data.Constants; - -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; - -public class NormalCloudGenerator extends FeatureBase implements IFeature { - - private NormalCloudGenerator(final Random rand) { - super(rand); - } - - public NormalCloudGenerator() { - this(new Random()); - } - - @Override - public void generate(final World world, final IChunkGenerator chunkGenerator, - final IChunkProvider chunkProvider, final ISpawnEntry spawnData, final ChunkPos chunkPos) { - final ChunkPos pos = chunkPos; - final JsonObject params = spawnData.getFeature().getFeatureParameters(); - - // First, load cached blocks for neighboring chunk ore spawns - final int chunkX = pos.x; - final int chunkZ = pos.z; - - mergeDefaults(params, getDefaultParameters()); - - runCache(chunkX, chunkZ, world, spawnData); - - // now to ore spawn - - // lets not offset blind, - final int blockX = chunkX * 16; - final int blockZ = chunkZ * 16; - - final int maxSpread = params.get(Constants.FormatBits.MAX_SPREAD).getAsInt(); - final int medianSize = params.get(Constants.FormatBits.MEDIAN_SIZE).getAsInt(); - final int minHeight = params.get(Constants.FormatBits.MIN_HEIGHT).getAsInt(); - final int maxHeight = params.get(Constants.FormatBits.MAX_HEIGHT).getAsInt(); - final int variance = params.get(Constants.FormatBits.VARIATION).getAsInt(); - int frequency = params.get(Constants.FormatBits.FREQUENCY).getAsInt(); - final int triesMin = params.get(Constants.FormatBits.ATTEMPTS_MIN).getAsInt(); - final int triesMax = params.get(Constants.FormatBits.ATTEMPTS_MAX).getAsInt(); - - // on the X and Z you have a possible 2-chunk range - 32 blocks - subtract the spread to get - // a size that will let us insert by the radius - final int offsetXZ = 32 - maxSpread; - - // you have the distance between minHeight and maxHeight - // this is the actual size of the space - final int sizeY = (maxHeight - minHeight); - final int offsetY = sizeY - maxSpread; - final int radiusXZ = offsetXZ / 2; - - // actual radius for placement is the size minus the spread to center it in the space and - // keep - // from overflowing - final int radiusY = offsetY / 2; - - // we center at the minimum plus the half the height - final int blockY = minHeight + (sizeY / 2); - - final int fSave = frequency; - int tryCount = 0; - - int tries; - - if (triesMax == triesMin) { - tries = triesMax; - } else { - tries = random.nextInt(triesMax - triesMin) + triesMin; - } - - while (tries > 0) { - if (this.random.nextInt(100) <= frequency) { - frequency = fSave; - final int x = blockX + getPoint(0, offsetXZ, radiusXZ) + radiusXZ; - // this should, hopefully, keep us centered between minHeight and maxHeight with - // nothing going above/below those values - final int y = blockY + getPoint(0, offsetY, radiusY); - final int z = blockZ + getPoint(0, offsetXZ, radiusXZ) + radiusXZ; - - int r = medianSize - variance; - - if (variance > 0) { - r += random.nextInt(2 * variance) - variance; - } - - final BlockPos p = new BlockPos(x, y, z); - - if (!spawnCloud(r, maxSpread, minHeight, maxHeight, p, spawnData, world) - && tryCount < 5) { - // make another try! - tries++; - frequency = 100; - tryCount++; - } else { - tryCount = 0; - } - } - - tries--; - } - } - - private boolean spawnCloud(final int size, final int maxSpread, final int minHeight, - final int maxHeight, final BlockPos pos, final ISpawnEntry spawnData, - final World world) { - // spawn one right at the center here, then generate for the cloud and do the math - - if (!spawn(spawnData.getBlocks().getRandomBlock(random), world, pos, - world.provider.getDimension(), true, spawnData)) { - return false; - } - - final int radius = maxSpread / 2; - boolean alreadySpewed = false; - int count = Math.min(size, (int) Math.round(Math.PI * Math.pow(radius, 2))); - - while (count > 0) { - int xp = getPoint(0, maxSpread, radius); - int yp = getPoint(minHeight, maxHeight, (maxHeight - minHeight) / 2); - int zp = getPoint(0, maxSpread, radius); - - BlockPos p = pos.add(xp, yp, zp); - - int z = 0; - - while (z < 5 && !spawn(spawnData.getBlocks().getRandomBlock(random), world, p, - world.provider.getDimension(), true, spawnData)) { - xp = getPoint(0, maxSpread, radius); - yp = getPoint(minHeight, maxHeight, (maxHeight - minHeight) / 2); - zp = getPoint(0, maxSpread, radius); - - p = pos.add(xp, yp, zp); - - z++; - } - - if (z >= 5 && !alreadySpewed) { - OreSpawn.LOGGER.info( - "unable to achieve requested cloud density for cloud centered at %s", pos); - alreadySpewed = true; - } - - count--; - } - - return true; - } - - @Override - public void setRandom(final Random rand) { - this.random = rand; - } - - @Override - public JsonObject getDefaultParameters() { - final JsonObject defParams = new JsonObject(); - defParams.addProperty(Constants.FormatBits.MAX_SPREAD, 16); - defParams.addProperty(Constants.FormatBits.MEDIAN_SIZE, 8); - defParams.addProperty(Constants.FormatBits.MIN_HEIGHT, 8); - defParams.addProperty(Constants.FormatBits.MAX_HEIGHT, 24); - defParams.addProperty(Constants.FormatBits.VARIATION, 4); - defParams.addProperty(Constants.FormatBits.FREQUENCY, 25); - defParams.addProperty(Constants.FormatBits.ATTEMPTS_MIN, 4); - defParams.addProperty(Constants.FormatBits.ATTEMPTS_MAX, 4); - return defParams; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/features/PrecisionGenerator.java b/src/main/java/com/mcmoddev/orespawn/impl/features/PrecisionGenerator.java deleted file mode 100644 index 0a88c5c..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/features/PrecisionGenerator.java +++ /dev/null @@ -1,294 +0,0 @@ -package com.mcmoddev.orespawn.impl.features; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.api.FeatureBase; -import com.mcmoddev.orespawn.api.IFeature; -import com.mcmoddev.orespawn.api.os3.ISpawnEntry; -import com.mcmoddev.orespawn.data.Constants.FormatBits; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.Vec3i; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; - -public class PrecisionGenerator extends FeatureBase implements IFeature { - - private PrecisionGenerator(final Random rand) { - super(rand); - } - - public PrecisionGenerator() { - this(new Random()); - } - - @Override - public void generate(final World world, final IChunkGenerator chunkGenerator, - final IChunkProvider chunkProvider, final ISpawnEntry spawnData, final ChunkPos posIn) { - final ChunkPos pos = posIn; - final JsonObject params = spawnData.getFeature().getFeatureParameters(); - - // First, load cached blocks for neighboring chunk ore spawns - final int chunkX = pos.x; - final int chunkZ = pos.z; - - mergeDefaults(params, getDefaultParameters()); - - runCache(chunkX, chunkZ, world, spawnData); - - // extract parameters - final int nodeCount = params.get(FormatBits.NODE_COUNT).getAsInt(); - final int maxHeight = params.get(FormatBits.MAX_HEIGHT).getAsInt(); - final int minHeight = params.get(FormatBits.MIN_HEIGHT).getAsInt(); - final int nodeSize = params.get(FormatBits.NODE_SIZE).getAsInt(); - - int thisNode = nodeSize; - - // now to use them - for (int c = nodeCount; c > 0; c--) { - int sc; - final HeightRange hr = new HeightRange(minHeight, maxHeight); - final BlockPos spot = chooseSpot(chunkX, chunkZ, hr); - - sc = spawnAtSpot(thisNode, hr, spot, new ChunkPos(chunkX, chunkZ), spawnData, world); - - // bit of feedback - if we underproduce or overproduce a node, the next one gets a - // correction - if (sc != thisNode && sc != 0) { - thisNode += (nodeSize - sc); - } else if (sc == thisNode) { - // if we produced exact size, reset the size - thisNode = nodeSize; - } - - // if we hit a node of size zero or less, we've done something wrong - if (thisNode <= 0) { - thisNode = nodeSize; - } - } - } - - private int spawnAtSpot(final int nodeSize, final HeightRange heightRange, final BlockPos spot, - final ChunkPos pos, final ISpawnEntry spawnData, final World world) { - int spawned = 0; - int c; - - BlockPos act = spot; - int counter = nodeSize; - - while (counter > 0 && spawned < nodeSize) { - c = spawnOreNode(act, pos, spawnData, world, nodeSize, heightRange); - - if (c == 0) { - act = chooseSpot(Math.floorDiv(spot.getX(), 16), Math.floorDiv(spot.getZ(), 16), - heightRange); - } - - counter -= (c + 1); - spawned += c; - } - - return spawned; - } - - private int spawnOreNode(final BlockPos loc, final ChunkPos pos, final ISpawnEntry spawnData, - final World world, final int nodeSize, final HeightRange heightRange) { - - int count = nodeSize; - final int lutType = (nodeSize < 8) ? offsetIndexRef_small.length : offsetIndexRef.length; - final int[] lut = (nodeSize < 8) ? offsetIndexRef_small : offsetIndexRef; - final Vec3i[] offs = new Vec3i[lutType]; - - System.arraycopy((nodeSize < 8) ? offsets_small : offsets, 0, offs, 0, lutType); - - if (nodeSize < 27) { - final int[] scrambledLUT = new int[lutType]; - System.arraycopy(lut, 0, scrambledLUT, 0, scrambledLUT.length); - scramble(scrambledLUT, this.random); - - int nc = 0; - - for (; count > 0 && nc <= nodeSize; count--) { - final IBlockState oreBlock = spawnData.getBlocks().getRandomBlock(this.random); - final Vec3i offset = offs[scrambledLUT[--count]]; - final BlockPos p = fixMungeOffset(offset, loc, heightRange, pos); - final int dimension = world.provider.getDimension(); - - if (spawn(oreBlock, world, p, dimension, true, spawnData)) { - nc++; - } - } - - return nc; - } - - return spawnFill(spawnData, world, pos, loc, nodeSize, heightRange); - } - - private BlockPos fixMungeOffset(final Vec3i offset, final BlockPos spot, - final HeightRange heightRange, final ChunkPos pos) { - final BlockPos p = spot.add(offset); - final ChunkPos x1z1 = new ChunkPos(pos.x + 1, pos.z + 1); - final int xMax = x1z1.getXEnd(); - final int zMax = x1z1.getZEnd(); - final int xMin = pos.getXStart(); - final int zMin = pos.getZStart(); - - int xmod = offset.getX(); - int ymod = offset.getY(); - int zmod = offset.getZ(); - - // correct the points values to not cause the Y coordinate to go outside the permissable - // range - if (p.getY() < heightRange.getMin() || p.getY() > heightRange.getMax()) { - ymod = rescaleOffset(ymod, spot.getY(), heightRange.getMin(), heightRange.getMax()); - } - - if (p.getX() < xMin || p.getX() > xMax) { - xmod = rescaleOffset(xmod, spot.getX(), xMin, xMax); - } - - if (p.getZ() < zMin || p.getZ() > zMax) { - zmod = rescaleOffset(zmod, spot.getZ(), zMin, zMax); - } - - return spot.add(xmod, ymod, zmod); - } - - private int rescaleOffset(final int offsetIn, final int centerIn, final int minimumIn, - final int maximumIn) { - final int actual = centerIn + offsetIn; - int wrapDistance; - final int range = maximumIn - minimumIn; - int workingPoint; - - if (actual < minimumIn) { - wrapDistance = minimumIn - actual; - } else { - wrapDistance = actual - maximumIn; - } - - if (wrapDistance < 0) { - wrapDistance = ((-1) * wrapDistance) % range; - } else { - wrapDistance %= range; - } - - if (actual < minimumIn) { - workingPoint = maximumIn - wrapDistance; - } else { - workingPoint = minimumIn + wrapDistance; - } - - return workingPoint - centerIn; - } - - private int spawnFill(final ISpawnEntry spawnData, final World world, final ChunkPos pos, - final BlockPos loc, final int nodeSize, final HeightRange heightRange) { - - final double radius = Math.pow(nodeSize, 1.0 / 3.0) * (3.0 / 4.0 / Math.PI) + 2; - final int rSqr = (int) Math.ceil(radius * radius); - - return spawnPrecise(spawnData, world, pos, loc, heightRange, !this.random.nextBoolean(), radius, rSqr, - nodeSize); - } - - private int spawnPrecise(final ISpawnEntry spawnData, final World world, final ChunkPos pos, - final BlockPos loc, final HeightRange heightRange, final boolean toPositive, - final double radius, final int rSqr, final int nodeSize) { - int quantity = nodeSize; - int nc = 0; - - for (int dy = (int) (-1 * radius); dy < radius; dy++) { - for (int dx = getStart(toPositive, radius); endCheck(toPositive, dx, - radius); dx = countItem(dx, toPositive)) { - for (int dz = getStart(toPositive, radius); endCheck(toPositive, dz, - radius); dz = countItem(dz, toPositive)) { - if (doCheckSpawn(dx, dy, dz, rSqr, heightRange, spawnData, world, pos, - loc) >= 0) { - nc++; - quantity--; - - if (nc >= nodeSize || quantity <= 0) { - return nc; - } - } - } - } - } - - return nc; - } - - private int doCheckSpawn(final int dx, final int dy, final int dz, final int rSqr, - final HeightRange heightRange, final ISpawnEntry spawnData, final World world, - final ChunkPos pos, final BlockPos loc) { - if (getABC(dx, dy, dz) <= rSqr) { - final BlockPos p = fixMungeOffset(new Vec3i(dx, dy, dz), loc, heightRange, pos); - final IBlockState bl = spawnData.getBlocks().getRandomBlock(this.random); - if (bl.getBlock().equals(net.minecraft.init.Blocks.AIR)) return -1; - return spawn(bl, world, p, world.provider.getDimension(), true, spawnData) ? 1 : 0; - } - - return -1; - } - - private int getPoint(final int lowerBound, final int upperBound) { - final List arr = new ArrayList<>(); - - for (int i = lowerBound; i <= upperBound; i++) { - arr.add(i); - } - - return arr.get(this.random.nextInt(arr.size())); - } - - private BlockPos chooseSpot(final int xPosition, final int zPosition, - final HeightRange heightRange) { - final int xRet = getPoint(0, 15) + (xPosition * 16); - final int zRet = getPoint(0, 15) + (zPosition * 16); - final int yRet = getPoint(heightRange.getMin(), heightRange.getMax()); - - return new BlockPos(xRet, yRet, zRet); - } - - @Override - public void setRandom(final Random rand) { - this.random = rand; - } - - @Override - public JsonObject getDefaultParameters() { - final JsonObject defaults = new JsonObject(); - defaults.addProperty(FormatBits.NODE_COUNT, 4); - defaults.addProperty(FormatBits.MIN_HEIGHT, 16); - defaults.addProperty(FormatBits.MAX_HEIGHT, 80); - defaults.addProperty(FormatBits.NODE_SIZE, 8); - return defaults; - } - - private class HeightRange { - - private int min; - private int max; - - HeightRange(final int min, final int max) { - this.min = min; - this.max = max; - } - - int getMin() { - return this.min; - } - - int getMax() { - return this.max; - } - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/features/UnderFluid.java b/src/main/java/com/mcmoddev/orespawn/impl/features/UnderFluid.java deleted file mode 100644 index f1c4697..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/features/UnderFluid.java +++ /dev/null @@ -1,212 +0,0 @@ -/** - * - */ -package com.mcmoddev.orespawn.impl.features; - -import java.util.Random; -import java.util.Set; -import java.util.HashSet; -import java.util.List; -import java.util.stream.StreamSupport; -import java.util.stream.Collectors; - -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.api.FeatureBase; -import com.mcmoddev.orespawn.api.IFeature; -import com.mcmoddev.orespawn.api.os3.ISpawnEntry; -import com.mcmoddev.orespawn.data.Constants; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.Vec3i; -import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; - -/** - * @author Daniel Hazelton - * - */ -public class UnderFluid extends FeatureBase implements IFeature { - - /** - * @param rand - */ - public UnderFluid() { - super(new Random()); - } - - /** - * Try to generate this feature to the specified parameters in the specified chunk. - *

- *

Theory: - *

For up to 2*maximum_tries pick a random spot in the spawn zone do: - *

Check the 5x5x5 region around that spot for the fluid: - *

if found, store the BlockPos of the fluid, if this store has reached maximum_tries entries, stop iteration - *

For each of the found positions, if any, seek up and down from the position to find the lower bound of the fluid - *

At the fluids lower bound, generate the node. - *

- * - * @param world {@link net.minecraft.world.World} World this chunk is in - * @param chunkGenerator {@link net.minecraft.world.gen.IChunkGenerator} Chunk generator for this chunk - * @param chunkProvider {@link net.minecraft.world.chunk.IChunkGenerator} Chunk provider for this chunk - * @param spawnData {@link com.mcmoddev.orespawn.api.os3.ISpawnEntry} Parameters and data on this spawn from the configuration file - * @param chunkPos {@link net.minecraft.util.math.ChunkPos} Absolute in-world coordinates, on the chunk grid, for this chunk (can get lowest value X/Z block coordinates for this chunk by multiplying provided X/Z by 16) - * @see com.mcmoddev.orespawn.api.IFeature#generate(net.minecraft.world.World, net.minecraft.world.gen.IChunkGenerator, net.minecraft.world.chunk.IChunkProvider, com.mcmoddev.orespawn.api.os3.ISpawnEntry, net.minecraft.util.math.ChunkPos) - */ - @Override - public void generate(final World world, final IChunkGenerator chunkGenerator, - final IChunkProvider chunkProvider, final ISpawnEntry spawnData, final ChunkPos chunkPos) { - final ChunkPos pos = chunkPos; - final JsonObject params = spawnData.getFeature().getFeatureParameters(); - - // First, load cached blocks for neighboring chunk ore spawns - final int chunkX = pos.x; - final int chunkZ = pos.z; - - mergeDefaults(params, getDefaultParameters()); - - runCache(chunkX, chunkZ, world, spawnData); - - // now to ore spawn - - final int blockX = chunkX * 16 + 8; - final int blockZ = chunkZ * 16 + 8; - - - final int minHeight = params.get(Constants.FormatBits.MIN_HEIGHT).getAsInt(); - final int maxHeight = params.get(Constants.FormatBits.MAX_HEIGHT).getAsInt(); - final int variance = params.get(Constants.FormatBits.VARIATION).getAsInt(); - final int triesMin = params.get(Constants.FormatBits.ATTEMPTS_MIN).getAsInt(); - final int triesMax = params.get(Constants.FormatBits.ATTEMPTS_MAX).getAsInt(); - final int nodeSize = params.get(Constants.FormatBits.NODE_SIZE).getAsInt(); - final Fluid fluid = FluidRegistry.getFluid(params.get(Constants.FormatBits.FLUID).getAsString()); - - int tries = this.random.nextInt(triesMax - triesMin + 1) + triesMin; - int ySpan = maxHeight - minHeight; - int surveySize = ((256 * (16 * ySpan)) / 4) / 125; - BlockPos refBlock = new BlockPos(blockX, minHeight, blockZ); - Block fluidBlock = fluid.getBlock(); - - Set found = new HashSet<>(); - - int surveyCount = 0; - int spawnCount = 0; - - while(surveyCount < surveySize && spawnCount < tries) { - BlockPos sampleCenter = refBlock.add(this.random.nextInt(16), this.random.nextInt(ySpan), this.random.nextInt(16)); - BlockPos lowSide = sampleCenter.add(-2,-2,-2); - BlockPos highSide = sampleCenter.add(2,2,2); - Chunk chunk = world.getChunk(sampleCenter); - - if(!found.contains(sampleCenter)) { - found.addAll(findPossibleTargets(chunk, lowSide, highSide, fluidBlock, minHeight)); - - if(!found.isEmpty()) { - BlockPos target = found.toArray(new BlockPos[0])[this.random.nextInt(found.size())]; - spawnCount += maybeSpawn(target, minHeight, maxHeight, nodeSize, variance, world, spawnData); - } - surveyCount++; - } - } - } - - private int maybeSpawn(BlockPos target, int minHeight, int maxHeight, int nodeSize, - int variance, World world, ISpawnEntry spawnData) { - BlockPos mp = target; - while(world.getBlockState(mp).getMaterial().isLiquid() && mp.getY() >= minHeight) { - mp = mp.down(); - } - - if (mp.getY() > minHeight && mp.getY() < maxHeight) { - // calculate actual size for this node - int size = this.random.nextInt(nodeSize - variance + 1) + this.random.nextInt(variance); - // try to spawn now, as we do ***NOT*** want the node to wrap, we have to do this different... - // so... we copy vanilla spawn logic, to a degree, I think - spawnOre(world, spawnData, mp, size); - return 1; - } - - - return 0; - } - - private List findPossibleTargets(Chunk chunk, BlockPos lowSide, BlockPos highSide, - Block fluidBlock, int minHeight) { - return StreamSupport.stream(BlockPos.getAllInBoxMutable(lowSide, highSide).spliterator(), false) - .filter( bp -> chunk.getBlockState(bp).getMaterial().isLiquid() && - chunk.getBlockState(bp).getBlock().equals(fluidBlock) && - bp.getY() >= minHeight ) - .map(BlockPos.MutableBlockPos::toImmutable) - .collect(Collectors.toList()); - } - - private void spawnOre(final World world, final ISpawnEntry spawnData, final BlockPos pos, - final int quantity) { - int count = quantity; - final int lutType = (quantity < 8) ? offsetIndexRef_small.length : offsetIndexRef.length; - final int[] lut = (quantity < 8) ? offsetIndexRef_small : offsetIndexRef; - final Vec3i[] offs = new Vec3i[lutType]; - - System.arraycopy((quantity < 8) ? offsets_small : offsets, 0, offs, 0, lutType); - - if (quantity < 27) { - final int[] scrambledLUT = new int[lutType]; - System.arraycopy(lut, 0, scrambledLUT, 0, scrambledLUT.length); - scramble(scrambledLUT, this.random); - - while (count > 0) { - final IBlockState oreBlock = spawnData.getBlocks().getRandomBlock(random); - if (oreBlock.getBlock().equals(net.minecraft.init.Blocks.AIR)) return; - final BlockPos target = pos.add(offs[scrambledLUT[--count]]); - spawn(oreBlock, world, target, world.provider.getDimension(), true, spawnData); - } - - return; - } - - doSpawnFill(this.random.nextBoolean(), count, world, spawnData, pos); - } - - private void doSpawnFill(final boolean nextBoolean, final int quantity, final World world, - final ISpawnEntry spawnData, final BlockPos pos) { - final int count = quantity; - final double radius = Math.pow(quantity, 1.0 / 3.0) * (3.0 / 4.0 / Math.PI) + 2; - final int rSqr = (int) (radius * radius); - if (nextBoolean) { - spawnMungeNE(world, pos, rSqr, radius, spawnData, count); - } else { - spawnMungeSW(world, pos, rSqr, radius, spawnData, count); - } - } - - /* (non-Javadoc) - * @see com.mcmoddev.orespawn.api.IFeature#setRandom(java.util.Random) - */ - @Override - public void setRandom(Random rand) { - this.random = rand; - } - - /* (non-Javadoc) - * @see com.mcmoddev.orespawn.api.IFeature#getDefaultParameters() - */ - @Override - public JsonObject getDefaultParameters() { - final JsonObject defParams = new JsonObject(); - defParams.addProperty(Constants.FormatBits.MIN_HEIGHT, 0); - defParams.addProperty(Constants.FormatBits.MAX_HEIGHT, 256); - defParams.addProperty(Constants.FormatBits.VARIATION, 16); - defParams.addProperty(Constants.FormatBits.ATTEMPTS_MIN, 4); - defParams.addProperty(Constants.FormatBits.ATTEMPTS_MAX, 4); - defParams.addProperty(Constants.FormatBits.NODE_SIZE, 8); - defParams.addProperty(Constants.FormatBits.FLUID, "water"); - return defParams; - } - -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/features/VeinGenerator.java b/src/main/java/com/mcmoddev/orespawn/impl/features/VeinGenerator.java deleted file mode 100644 index dd3288c..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/features/VeinGenerator.java +++ /dev/null @@ -1,583 +0,0 @@ -package com.mcmoddev.orespawn.impl.features; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Random; - -import com.google.common.collect.Lists; -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.FeatureBase; -import com.mcmoddev.orespawn.api.IFeature; -import com.mcmoddev.orespawn.api.os3.ISpawnEntry; -import com.mcmoddev.orespawn.data.Constants; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.WeightedRandom; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.Vec3i; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; - -public class VeinGenerator extends FeatureBase implements IFeature { - - private VeinGenerator(final Random rand) { - super(rand); - } - - public VeinGenerator() { - this(new Random()); - } - - @Override - public void generate(final World world, final IChunkGenerator chunkGenerator, - final IChunkProvider chunkProvider, final ISpawnEntry spawnData, final ChunkPos _pos) { - final ChunkPos pos = _pos; - final JsonObject params = spawnData.getFeature().getFeatureParameters(); - - // First, load cached blocks for neighboring chunk ore spawns - final int chunkX = pos.x; - final int chunkZ = pos.z; - - runCache(chunkX, chunkZ, world, spawnData); - mergeDefaults(params, getDefaultParameters()); - - // now to ore spawn - - final int blockX = chunkX * 16 + 8; - final int blockZ = chunkZ * 16 + 8; - - final int minY = params.get(Constants.FormatBits.MIN_HEIGHT).getAsInt(); - final int maxY = params.get(Constants.FormatBits.MAX_HEIGHT).getAsInt(); - final int vari = params.get(Constants.FormatBits.VARIATION).getAsInt(); - final int freq = params.get(Constants.FormatBits.FREQUENCY).getAsInt(); - final int length = params.get(Constants.FormatBits.LENGTH).getAsInt(); - final EnumFacing startingFace = getFaceFromString( - params.get(Constants.FormatBits.STARTINGFACE).getAsString()); - final int nodeSize = params.get(Constants.FormatBits.NODE_SIZE).getAsInt(); - final int triesMin = params.get(Constants.FormatBits.ATTEMPTS_MIN).getAsInt(); - final int triesMax = params.get(Constants.FormatBits.ATTEMPTS_MAX).getAsInt(); - - int tries; - - if (triesMax == triesMin) { - tries = triesMax; - } else { - tries = random.nextInt(triesMax - triesMin) + triesMin; - } - - // we have an offset into the chunk but actually need something more - while (tries > 0) { - if (this.random.nextInt(100) <= freq) { - final int x = blockX + random.nextInt(16); - final int y = random.nextInt(maxY - minY) + minY; - final int z = blockZ + random.nextInt(16); - - final int r; - - if (vari > 0) { - r = random.nextInt(2 * vari) - vari; - } else { - r = 0; - } - - spawnVein(length + r, nodeSize, startingFace, new BlockPos(x, y, z), spawnData, - world); - } - - tries--; - } - } - - private EnumFacing getFaceFromString(final String direction) { - final String work = direction.toLowerCase(); - switch (work) { - case "north": - return EnumFacing.NORTH; - case "south": - return EnumFacing.SOUTH; - case "east": - return EnumFacing.EAST; - case "west": - return EnumFacing.WEST; - case "down": - return EnumFacing.DOWN; - case "up": - return EnumFacing.UP; - case "random": - return EnumFacing.VALUES[this.random.nextInt(EnumFacing.VALUES.length)]; - case "vertical": - return this.random.nextBoolean() ? EnumFacing.UP : EnumFacing.DOWN; - case "horizontal": - return EnumFacing.HORIZONTALS[this.random.nextInt(EnumFacing.HORIZONTALS.length)]; - default: - OreSpawn.LOGGER.error( - "Invalid value %s found in parameters for vein spawn, returning \"north\"", - direction); - return EnumFacing.NORTH; - } - } - - private enum EnumSquare { - TOP_EDGE(0), LEFT_EDGE(1), BOTTOM_EDGE(2), RIGHT_EDGE(3), LEFT_TOP(4), LEFT_BOTTOM(5), - RIGHT_TOP(6), RIGHT_BOTTOM(7), FACE(8); - - private int index; - - private EnumSquare(int index) { - this.index = index; - } - - final public int getIndex() { - return this.index; - } - } - - private void spawnVein(final int veinLength, final int nodeSize, final EnumFacing startingFace, - final BlockPos blockPos, final ISpawnEntry spawnData, final World world) { - EnumFacing face = startingFace; - EnumSquare square = EnumSquare.values()[this.random.nextInt(EnumSquare.values().length)]; - BlockPos workingPos = new BlockPos(blockPos); - - if (!spawnData.getMatcher().test(world.getBlockState(blockPos))) { - return; - } - - // build vein - final List points = Lists.newLinkedList(); - for (; points.size() < veinLength;) { - points.add(workingPos); - List nextFaces = getNextFaceSet(square, face); - - if (!nextFaces.isEmpty()) { - BlockPos temp = workingPos; - for (EnumFacing f : nextFaces) { - temp = temp.offset(f, 1); - } - nextFaces.clear(); - points.add(temp); - workingPos = temp; - } - - face = getNextStartingFace(square, face); - square = getNextSquare(); - } - - spawnOre(world, spawnData, blockPos, nodeSize); - for (final BlockPos pos : points) { - spawnOre(world, spawnData, pos, nodeSize); - } - } - - private class SquareWeight extends WeightedRandom.Item { - - private EnumSquare item; - - public SquareWeight(EnumSquare item, int weight) { - super(weight); - this.item = item; - } - } - - private EnumSquare getNextSquare() { - float[] weights = new float[] { - 0.12f, 0.12f, 0.12f, 0.12f, 0.0475f, 0.0475f, 0.0475f, 0.0475f, 0.33f - }; - List items = new ArrayList<>(); - - for (EnumSquare sq : EnumSquare.values()) { - items.add(new SquareWeight(sq, (int) (weights[sq.getIndex()] * 10000))); - } - - return ((SquareWeight) WeightedRandom.getRandomItem(this.random, items)).item; - } - - private static final EnumFacing[][][] congruentSquares = new EnumFacing[][][] { - // Index 0 - DOWN - new EnumFacing[][] { - new EnumFacing[] { - EnumFacing.SOUTH, null - }, // TOP_EDGE - new EnumFacing[] { - EnumFacing.WEST, null - }, // LEFT_EDGE - new EnumFacing[] { - EnumFacing.NORTH, null - }, // BOTTOM_EDGE - new EnumFacing[] { - EnumFacing.EAST, null - }, // RIGHT_EDGE - new EnumFacing[] { - EnumFacing.SOUTH, EnumFacing.WEST - }, // LEFT_TOP - new EnumFacing[] { - EnumFacing.NORTH, EnumFacing.WEST - }, // LEFT_BOTTOM - new EnumFacing[] { - EnumFacing.SOUTH, EnumFacing.EAST - }, // RIGHT_BOTTOM - new EnumFacing[] { - EnumFacing.SOUTH, EnumFacing.EAST - } // RIGHT_TOP - }, new EnumFacing[][] { - // Index 1 - UP - new EnumFacing[] { - EnumFacing.SOUTH, null - }, // TOP_EDGE - new EnumFacing[] { - EnumFacing.WEST, null - }, // LEFT_EDGE - new EnumFacing[] { - EnumFacing.NORTH, null - }, // BOTTOM_EDGE - new EnumFacing[] { - EnumFacing.EAST, null - }, // RIGHT_EDGE - new EnumFacing[] { - EnumFacing.SOUTH, EnumFacing.WEST - }, // LEFT_TOP - new EnumFacing[] { - EnumFacing.NORTH, EnumFacing.WEST - }, // LEFT_BOTTOM - new EnumFacing[] { - EnumFacing.SOUTH, EnumFacing.EAST - }, // RIGHT_BOTTOM - new EnumFacing[] { - EnumFacing.SOUTH, EnumFacing.EAST - } // RIGHT_TOP - }, new EnumFacing[][] { - // Index 2 - NORTH - new EnumFacing[] { - EnumFacing.UP, null - }, // TOP_EDGE - new EnumFacing[] { - EnumFacing.WEST, null - }, // LEFT_EDGE - new EnumFacing[] { - EnumFacing.DOWN, null - }, // BOTTOM_EDGE - new EnumFacing[] { - EnumFacing.EAST, null - }, // RIGHT_EDGE - new EnumFacing[] { - EnumFacing.UP, EnumFacing.WEST - }, // LEFT_TOP - new EnumFacing[] { - EnumFacing.DOWN, EnumFacing.WEST - }, // LEFT_BOTTOM - new EnumFacing[] { - EnumFacing.DOWN, EnumFacing.EAST - }, // RIGHT_BOTTOM - new EnumFacing[] { - EnumFacing.UP, EnumFacing.EAST - } // RIGHT_TOP - }, new EnumFacing[][] { - // Index 3 - SOUTH - new EnumFacing[] { - EnumFacing.UP, null - }, // TOP_EDGE - new EnumFacing[] { - EnumFacing.EAST, null - }, // LEFT_EDGE - new EnumFacing[] { - EnumFacing.DOWN, null - }, // BOTTOM_EDGE - new EnumFacing[] { - EnumFacing.WEST, null - }, // RIGHT_EDGE - new EnumFacing[] { - EnumFacing.UP, EnumFacing.EAST - }, // LEFT_TOP - new EnumFacing[] { - EnumFacing.DOWN, EnumFacing.EAST - }, // LEFT_BOTTOM - new EnumFacing[] { - EnumFacing.DOWN, EnumFacing.WEST - }, // RIGHT_BOTTOM - new EnumFacing[] { - EnumFacing.UP, EnumFacing.WEST - } // RIGHT_TOP - }, new EnumFacing[][] { - // Index 4 - WEST - new EnumFacing[] { - EnumFacing.UP, null - }, // TOP_EDGE - new EnumFacing[] { - EnumFacing.SOUTH, null - }, // LEFT_EDGE - new EnumFacing[] { - EnumFacing.DOWN, null - }, // BOTTOM_EDGE - new EnumFacing[] { - EnumFacing.NORTH, null - }, // RIGHT_EDGE - new EnumFacing[] { - EnumFacing.UP, EnumFacing.SOUTH - }, // LEFT_TOP - new EnumFacing[] { - EnumFacing.DOWN, EnumFacing.SOUTH - }, // LEFT_BOTTOM - new EnumFacing[] { - EnumFacing.DOWN, EnumFacing.NORTH - }, // RIGHT_BOTTOM - new EnumFacing[] { - EnumFacing.UP, EnumFacing.NORTH - } // RIGHT_TOP - }, new EnumFacing[][] { - // Index 5 - EAST - new EnumFacing[] { - EnumFacing.UP, null - }, // TOP_EDGE - new EnumFacing[] { - EnumFacing.NORTH, null - }, // LEFT_EDGE - new EnumFacing[] { - EnumFacing.DOWN, null - }, // BOTTOM_EDGE - new EnumFacing[] { - EnumFacing.SOUTH, null - }, // RIGHT_EDGE - new EnumFacing[] { - EnumFacing.UP, EnumFacing.NORTH - }, // LEFT_TOP - new EnumFacing[] { - EnumFacing.DOWN, EnumFacing.NORTH - }, // LEFT_BOTTOM - new EnumFacing[] { - EnumFacing.DOWN, EnumFacing.SOUTH - }, // RIGHT_BOTTOM - new EnumFacing[] { - EnumFacing.UP, EnumFacing.SOUTH - } // RIGHT_TOP - } - }; - - private EnumFacing getNextStartingFace(EnumSquare square, EnumFacing face) { - - if ((this.random.nextBoolean()) || (square == EnumSquare.FACE)) { - return face; - } - - EnumFacing[] possibles = Arrays.asList(congruentSquares[face.getIndex()][square.getIndex()]) - .stream().filter(it -> it != null).toArray(EnumFacing[]::new); - - if (possibles.length > 1) { - return possibles[this.random.nextInt(possibles.length)]; - } - return possibles[0]; - } - - private List getNextFaceSet(EnumSquare square, EnumFacing face) { - List rv = new ArrayList<>(); - - rv.add(face); - - switch (square) { - case BOTTOM_EDGE: - switch (face) { - case EAST: - case WEST: - case NORTH: - case SOUTH: - rv.add(EnumFacing.DOWN); - break; - case UP: - case DOWN: - rv.add(EnumFacing.NORTH); - break; - default: - break; - } - break; - case TOP_EDGE: - switch (face) { - case EAST: - case WEST: - case NORTH: - case SOUTH: - rv.add(EnumFacing.UP); - break; - case UP: - case DOWN: - rv.add(EnumFacing.SOUTH); - break; - default: - break; - } - break; - case LEFT_EDGE: - switch (face) { - case EAST: - case WEST: - case NORTH: - case SOUTH: - rv.add(face.rotateYCCW()); - break; - case UP: - case DOWN: - rv.add(EnumFacing.EAST); - break; - default: - break; - } - break; - case RIGHT_EDGE: - switch (face) { - case EAST: - case WEST: - case NORTH: - case SOUTH: - rv.add(face.rotateY()); - break; - case UP: - case DOWN: - rv.add(EnumFacing.WEST); - break; - default: - break; - } - break; - case FACE: - break; - case LEFT_TOP: - switch (face) { - case EAST: - case WEST: - case NORTH: - case SOUTH: - rv.add(face.rotateYCCW()); - rv.add(EnumFacing.UP); - break; - case UP: - case DOWN: - rv.add(EnumFacing.EAST); - rv.add(EnumFacing.SOUTH); - break; - default: - break; - } - break; - case LEFT_BOTTOM: - switch (face) { - case EAST: - case WEST: - case NORTH: - case SOUTH: - rv.add(face.rotateYCCW()); - rv.add(EnumFacing.DOWN); - break; - case UP: - case DOWN: - rv.add(EnumFacing.EAST); - rv.add(EnumFacing.NORTH); - break; - default: - break; - } - break; - case RIGHT_TOP: - switch (face) { - case EAST: - case WEST: - case NORTH: - case SOUTH: - rv.add(face.rotateY()); - rv.add(EnumFacing.UP); - break; - case UP: - case DOWN: - rv.add(EnumFacing.EAST); - rv.add(EnumFacing.SOUTH); - break; - default: - break; - } - break; - case RIGHT_BOTTOM: - switch (face) { - case EAST: - case WEST: - case NORTH: - case SOUTH: - rv.add(face.rotateY()); - rv.add(EnumFacing.DOWN); - break; - case UP: - case DOWN: - rv.add(EnumFacing.EAST); - rv.add(EnumFacing.NORTH); - break; - default: - break; - } - break; - default: - break; - } - - return rv; - } - - private void spawnOre(final World world, final ISpawnEntry spawnData, final BlockPos pos, - final int quantity) { - int count = quantity; - final int lutType = (quantity < 8) ? offsetIndexRef_small.length : offsetIndexRef.length; - final int[] lut = (quantity < 8) ? offsetIndexRef_small : offsetIndexRef; - final Vec3i[] offs = new Vec3i[lutType]; - - System.arraycopy((quantity < 8) ? offsets_small : offsets, 0, offs, 0, lutType); - - if (quantity < 27) { - final int[] scrambledLUT = new int[lutType]; - System.arraycopy(lut, 0, scrambledLUT, 0, scrambledLUT.length); - scramble(scrambledLUT, this.random); - - while (count > 0) { - final IBlockState oreBlock = spawnData.getBlocks().getRandomBlock(random); - if (oreBlock.getBlock().equals(net.minecraft.init.Blocks.AIR)) return; - final BlockPos target = pos.add(offs[scrambledLUT[--count]]); - spawn(oreBlock, world, target, world.provider.getDimension(), true, spawnData); - } - - return; - } - - doSpawnFill(this.random.nextBoolean(), count, world, spawnData, pos); - } - - private void doSpawnFill(final boolean nextBoolean, final int quantity, final World world, - final ISpawnEntry spawnData, final BlockPos pos) { - final int count = quantity; - final double radius = Math.pow(quantity, 1.0 / 3.0) * (3.0 / 4.0 / Math.PI) + 2; - final int rSqr = (int) (radius * radius); - if (nextBoolean) { - spawnMungeNE(world, pos, rSqr, radius, spawnData, count); - } else { - spawnMungeSW(world, pos, rSqr, radius, spawnData, count); - } - } - - @Override - public JsonObject getDefaultParameters() { - final JsonObject defParams = new JsonObject(); - defParams.addProperty(Constants.FormatBits.MIN_HEIGHT, 0); - defParams.addProperty(Constants.FormatBits.MAX_HEIGHT, 256); - defParams.addProperty(Constants.FormatBits.VARIATION, 16); - defParams.addProperty(Constants.FormatBits.FREQUENCY, 50); - defParams.addProperty(Constants.FormatBits.ATTEMPTS_MAX, 8); - defParams.addProperty(Constants.FormatBits.ATTEMPTS_MIN, 4); - defParams.addProperty(Constants.FormatBits.LENGTH, 16); - defParams.addProperty(Constants.FormatBits.STARTINGFACE, "north"); - defParams.addProperty(Constants.FormatBits.NODE_SIZE, 3); - return defParams; - } - - @Override - public void setRandom(final Random rand) { - this.random = rand; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationAcceptAny.java b/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationAcceptAny.java deleted file mode 100644 index 057eacc..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationAcceptAny.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.mcmoddev.orespawn.impl.location; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.api.BiomeLocation; -import com.mcmoddev.orespawn.data.Constants.ConfigNames; - -import net.minecraft.world.biome.Biome; - -public class BiomeLocationAcceptAny implements BiomeLocation { - - @Override - public boolean matches(final Biome biome) { - return true; - } - - @Override - public JsonElement serialize() { - final JsonObject rv = new JsonObject(); - rv.add(ConfigNames.BLACKLIST, new JsonArray()); - return rv; - } - -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationComposition.java b/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationComposition.java deleted file mode 100644 index 4abce92..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationComposition.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.mcmoddev.orespawn.impl.location; - -import java.util.LinkedList; -import java.util.List; -import java.util.Objects; - -import com.google.common.collect.ImmutableList; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.api.BiomeLocation; -import com.mcmoddev.orespawn.data.Constants; - -import net.minecraft.world.biome.Biome; - -public final class BiomeLocationComposition implements BiomeLocation { - - private final BiomeLocation inclusions; - - private final BiomeLocation exclusions; - - private final int hash; - - public BiomeLocationComposition(final BiomeLocation inclusions, - final BiomeLocation exclusions) { - this.inclusions = inclusions; - this.exclusions = exclusions; - this.hash = Objects.hash(inclusions, exclusions); - } - - @Override - public boolean matches(final Biome biome) { - final boolean inWhite = this.inclusions.matches(biome); - final boolean inBlack = this.exclusions.matches(biome); - - return !inBlack && inWhite; - } - - @Override - public int hashCode() { - return this.hash; - } - - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - - if (obj instanceof BiomeLocationComposition) { - final BiomeLocationComposition other = (BiomeLocationComposition) obj; - return this.inclusions.equals(other.inclusions) - && this.exclusions.equals(other.exclusions); - } - - return false; - } - - @Override - public ImmutableList getBiomes() { - final List temp = new LinkedList<>(); - temp.addAll(this.inclusions.getBiomes()); - temp.addAll(this.exclusions.getBiomes()); - return ImmutableList.copyOf(temp); - } - - public BiomeLocation getInclusions() { - return this.inclusions; - } - - public BiomeLocation getExclusions() { - return this.exclusions; - } - - @Override - public JsonElement serialize() { - final JsonObject rv = new JsonObject(); - - rv.add(Constants.ConfigNames.BLACKLIST, this.exclusions.serialize()); - if (!(this.inclusions instanceof BiomeLocationEmpty)) { - rv.add(Constants.ConfigNames.WHITELIST, this.inclusions.serialize()); - } - - return rv; - } - -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationDictionary.java b/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationDictionary.java deleted file mode 100644 index d45d846..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationDictionary.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.mcmoddev.orespawn.impl.location; - -import com.google.common.collect.ImmutableList; -import com.google.gson.JsonElement; -import com.google.gson.JsonPrimitive; -import com.mcmoddev.orespawn.api.BiomeLocation; - -import net.minecraft.world.biome.Biome; -import net.minecraftforge.common.BiomeDictionary; - -public final class BiomeLocationDictionary implements BiomeLocation { - - private final BiomeDictionary.Type type; - - private final int hash; - - public BiomeLocationDictionary(final BiomeDictionary.Type type) { - this.type = type; - this.hash = type.hashCode(); - } - - @Override - public boolean matches(final Biome biome) { - return BiomeDictionary.hasType(biome, this.type); - } - - @Override - public int hashCode() { - return this.hash; - } - - @Override - public boolean equals(final Object obj) { - return (obj == this) || ((obj instanceof BiomeLocationDictionary) - && this.type.equals(((BiomeLocationDictionary) obj).type)); - } - - public BiomeDictionary.Type getType() { - return this.type; - } - - @Override - public ImmutableList getBiomes() { - return ImmutableList.copyOf(BiomeDictionary.getBiomes(this.type)); - } - - @Override - public JsonElement serialize() { - return new JsonPrimitive(this.type.toString().toUpperCase()); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationEmpty.java b/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationEmpty.java deleted file mode 100644 index 44db55a..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationEmpty.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.mcmoddev.orespawn.impl.location; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.mcmoddev.orespawn.api.BiomeLocation; - -import net.minecraft.world.biome.Biome; - -public class BiomeLocationEmpty implements BiomeLocation { - - @Override - public boolean matches(final Biome biome) { - return false; - } - - @Override - public JsonElement serialize() { - return new JsonArray(); - } - -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationList.java b/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationList.java deleted file mode 100644 index 56b3408..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationList.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.mcmoddev.orespawn.impl.location; - -import java.util.LinkedList; -import java.util.List; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.mcmoddev.orespawn.api.BiomeLocation; - -import net.minecraft.world.biome.Biome; - -public final class BiomeLocationList implements BiomeLocation { - - private final ImmutableSet locations; - - private final int hash; - - public BiomeLocationList(final ImmutableSet locations) { - this.locations = locations; - this.hash = locations.hashCode(); - } - - @Override - public boolean matches(final Biome biome) { - return this.locations.stream().anyMatch(loc -> loc.matches(biome)); - } - - @Override - public int hashCode() { - return this.hash; - } - - @Override - public boolean equals(final Object obj) { - return (obj == this) || ((obj instanceof BiomeLocationList) - && this.locations.equals(((BiomeLocationList) obj).locations)); - } - - @Override - public ImmutableList getBiomes() { - final List temp = new LinkedList<>(); - locations.stream().forEach(bl -> temp.addAll(bl.getBiomes())); - return ImmutableList.copyOf(temp); - } - - public ImmutableSet getLocations() { - return this.locations; - } - - @Override - public JsonElement serialize() { - final JsonArray rv = new JsonArray(); - this.locations.stream().filter(bl -> (!(bl instanceof BiomeLocationEmpty))) - .forEach(bl -> rv.add(bl.serialize())); - - return rv; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationSingle.java b/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationSingle.java deleted file mode 100644 index 0b862c7..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/location/BiomeLocationSingle.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.mcmoddev.orespawn.impl.location; - -import com.google.common.collect.ImmutableList; -import com.google.gson.JsonElement; -import com.google.gson.JsonPrimitive; -import com.mcmoddev.orespawn.api.BiomeLocation; - -import net.minecraft.world.biome.Biome; - -public final class BiomeLocationSingle implements BiomeLocation { - - private final Biome biome; - - private final int hash; - - public BiomeLocationSingle(final Biome biome) { - this.biome = biome; - this.hash = biome.hashCode(); - } - - @Override - public boolean matches(final Biome biome) { - return this.biome.equals(biome); - } - - @Override - public ImmutableList getBiomes() { - return ImmutableList.of(this.biome); - } - - @Override - public int hashCode() { - return this.hash; - } - - @Override - public boolean equals(final Object obj) { - return (obj == this) || ((obj instanceof BiomeLocationSingle) - && this.biome.equals(((BiomeLocationSingle) obj).biome)); - } - - public Biome getBiome() { - return this.biome; - } - - @Override - public JsonElement serialize() { - return new JsonPrimitive(this.biome.getRegistryName().toString()); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/BiomeBuilder.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/BiomeBuilder.java deleted file mode 100644 index a8a9bf5..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/BiomeBuilder.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import java.util.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import com.google.common.collect.ImmutableSet; -import com.mcmoddev.orespawn.api.BiomeLocation; -import com.mcmoddev.orespawn.api.os3.IBiomeBuilder; -import com.mcmoddev.orespawn.impl.location.BiomeLocationAcceptAny; -import com.mcmoddev.orespawn.impl.location.BiomeLocationComposition; -import com.mcmoddev.orespawn.impl.location.BiomeLocationEmpty; -import com.mcmoddev.orespawn.impl.location.BiomeLocationList; -import com.mcmoddev.orespawn.impl.location.BiomeLocationSingle; - -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.biome.Biome; -import net.minecraftforge.fml.common.registry.ForgeRegistries; - -public class BiomeBuilder implements IBiomeBuilder { - - private final List whitelist = new LinkedList<>(); - private final List blacklist = new LinkedList<>(); - - private boolean acceptAll = false; - - public BiomeBuilder() { - // - } - - @Override - public IBiomeBuilder addWhitelistEntry(final Biome biome) { - this.whitelist.add(biome); - return this; - } - - @Override - public IBiomeBuilder addWhitelistEntry(final String biomeName) { - return this.addWhitelistEntry(new ResourceLocation(biomeName)); - } - - @Override - public IBiomeBuilder addWhitelistEntry(final ResourceLocation biomeResourceLocation) { - return this.addWhitelistEntry(ForgeRegistries.BIOMES.getValue(biomeResourceLocation)); - } - - @Override - public IBiomeBuilder addBlacklistEntry(final Biome biome) { - this.blacklist.add(biome); - return this; - } - - @Override - public IBiomeBuilder addBlacklistEntry(final String biomeName) { - return this.addBlacklistEntry(new ResourceLocation(biomeName)); - } - - @Override - public IBiomeBuilder addBlacklistEntry(final ResourceLocation biomeResourceLocation) { - return this.addBlacklistEntry(ForgeRegistries.BIOMES.getValue(biomeResourceLocation)); - } - - @Override - public IBiomeBuilder setAcceptAll() { - this.acceptAll = true; - return this; - } - - @Override - public BiomeLocation create() { - if (this.acceptAll) { - return new BiomeLocationAcceptAny(); - } - - BiomeLocation whitelistI; - BiomeLocation blacklistI; - if (this.whitelist.isEmpty()) { - if (!this.blacklist.isEmpty()) { - whitelistI = new BiomeLocationAcceptAny(); - } else { - whitelistI = new BiomeLocationEmpty(); - } - } else { - whitelistI = new BiomeLocationList(ImmutableSet.copyOf( - this.whitelist.stream().map(biome -> new BiomeLocationSingle(biome)) - .collect(Collectors.toList()))); - } - - if (this.blacklist.isEmpty()) { - blacklistI = new BiomeLocationEmpty(); - } else { - blacklistI = new BiomeLocationList(ImmutableSet.copyOf( - this.blacklist.stream().map(biome -> new BiomeLocationSingle(biome)) - .collect(Collectors.toList()))); - } - - return new BiomeLocationComposition(whitelistI, blacklistI); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/BlockBuilder.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/BlockBuilder.java deleted file mode 100644 index 7bc3f62..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/BlockBuilder.java +++ /dev/null @@ -1,188 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.exceptions.BadStateValueException; -import com.mcmoddev.orespawn.api.os3.IBlockBuilder; -import com.mcmoddev.orespawn.api.os3.IBlockDefinition; -import com.mcmoddev.orespawn.util.StateUtil; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.common.registry.ForgeRegistries; - -public class BlockBuilder implements IBlockBuilder { - - private IBlockState blockState; - private int chance; - private boolean isValid = true; - - public BlockBuilder() { - // nothing to do here - } - - @Override - public IBlockBuilder setFromBlockState(final IBlockState blockState) { - final ResourceLocation key = blockState.getBlock().getRegistryName(); - if (!ForgeRegistries.BLOCKS.containsKey(key)) { - this.isValid = false; - } - return this.setFromBlockStateWithChance(blockState, 100); - } - - @Override - public IBlockBuilder setFromBlock(final Block block) { - final ResourceLocation key = block.getRegistryName(); - if (!ForgeRegistries.BLOCKS.containsKey(key)) { - this.isValid = false; - } - return this.setFromBlockState(block.getDefaultState()); - } - - @Override - public IBlockBuilder setFromName(final String blockName) { - return this.setFromName(new ResourceLocation(blockName)); - } - - @Override - public IBlockBuilder setFromName(final String blockName, final String state) { - return this.setFromName(new ResourceLocation(blockName), state); - } - - @Override - public IBlockBuilder setFromName(final String blockName, final int metadata) { - return this.setFromName(new ResourceLocation(blockName), metadata); - } - - @Override - public IBlockBuilder setFromName(final ResourceLocation blockResourceLocation) { - if (!ForgeRegistries.BLOCKS.containsKey(blockResourceLocation)) { - this.isValid = false; - } - return this.setFromBlock(ForgeRegistries.BLOCKS.getValue(blockResourceLocation)); - } - - @Override - public IBlockBuilder setFromName(final ResourceLocation blockResourceLocation, - final String state) { - if (!ForgeRegistries.BLOCKS.containsKey(blockResourceLocation)) { - this.isValid = false; - } - final Block tempBlock = ForgeRegistries.BLOCKS.getValue(blockResourceLocation); - try { - return this.setFromBlockState(StateUtil.deserializeState(tempBlock, state)); - } catch (BadStateValueException e) { - StringBuilder p = new StringBuilder(); - for(StackTraceElement elem: e.getStackTrace()) p.append(String.format("%s.%s (%s:%u)\n", elem.getClassName(), elem.getMethodName(), elem.getFileName(), elem.getLineNumber())); - OreSpawn.LOGGER.error(String.format("Exception: %s\n%s", e.getMessage(), p.toString())); - return this; - } - } - - /** - * - * @deprecated - */ - @Override - @Deprecated - public IBlockBuilder setFromName(final ResourceLocation blockResourceLocation, - final int metadata) { - if (!ForgeRegistries.BLOCKS.containsKey(blockResourceLocation)) { - this.isValid = false; - } - final Block tempBlock = ForgeRegistries.BLOCKS.getValue(blockResourceLocation); - return this.setFromBlockState(tempBlock.getStateFromMeta(metadata)); - } - - @Override - public IBlockBuilder setFromBlockStateWithChance(final IBlockState blockState, - final int chance) { - final ResourceLocation key = blockState.getBlock().getRegistryName(); - if (!ForgeRegistries.BLOCKS.containsKey(key)) { - this.isValid = false; - } - this.blockState = blockState; - this.chance = chance; - return this; - } - - @Override - public IBlockBuilder setFromBlockWithChance(final Block block, final int chance) { - final ResourceLocation key = block.getRegistryName(); - if (!ForgeRegistries.BLOCKS.containsKey(key)) { - this.isValid = false; - } - return this.setFromBlockStateWithChance(block.getDefaultState(), chance); - } - - @Override - public IBlockBuilder setFromNameWithChance(final String blockName, final int chance) { - return this.setFromNameWithChance(new ResourceLocation(blockName), chance); - } - - @Override - public IBlockBuilder setFromNameWithChance(final String blockName, final String state, - final int chance) { - return this.setFromNameWithChance(new ResourceLocation(blockName), state, chance); - } - - @Override - public IBlockBuilder setFromNameWithChance(final String blockName, final int metadata, - final int chance) { - return this.setFromNameWithChance(new ResourceLocation(blockName), metadata, chance); - } - - @Override - public IBlockBuilder setFromNameWithChance(final ResourceLocation blockResourceLocation, - final int chance) { - if (!ForgeRegistries.BLOCKS.containsKey(blockResourceLocation)) { - this.isValid = false; - } - return this.setFromBlockWithChance(ForgeRegistries.BLOCKS.getValue(blockResourceLocation), - chance); - } - - @Override - public IBlockBuilder setFromNameWithChance(final ResourceLocation blockResourceLocation, - final String state, final int chance) { - if (!ForgeRegistries.BLOCKS.containsKey(blockResourceLocation)) { - this.isValid = false; - } - final Block tempBlock = ForgeRegistries.BLOCKS.getValue(blockResourceLocation); - try { - return this.setFromBlockStateWithChance(StateUtil.deserializeState(tempBlock, state), - chance); - } catch (BadStateValueException e) { - StringBuilder p = new StringBuilder(); - for(StackTraceElement elem: e.getStackTrace()) p.append(String.format("%s.%s (%s:%d)\n", elem.getClassName(), elem.getMethodName(), elem.getFileName(), elem.getLineNumber())); - OreSpawn.LOGGER.error(String.format("Exception: %s\n%s", e.getMessage(), p.toString())); - return this; - } - } - - /** - * - * @deprecated - */ - @Override - @Deprecated - public IBlockBuilder setFromNameWithChance(final ResourceLocation blockResourceLocation, - final int metadata, final int chance) { - if (!ForgeRegistries.BLOCKS.containsKey(blockResourceLocation)) { - this.isValid = false; - } - final Block tempBlock = ForgeRegistries.BLOCKS.getValue(blockResourceLocation); - return this.setFromBlockStateWithChance(tempBlock.getStateFromMeta(metadata), chance); - } - - @Override - public IBlockBuilder setChance(final int chance) { - this.chance = chance; - return this; - } - - @Override - public IBlockDefinition create() { - return new BlockDefinition(this.blockState, this.chance, this.isValid); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/BlockDefinition.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/BlockDefinition.java deleted file mode 100644 index f30af42..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/BlockDefinition.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import com.mcmoddev.orespawn.api.os3.IBlockDefinition; - -import net.minecraft.block.state.IBlockState; - -public class BlockDefinition implements IBlockDefinition { - - private final IBlockState blockState; - private final int blockChance; - private final boolean isValid; - - public BlockDefinition(final IBlockState blockState, final int chance, final boolean isValid) { - this.blockState = blockState; - this.blockChance = chance; - this.isValid = isValid; - } - - @Override - public IBlockState getBlock() { - return this.blockState; - } - - @Override - public int getChance() { - return this.blockChance; - } - - @Override - public boolean isValid() { - return this.isValid; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/BlockList.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/BlockList.java deleted file mode 100644 index 326ad77..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/BlockList.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import java.util.LinkedList; -import java.util.List; -import java.util.Random; - -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.IBlockList; -import com.mcmoddev.orespawn.api.os3.IBlockDefinition; - -import net.minecraft.block.state.IBlockState; - -public class BlockList implements IBlockList { - - private final List myBlocks; - private final List workingList; - - public BlockList() { - this.myBlocks = new LinkedList<>(); - this.workingList = new LinkedList<>(); - } - - @Override - public void addBlock(final IBlockDefinition block) { - this.myBlocks.add(block); - } - - @Override - public IBlockState getRandomBlock(final Random rand) { - if (this.workingList.isEmpty()) { - this.startNewSpawn(); - if (this.workingList.isEmpty()) { - return net.minecraft.init.Blocks.AIR.getDefaultState(); - } - } - - final int spot = rand.nextInt(this.workingList.size()); - final IBlockState rv = this.workingList.get(spot); - this.workingList.remove(spot); - return rv; - } - - @Override - public void startNewSpawn() { - this.workingList.clear(); - - this.myBlocks.stream().filter(b -> b.isValid()).forEach(b -> { - for (int i = 0; i < b.getChance(); i++) { - this.workingList.add(b.getBlock()); - } - }); - } - - @Override - public void dump() { - this.myBlocks.stream().map(bd -> bd.getBlock()).forEach( - bs -> OreSpawn.LOGGER.debug("Block %s (with state: %s)", bs.getBlock(), bs)); - } - - @Override - public int count() { - return this.myBlocks.size(); - } - -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionBuilder.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionBuilder.java deleted file mode 100644 index 9467beb..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionBuilder.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import java.util.LinkedList; -import java.util.List; - -import com.mcmoddev.orespawn.api.IDimensionList; -import com.mcmoddev.orespawn.api.os3.IDimensionBuilder; - -public class DimensionBuilder implements IDimensionBuilder { - - private final List dimensionWhitelist = new LinkedList<>(); - private final List dimensionBlacklist = new LinkedList<>(); - private boolean acceptAll = false; - private boolean denyAll = false; - private boolean acceptAllOverworld = true; - - public DimensionBuilder() { - // - } - - @Override - public IDimensionBuilder addWhitelistEntry(final int dimensionID) { - this.acceptAllOverworld = false; - this.dimensionWhitelist.add(dimensionID); - return this; - } - - @Override - public IDimensionBuilder addBlacklistEntry(final int dimensionID) { - this.acceptAllOverworld = false; - this.dimensionBlacklist.add(dimensionID); - return this; - } - - @Override - public IDimensionBuilder setAcceptAll() { - if (this.denyAll) { - this.denyAll = false; - } - this.acceptAll = true; - return this; - } - - @Override - public IDimensionBuilder setDenyAll() { - if (this.acceptAll) { - this.acceptAll = false; - } - this.denyAll = true; - return this; - } - - @Override - public IDimensionList create() { - if (this.acceptAll - || ((this.dimensionWhitelist.isEmpty()) && (this.dimensionBlacklist.isEmpty())) - && !(this.acceptAllOverworld)) { - return new DimensionListAcceptAll(); - } else if (this.denyAll) { - return new DimensionListDenyAll(); - } else if (this.acceptAllOverworld) { - return new DimensionListAcceptAllOverworld(); - } else { - return new DimensionList(this.dimensionWhitelist, this.dimensionBlacklist); - } - } - - @Override - public IDimensionBuilder setAcceptAllOverworld() { - this.acceptAll = false; - this.denyAll = false; - this.acceptAllOverworld = true; - return this; - } - -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionList.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionList.java deleted file mode 100644 index 61d9ebc..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionList.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import java.util.ArrayList; -import java.util.List; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.data.Constants; - -public class DimensionList implements com.mcmoddev.orespawn.api.IDimensionList { - - private final List whitelist = new ArrayList<>(); - private final List blacklist = new ArrayList<>(); - - public DimensionList(final List whitelist, final List blacklist) { - this.whitelist.addAll(whitelist); - this.blacklist.addAll(blacklist); - } - - @Override - public boolean matches(final int dimensionID) { - if (this.whitelist.contains(Integer.valueOf(dimensionID))) { - return true; - } - if (this.blacklist.contains(Integer.valueOf(dimensionID))) { - return false; - } - if (!this.whitelist.isEmpty()) { - return false; - } - if (!this.blacklist.isEmpty()) { - return true; - } - - // if it gets here, the whitelist and blacklist are empty... - // ***THAT*** should have resulted in a DimensionListAcceptAll being created, but... - return true; - } - - @Override - public JsonObject serialize() { - final JsonObject rv = new JsonObject(); - if (!this.whitelist.isEmpty()) { - final JsonArray wl = new JsonArray(); - whitelist.stream().forEach(wl::add); - rv.add(Constants.ConfigNames.WHITELIST, wl); - } - - if (!this.blacklist.isEmpty()) { - final JsonArray bl = new JsonArray(); - blacklist.stream().forEach(bl::add); - rv.add(Constants.ConfigNames.WHITELIST, bl); - } else if (this.whitelist.isEmpty()) { - return new DimensionListAcceptAllOverworld().serialize(); - } - - return rv; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionListAcceptAll.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionListAcceptAll.java deleted file mode 100644 index 8f2b1ce..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionListAcceptAll.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.api.IDimensionList; -import com.mcmoddev.orespawn.data.Constants.ConfigNames; - -public class DimensionListAcceptAll implements IDimensionList { - - @Override - public boolean matches(final int dimensionID) { - return true; - } - - @Override - public JsonObject serialize() { - final JsonObject rv = new JsonObject(); - rv.add(ConfigNames.BLACKLIST, new JsonArray()); - return rv; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionListAcceptAllOverworld.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionListAcceptAllOverworld.java deleted file mode 100644 index 263272c..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionListAcceptAllOverworld.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.api.IDimensionList; -import com.mcmoddev.orespawn.data.Constants; - -public class DimensionListAcceptAllOverworld implements IDimensionList { - - @Override - public boolean matches(final int dimensionID) { - return dimensionID != -1 && dimensionID != 1; - } - - @Override - public JsonObject serialize() { - final JsonObject rv = new JsonObject(); - final JsonArray bl = new JsonArray(); - bl.add(-1); - bl.add(1); - rv.add(Constants.ConfigNames.BLACKLIST, bl); - - return rv; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionListDenyAll.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionListDenyAll.java deleted file mode 100644 index 49eef5c..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/DimensionListDenyAll.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.api.IDimensionList; -import com.mcmoddev.orespawn.data.Constants; - -public class DimensionListDenyAll implements IDimensionList { - - @Override - public boolean matches(final int dimensionID) { - return false; - } - - @Override - public JsonObject serialize() { - final JsonObject rv = new JsonObject(); - rv.add(Constants.ConfigNames.WHITELIST, new JsonArray()); - - return rv; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/FeatureBuilder.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/FeatureBuilder.java deleted file mode 100644 index 7bbaa8b..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/FeatureBuilder.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import java.util.Locale; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.IFeature; -import com.mcmoddev.orespawn.api.os3.IFeatureBuilder; -import com.mcmoddev.orespawn.api.os3.IFeatureEntry; - -import net.minecraft.util.ResourceLocation; - -public class FeatureBuilder implements IFeatureBuilder { - - private IFeature feature; - private JsonObject parameters; - private boolean useDefaults; - - public FeatureBuilder() { - this.useDefaults = false; - this.parameters = new JsonObject(); - } - - @Override - public IFeatureBuilder setFeature(final String featureName) { - String actName = featureName; - if (!actName.contains(":")) { - actName = String.format(Locale.ENGLISH, "orespawn:%s", featureName); - } - return this.setFeature(new ResourceLocation(actName)); - } - - @Override - public IFeatureBuilder setFeature(final ResourceLocation featureResourceLocation) { - if (!OreSpawn.API.featureExists(featureResourceLocation)) { - OreSpawn.LOGGER.warn( - "Feature %s is not known, feature for this will be set to the default feature", - featureResourceLocation.getPath()); - } - return this.setFeature(OreSpawn.API.getFeature(featureResourceLocation)); - } - - @Override - public IFeatureBuilder setFeature(final IFeature feature) { - this.feature = feature; - return this; - } - - @Override - public IFeatureBuilder setParameter(final String parameterName, final String parameterValue) { - this.parameters.addProperty(parameterName, parameterValue); - return this; - } - - @Override - public IFeatureBuilder setParameter(final String parameterName, final int parameterValue) { - this.parameters.addProperty(parameterName, parameterValue); - return this; - } - - @Override - public IFeatureBuilder setParameter(final String parameterName, final float parameterValue) { - this.parameters.addProperty(parameterName, parameterValue); - return this; - } - - @Override - public IFeatureBuilder setParameter(final String parameterName, final boolean parameterValue) { - this.parameters.addProperty(parameterName, parameterValue); - return this; - } - - @Override - public IFeatureBuilder setParameter(final String parameterName, - final JsonElement parameterValue) { - this.parameters.add(parameterName, parameterValue); - return this; - } - - private void setFeatureParameter(final String parameterName, final JsonElement parameterValue, - final FeatureEntry feat) { - if (parameterValue.getAsJsonPrimitive().isBoolean()) { - feat.setParameter(parameterName, parameterValue.getAsBoolean()); - } else if (parameterValue.getAsJsonPrimitive().isString()) { - feat.setParameter(parameterName, parameterValue.getAsString()); - } else { - float paramAsFloat = parameterValue.getAsFloat(); - if ((paramAsFloat - Math.floor(paramAsFloat)) > 0) { - feat.setParameter(parameterName, parameterValue.getAsFloat()); - } else { - feat.setParameter(parameterName, parameterValue.getAsInt()); - } - } - } - - @Override - public IFeatureBuilder setUseFeatureDefaults() { - this.useDefaults = true; - return this; - } - - @Override - public IFeatureEntry create() { - final FeatureEntry res = new FeatureEntry(this.feature); - if (!this.useDefaults) { - // only copy in the parameters we need - this.feature.getDefaultParameters().entrySet().stream() - .filter(ent -> !this.parameters.has(ent.getKey())) - .forEach(ent -> this.parameters.add(ent.getKey(), ent.getValue())); - } else { - // overwrite - they've said to just use the defaults - this.feature.getDefaultParameters().entrySet().stream() - .forEach(ent -> this.parameters.add(ent.getKey(), ent.getValue())); - } - - this.parameters.entrySet().stream() - .forEach(ent -> this.setFeatureParameter(ent.getKey(), ent.getValue(), res)); - - return res; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/FeatureEntry.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/FeatureEntry.java deleted file mode 100644 index c5d7167..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/FeatureEntry.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.api.IFeature; -import com.mcmoddev.orespawn.api.os3.IFeatureEntry; - -public class FeatureEntry implements IFeatureEntry { - - private final IFeature feature; - private final JsonObject parameters; - - public FeatureEntry(final IFeature feature) { - this.feature = feature; - this.parameters = new JsonObject(); - } - - @Override - public IFeature getFeature() { - return this.feature; - } - - @Override - public String getFeatureName() { - return this.feature.getRegistryName().getPath(); - } - - @Override - public JsonObject getFeatureParameters() { - final JsonObject defs = feature.getDefaultParameters(); - this.parameters.entrySet().stream().forEach(ent -> defs.add(ent.getKey(), ent.getValue())); - return defs; - } - - @Override - public void setParameter(final String parameterName, final String parameterValue) { - this.parameters.addProperty(parameterName, parameterValue); - } - - @Override - public void setParameter(final String parameterName, final int parameterValue) { - this.parameters.addProperty(parameterName, parameterValue); - } - - @Override - public void setParameter(final String parameterName, final boolean parameterValue) { - this.parameters.addProperty(parameterName, parameterValue); - } - - @Override - public void setParameter(final String parameterName, final float parameterValue) { - this.parameters.addProperty(parameterName, parameterValue); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/OS3APIImpl.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/OS3APIImpl.java deleted file mode 100644 index 8366487..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/OS3APIImpl.java +++ /dev/null @@ -1,282 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.PathMatcher; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.TreeMap; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.IFeature; -import com.mcmoddev.orespawn.api.exceptions.MissingVersionException; -import com.mcmoddev.orespawn.api.exceptions.NotAProperConfigException; -import com.mcmoddev.orespawn.api.exceptions.OldVersionException; -import com.mcmoddev.orespawn.api.exceptions.UnknownVersionException; -import com.mcmoddev.orespawn.api.os3.IBiomeBuilder; -import com.mcmoddev.orespawn.api.os3.IBlockBuilder; -import com.mcmoddev.orespawn.api.os3.IDimensionBuilder; -import com.mcmoddev.orespawn.api.os3.IFeatureBuilder; -import com.mcmoddev.orespawn.api.os3.IReplacementBuilder; -import com.mcmoddev.orespawn.api.os3.IReplacementEntry; -import com.mcmoddev.orespawn.api.os3.ISpawnBuilder; -import com.mcmoddev.orespawn.api.os3.ISpawnEntry; -import com.mcmoddev.orespawn.api.os3.OS3API; -import com.mcmoddev.orespawn.data.Constants; -import com.mcmoddev.orespawn.data.FeatureRegistry; -import com.mcmoddev.orespawn.data.PresetsStorage; -import com.mcmoddev.orespawn.data.ReplacementsRegistry; -import com.mcmoddev.orespawn.json.OreSpawnReader; -import com.mcmoddev.orespawn.worldgen.OreSpawnFeatureGenerator; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.crash.CrashReport; -import net.minecraft.util.ResourceLocation; - -public class OS3APIImpl implements OS3API { - - private static final Map spawns; - private static final List generators; - private static final FeatureRegistry features; - private static final ReplacementsRegistry replacements; - private static final PresetsStorage presets; - private static final String ORE_SPAWN_VERSION = "OreSpawn Version"; - private static final Map spawnsToSourceFiles = new TreeMap<>(); - - static { - spawns = new ConcurrentHashMap<>(); - features = new FeatureRegistry(); - replacements = new ReplacementsRegistry(); - presets = new PresetsStorage(); - generators = new LinkedList<>(); - } - - public OS3APIImpl() { - // - } - - public void loadConfigFiles() { - final String failedReadingConfigsFrom = "Failed reading configs from "; - PathMatcher featuresFiles = FileSystems.getDefault() - .getPathMatcher("glob:**/features-*.json"); - PathMatcher replacementsFiles = FileSystems.getDefault() - .getPathMatcher("glob:**/replacements-*.json"); - PathMatcher jsonMatcher = FileSystems.getDefault().getPathMatcher("glob:**/*.json"); - - try (final Stream stream = Files.walk(Constants.SYSCONF, 1)) { - stream.filter(featuresFiles::matches).map(Path::toFile) - .forEach(features::loadFeaturesFile); - } catch (final IOException e) { - CrashReport report = CrashReport.makeCrashReport(e, - failedReadingConfigsFrom + Constants.SYSCONF.toString()); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - - // have to do this twice or we have issues - try (final Stream stream = Files.walk(Constants.SYSCONF, 1)) { - stream.filter(replacementsFiles::matches).forEach(replacements::loadFile); - } catch (final IOException e) { - CrashReport report = CrashReport.makeCrashReport(e, - failedReadingConfigsFrom + Constants.SYSCONF.toString()); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - - if (Constants.SYSCONF.resolve("presets-default.json").toFile().exists()) { - presets.load(Constants.SYSCONF.resolve("presets-default.json")); - } - - try (final Stream stream = Files.walk(Constants.CONFDIR, 1)) { - stream.filter(jsonMatcher::matches).forEach(conf -> { - try { - OreSpawnReader.tryReadFile(conf); - } catch (final MissingVersionException | NotAProperConfigException - | OldVersionException | UnknownVersionException e) { - CrashReport report = CrashReport.makeCrashReport(e, - "Failed reading config " + conf.toString()); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - }); - } catch (final IOException e) { - CrashReport report = CrashReport.makeCrashReport(e, - failedReadingConfigsFrom + Constants.CONFDIR.toString()); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - } - - @Override - public void addGenerator(final OreSpawnFeatureGenerator generator) { - generators.add(generator); - } - - @Override - public List getGenerators() { - return new LinkedList(generators); - } - - @Override - public void addSpawn(final ISpawnEntry spawnEntry) { - if (spawnEntry != null) { - spawns.put(new ResourceLocation(spawnEntry.getSpawnName()), spawnEntry); - } - } - - @Override - public void addFeature(final String featureName, final IFeature feature) { - features.addFeature(featureName, feature); - } - - @Override - public void addReplacement(final IReplacementEntry replacementEntry) { - replacements.addReplacement(replacementEntry); - } - - @Override - public ISpawnBuilder getSpawnBuilder() { - return new SpawnBuilder(); - } - - @Override - public IDimensionBuilder getDimensionBuilder() { - return new DimensionBuilder(); - } - - @Override - public IFeatureBuilder getFeatureBuilder() { - return new FeatureBuilder(); - } - - @Override - public IBlockBuilder getBlockBuilder() { - return new BlockBuilder(); - } - - @Override - public IBiomeBuilder getBiomeBuilder() { - return new BiomeBuilder(); - } - - @Override - public IReplacementBuilder getReplacementBuilder() { - return new ReplacementBuilder(); - } - - @Override - public Map getReplacements() { - final Map temp = new HashMap<>(); - replacements.getReplacements().entrySet().stream() - .forEach(e -> temp.put(e.getKey().getPath(), e.getValue())); - return ImmutableMap.copyOf(temp); - } - - @Override - public IReplacementEntry getReplacement(final String replacementName) { - return replacements.getReplacement(replacementName); - } - - @Override - public List getSpawns(final int dimensionID) { - return ImmutableList.copyOf( - spawns.entrySet().stream().filter(e -> e.getValue().dimensionAllowed(dimensionID)) - .map(Map.Entry::getValue).collect(Collectors.toList())); - } - - @Override - public ISpawnEntry getSpawn(final String spawnName) { - return spawns.get(new ResourceLocation(spawnName)); - } - - @Override - public Map getAllSpawns() { - final Map sp = new HashMap<>(); - spawns.entrySet().forEach(ent -> sp.put(ent.getKey().getPath(), ent.getValue())); - return ImmutableMap.copyOf(sp); - } - - @Override - public boolean featureExists(final String featureName) { - return this.featureExists(new ResourceLocation(featureName.contains(":") ? featureName - : String.format(Locale.ENGLISH, "orespawn:%s", featureName))); - } - - @Override - public boolean featureExists(final ResourceLocation featureName) { - return features.hasFeature(featureName); - } - - @Override - public IFeature getFeature(final String featureName) { - return this.getFeature(new ResourceLocation(featureName)); - } - - @Override - public IFeature getFeature(final ResourceLocation featureName) { - return features.getFeature(featureName); - } - - @Override - public PresetsStorage copyPresets() { - final PresetsStorage copy = new PresetsStorage(); - presets.copy(copy); - return copy; - } - - @Override - public List getDimensionDefaultReplacements(final int dimensionID) { - return replacements.getDimensionDefault(dimensionID); - } - - @Override - public boolean hasReplacement(final ResourceLocation resourceLocation) { - return replacements.has(resourceLocation); - } - - @Override - public boolean hasReplacement(final String name) { - return this.hasReplacement(new ResourceLocation( - name.contains(":") ? name : String.format(Locale.ENGLISH, "orespawn:%s", name))); - } - - @Override - public void mapEntryToFile(final Path p, final String entryName) { - spawnsToSourceFiles.put(entryName, p); - } - - @Override - public List getSpawnsForFile(final String fileName) { - final Path p = Constants.CONFDIR.resolve(fileName); - final List values = spawnsToSourceFiles.entrySet().stream() - .filter(ent -> ent.getValue().equals(p)).map(Map.Entry::getKey) - .collect(Collectors.toList()); - return ImmutableList.copyOf(values); - } - - @Override - public Map> getSpawnsByFile() { - final Map> temp = new HashMap<>(); - spawnsToSourceFiles.entrySet().stream().forEach(ent -> { - if (temp.containsKey(ent.getValue())) { - temp.get(ent.getValue()).add(ent.getKey()); - } else { - temp.put(ent.getValue(), Lists.newLinkedList(Arrays.asList(ent.getKey()))); - } - }); - - return ImmutableMap.copyOf(temp); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/ReplacementBuilder.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/ReplacementBuilder.java deleted file mode 100644 index 8071d4b..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/ReplacementBuilder.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; - -import org.apache.commons.lang3.RandomStringUtils; - -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.exceptions.BadStateValueException; -import com.mcmoddev.orespawn.api.os3.IReplacementBuilder; -import com.mcmoddev.orespawn.api.os3.IReplacementEntry; -import com.mcmoddev.orespawn.util.StateUtil; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.common.registry.ForgeRegistries; - -public class ReplacementBuilder implements IReplacementBuilder { - - private String replacementName = null; - private List entries; - - public ReplacementBuilder() { - this.entries = new LinkedList<>(); - } - - @Override - public IReplacementBuilder setFromName(final String entryName) { - this.replacementName = entryName; - this.entries.addAll(OreSpawn.API.getReplacement(entryName).getEntries()); - return this; - } - - @Override - public IReplacementBuilder setName(final String name) { - this.replacementName = name; - return this; - } - - @Override - public IReplacementBuilder addEntry(final IBlockState blockState) { - this.entries.add(blockState); - return this; - } - - @Override - public IReplacementBuilder addEntry(final String blockName) { - return this.addEntry(new ResourceLocation(blockName)); - } - - @Override - public IReplacementBuilder addEntry(final String blockName, final String state) { - return this.addEntry(new ResourceLocation(blockName), state); - } - - /** - * - * @deprecated - */ - @Override - @Deprecated - public IReplacementBuilder addEntry(final String blockName, final int metadata) { - return this.addEntry(new ResourceLocation(blockName), metadata); - } - - @Override - public IReplacementBuilder addEntry(final ResourceLocation blockResourceLocation) { - return this - .addEntry(ForgeRegistries.BLOCKS.getValue(blockResourceLocation).getDefaultState()); - } - - @Override - public IReplacementBuilder addEntry(final ResourceLocation blockResourceLocation, - final String state) { - try { - return this.addEntry(StateUtil - .deserializeState(ForgeRegistries.BLOCKS.getValue(blockResourceLocation), state)); - } catch (BadStateValueException e) { - StringBuilder p = new StringBuilder(); - for(StackTraceElement elem: e.getStackTrace()) p.append(String.format("%s.%s (%s:%u)\n", elem.getClassName(), elem.getMethodName(), elem.getFileName(), elem.getLineNumber())); - OreSpawn.LOGGER.error(String.format("Exception: %s\n%s", e.getMessage(), p.toString())); - return this.addEntry(ForgeRegistries.BLOCKS.getValue(blockResourceLocation).getDefaultState()); - } - } - - /** - * - * @deprecated - */ - @Override - @Deprecated - public IReplacementBuilder addEntry(final ResourceLocation blockResourceLocation, - final int metadata) { - return this.addEntry( - ForgeRegistries.BLOCKS.getValue(blockResourceLocation).getStateFromMeta(metadata)); - } - - @Override - public boolean hasEntries() { - return !this.entries.isEmpty(); - } - - @Override - public IReplacementEntry create() { - if (this.replacementName == null) { - this.replacementName = String.format(Locale.ENGLISH, "replacement_%s", - RandomStringUtils.randomAlphanumeric(8, 16)); - } - - return new ReplacementEntry(this.replacementName, this.entries); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/ReplacementEntry.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/ReplacementEntry.java deleted file mode 100644 index e2e21fc..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/ReplacementEntry.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.common.collect.ImmutableList; -import com.mcmoddev.orespawn.api.os3.IReplacementEntry; -import com.mcmoddev.orespawn.api.os3.OreSpawnBlockMatcher; - -import net.minecraft.block.state.IBlockState; -import net.minecraftforge.registries.IForgeRegistryEntry; - -public class ReplacementEntry extends IForgeRegistryEntry.Impl - implements IReplacementEntry { - - private final List matchVal; - private OreSpawnBlockMatcher matcher = null; - - public ReplacementEntry(final String name, final IBlockState... toMatch) { - super.setRegistryName(name); - this.matchVal = Arrays.asList(toMatch); - } - - public ReplacementEntry(final String name, final List toMatch) { - super.setRegistryName(name); - this.matchVal = new ArrayList<>(); - this.matchVal.addAll(toMatch); - } - - @Override - public OreSpawnBlockMatcher getMatcher() { - if (this.matcher == null) { - this.matcher = new OreSpawnBlockMatcher(this.matchVal); - } - return this.matcher; - } - - public List getEntries() { - return ImmutableList.copyOf(this.matchVal); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/SpawnBuilder.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/SpawnBuilder.java deleted file mode 100644 index 2d9dac8..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/SpawnBuilder.java +++ /dev/null @@ -1,231 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.BiomeLocation; -import com.mcmoddev.orespawn.api.IBlockList; -import com.mcmoddev.orespawn.api.IDimensionList; -import com.mcmoddev.orespawn.api.exceptions.BadStateValueException; -import com.mcmoddev.orespawn.api.os3.IBlockDefinition; -import com.mcmoddev.orespawn.api.os3.IFeatureEntry; -import com.mcmoddev.orespawn.api.os3.IReplacementEntry; -import com.mcmoddev.orespawn.api.os3.ISpawnBuilder; -import com.mcmoddev.orespawn.util.StateUtil; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.common.registry.ForgeRegistries; - -public class SpawnBuilder implements ISpawnBuilder { - - private String spawnName; - private boolean enabled; - private boolean retrogen; - private IBlockList blocks; - private IFeatureEntry feature; - private BiomeLocation biomes; - private IDimensionList dimensions; - private IReplacementEntry replacements; - - public SpawnBuilder() { - this.enabled = false; - this.retrogen = false; - this.blocks = new BlockList(); - } - - public SpawnBuilder(final String spawnName) { - this(); - this.spawnName = spawnName; - } - - @Override - public ISpawnBuilder setName(final String name) { - this.spawnName = name; - return this; - } - - @Override - public ISpawnBuilder setDimensions(final IDimensionList dimensions) { - this.dimensions = dimensions; - return this; - } - - @Override - public ISpawnBuilder setBiomes(final BiomeLocation biomes) { - this.biomes = biomes; - return this; - } - - @Override - public ISpawnBuilder setEnabled(final boolean enabled) { - this.enabled = enabled; - return this; - } - - @Override - public ISpawnBuilder setRetrogen(final boolean retrogen) { - this.retrogen = retrogen; - return this; - } - - @Override - public ISpawnBuilder setReplacement(final IReplacementEntry replacements) { - this.replacements = replacements; - return this; - } - - @Override - public ISpawnBuilder setFeature(final IFeatureEntry feature) { - this.feature = feature; - return this; - } - - @Override - public ISpawnBuilder addBlock(final String blockName) { - return this.addBlock(new ResourceLocation(blockName)); - } - - @Override - public ISpawnBuilder addBlock(final String blockName, final String blockState) { - return this.addBlock(new ResourceLocation(blockName), blockState); - } - - /** - * - * @deprecated - */ - @Override - @Deprecated - public ISpawnBuilder addBlock(final String blockName, final int blockMetadata) { - return this.addBlock(new ResourceLocation(blockName), blockMetadata); - } - - @Override - public ISpawnBuilder addBlock(final ResourceLocation blockResourceLocation) { - return this.addBlockWithChance(blockResourceLocation, 100); - } - - @Override - public ISpawnBuilder addBlock(final ResourceLocation blockResourceLocation, - final String blockState) { - return this.addBlockWithChance(blockResourceLocation, blockState, 100); - } - - /** - * - * @deprecated - */ - @Override - @Deprecated - public ISpawnBuilder addBlock(final ResourceLocation blockResourceLocation, - final int blockMetadata) { - return this.addBlockWithChance(blockResourceLocation, 100); - } - - @Override - public ISpawnBuilder addBlock(final Block block) { - return this.addBlockWithChance(block, 100); - } - - @Override - public ISpawnBuilder addBlock(final IBlockState block) { - return this.addBlockWithChance(block, 100); - } - - @Override - public ISpawnBuilder addBlockWithChance(final String blockName, final int chance) { - return this.addBlockWithChance(new ResourceLocation(blockName), chance); - } - - @Override - public ISpawnBuilder addBlockWithChance(final String blockName, final String blockState, - final int chance) { - return this.addBlockWithChance(new ResourceLocation(blockName), blockState, chance); - } - - /** - * - * @deprecated - */ - @Override - @Deprecated - public ISpawnBuilder addBlockWithChance(final String blockName, final int blockMetadata, - final int chance) { - return this.addBlockWithChance(blockName, blockMetadata, chance); - } - - @Override - public ISpawnBuilder addBlockWithChance(final ResourceLocation blockResourceLocation, - final int chance) { - final IBlockState tempVar = ForgeRegistries.BLOCKS.getValue(blockResourceLocation) - .getDefaultState(); - return this.addBlockWithChance(tempVar, chance); - } - - @Override - public ISpawnBuilder addBlockWithChance(final ResourceLocation blockResourceLocation, - final String blockState, final int chance) { - final Block tempBlock = ForgeRegistries.BLOCKS.getValue(blockResourceLocation); - IBlockState tempVar; - try { - tempVar = StateUtil.deserializeState(tempBlock, blockState); - } catch (BadStateValueException e) { - StringBuilder p = new StringBuilder(); - for(StackTraceElement elem: e.getStackTrace()) p.append(String.format("%s.%s (%s:%u)\n", elem.getClassName(), elem.getMethodName(), elem.getFileName(), elem.getLineNumber())); - OreSpawn.LOGGER.error(String.format("Exception: %s\n%s", e.getMessage(), p.toString())); - tempVar = tempBlock.getDefaultState(); - } - return this.addBlockWithChance(tempVar, chance); - } - - /** - * - * @deprecated - */ - @Override - @Deprecated - public ISpawnBuilder addBlockWithChance(final ResourceLocation blockResourceLocation, - final int blockMetadata, final int chance) { - final IBlockState tempVar = ForgeRegistries.BLOCKS.getValue(blockResourceLocation) - .getStateFromMeta(blockMetadata); - return this.addBlockWithChance(tempVar, chance); - } - - @Override - public ISpawnBuilder addBlockWithChance(final Block block, final int chance) { - final IBlockState tempVar = block.getDefaultState(); - return this.addBlockWithChance(tempVar, chance); - } - - @Override - public ISpawnBuilder addBlockWithChance(final IBlockState block, final int chance) { - final BlockBuilder bb = new BlockBuilder(); - bb.setFromBlockStateWithChance(block, chance); - return this.addBlock(bb.create()); - } - - @Override - public ISpawnBuilder addBlock(final IBlockDefinition block) { - if (block.isValid()) { - this.blocks.addBlock(block); - } - return this; - } - - @Override - public SpawnEntry create() { - if (this.blocks.count() > 0) { - if (this.dimensions == null) this.dimensions = new DimensionBuilder().setAcceptAll().create(); - if (this.biomes == null) this.biomes = new BiomeBuilder().setAcceptAll().create(); - if (this.replacements == null) this.replacements = com.mcmoddev.orespawn.OreSpawn.API.getReplacement("default"); - if (this.feature == null) { - com.mcmoddev.orespawn.OreSpawn.LOGGER.fatal("Spawn entry {} does not have a stated feature, ignoring.", this.spawnName); - return null; - } - return new SpawnEntry(this.spawnName, this.enabled, this.retrogen, this.dimensions, - this.biomes, this.replacements, this.blocks, this.feature); - } else { - return null; - } - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/impl/os3/SpawnEntry.java b/src/main/java/com/mcmoddev/orespawn/impl/os3/SpawnEntry.java deleted file mode 100644 index 8aa7258..0000000 --- a/src/main/java/com/mcmoddev/orespawn/impl/os3/SpawnEntry.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.mcmoddev.orespawn.impl.os3; - -import java.util.Random; - -import com.mcmoddev.orespawn.api.BiomeLocation; -import com.mcmoddev.orespawn.api.IBlockList; -import com.mcmoddev.orespawn.api.IDimensionList; -import com.mcmoddev.orespawn.api.os3.IFeatureEntry; -import com.mcmoddev.orespawn.api.os3.IReplacementEntry; -import com.mcmoddev.orespawn.api.os3.OreSpawnBlockMatcher; - -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; -import net.minecraftforge.fml.common.registry.ForgeRegistries; - -public class SpawnEntry implements com.mcmoddev.orespawn.api.os3.ISpawnEntry { - - private final String spawnName; - private final IDimensionList dimensions; - private final IReplacementEntry replacements; - private final IBlockList blocks; - private final BiomeLocation biomes; - private final IFeatureEntry feature; - private final boolean enabled; - private final boolean retrogen; - - public SpawnEntry(final String spawnName, final boolean enabled, final boolean retrogen, - final IDimensionList dimensions, final BiomeLocation biomes, - final IReplacementEntry replacements, final IBlockList blocks, - final IFeatureEntry feature) { - this.spawnName = spawnName; - this.enabled = enabled; - this.retrogen = retrogen; - this.dimensions = dimensions; - this.biomes = biomes; - this.replacements = replacements; - this.blocks = blocks; - this.feature = feature; - } - - @Override - public boolean isRetrogen() { - return this.retrogen; - } - - @Override - public boolean isEnabled() { - return this.enabled; - } - - @Override - public String getSpawnName() { - return this.spawnName; - } - - @Override - public boolean dimensionAllowed(final int dimension) { - return this.dimensions.matches(dimension); - } - - @Override - public boolean biomeAllowed(final ResourceLocation biomeName) { - return this.biomeAllowed(ForgeRegistries.BIOMES.getValue(biomeName)); - } - - @Override - public boolean biomeAllowed(final Biome biome) { - return this.biomes.matches(biome); - } - - @Override - public IFeatureEntry getFeature() { - return this.feature; - } - - @Override - public OreSpawnBlockMatcher getMatcher() { - return this.replacements.getMatcher(); - } - - @Override - public IBlockList getBlocks() { - return this.blocks; - } - - @Override - public void generate(final Random random, final World world, - final IChunkGenerator chunkGenerator, final IChunkProvider chunkProvider, - final ChunkPos pos) { - this.feature.getFeature().setRandom(random); - this.feature.getFeature().generate(world, chunkGenerator, chunkProvider, this, pos); - } - - @Override - public IDimensionList getDimensions() { - return this.dimensions; - } - - @Override - public BiomeLocation getBiomes() { - return this.biomes; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/json/OreSpawnReader.java b/src/main/java/com/mcmoddev/orespawn/json/OreSpawnReader.java deleted file mode 100644 index 8d30a8b..0000000 --- a/src/main/java/com/mcmoddev/orespawn/json/OreSpawnReader.java +++ /dev/null @@ -1,447 +0,0 @@ -package com.mcmoddev.orespawn.json; - -import java.io.BufferedReader; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.AbstractMap; -import java.util.Arrays; -import java.util.List; -import java.util.Map.Entry; -import java.util.stream.Collectors; - -import com.google.common.collect.ImmutableList; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonIOException; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.exceptions.BadStateValueException; -import com.mcmoddev.orespawn.api.exceptions.BadValueException; -import com.mcmoddev.orespawn.api.exceptions.MissingVersionException; -import com.mcmoddev.orespawn.api.exceptions.NotAProperConfigException; -import com.mcmoddev.orespawn.api.exceptions.OldVersionException; -import com.mcmoddev.orespawn.api.exceptions.UnknownFieldException; -import com.mcmoddev.orespawn.api.exceptions.UnknownNameException; -import com.mcmoddev.orespawn.api.exceptions.UnknownVersionException; -import com.mcmoddev.orespawn.api.os3.IBiomeBuilder; -import com.mcmoddev.orespawn.api.os3.IBlockBuilder; -import com.mcmoddev.orespawn.api.os3.IDimensionBuilder; -import com.mcmoddev.orespawn.api.os3.IFeatureBuilder; -import com.mcmoddev.orespawn.api.os3.IReplacementBuilder; -import com.mcmoddev.orespawn.api.os3.ISpawnBuilder; -import com.mcmoddev.orespawn.data.Constants; -import com.mcmoddev.orespawn.data.PresetsStorage; -import com.mcmoddev.orespawn.util.StateUtil; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.crash.CrashReport; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.common.BiomeDictionary; -import net.minecraftforge.fml.common.registry.ForgeRegistries; -import net.minecraftforge.oredict.OreDictionary; - -public class OreSpawnReader { - - private static final String ORE_SPAWN_VERSION = "OreSpawn Version"; - - private OreSpawnReader() { - // hiding the default one - } - - private static JsonElement doPresetFix(final JsonElement value, - final PresetsStorage configPresets) { - if (value.isJsonObject()) { - return doPresetForObject(value.getAsJsonObject(), configPresets); - } else if (value.isJsonArray()) { - return doPresetForArray(value.getAsJsonArray(), configPresets); - } else if (value.isJsonPrimitive() && !value.isJsonNull()) { - if (value.getAsJsonPrimitive().isString() && value.getAsString().matches("^\\$.*")) { - return configPresets.get(value.getAsString()); - } else { - return value; - } - } else { - OreSpawn.LOGGER.error("Error handling presets for config, unknown value type for item " - + value.toString()); - return value; - } - } - - public static void tryReadFile(final Path conf) - throws MissingVersionException, NotAProperConfigException, OldVersionException, - UnknownVersionException { - final JsonParser parser = new JsonParser(); - - try (BufferedReader data = Files.newBufferedReader(conf)) { - final JsonElement json = parser.parse(data); - - if (!json.isJsonObject()) { - throw new NotAProperConfigException(); - } - - final JsonObject root = json.getAsJsonObject(); - if (!root.has(Constants.ConfigNames.FILE_VERSION)) { - throw new MissingVersionException(); - } - - final float version = root.get(Constants.ConfigNames.FILE_VERSION).getAsFloat(); - if (version < 2f) { - throw new OldVersionException(); - } else if (version != 2f) { - throw new UnknownVersionException(); - } - - if (!root.has(Constants.ConfigNames.SPAWNS)) { - throw new NotAProperConfigException(); - } - - final JsonObject spawnData = doHandlePresets(root).get(Constants.ConfigNames.SPAWNS) - .getAsJsonObject(); - spawnData.entrySet().stream().forEach(e -> { - try { - OreSpawn.API.mapEntryToFile(conf, e.getKey()); - loadSingleEntry(e); - } catch (UnknownFieldException | BadValueException | UnknownNameException e1) { - CrashReport report = CrashReport.makeCrashReport(e1, - "Error parsing an entry " + e.getKey() + " in " + conf.toString()); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - }); - } catch (final IOException e) { - CrashReport report = CrashReport.makeCrashReport(e, - "Failed reading config data " + conf.toString()); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } catch (final JsonIOException | JsonSyntaxException e) { - CrashReport report = CrashReport.makeCrashReport(e, - "JSON Parsing Error in " + conf.toString()); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - } - - private static JsonObject doHandlePresets(final JsonObject spawnData) { - final PresetsStorage configPresets = OreSpawn.API.copyPresets(); - if (spawnData.has(Constants.ConfigNames.PRESETS)) { - spawnData.get(Constants.ConfigNames.PRESETS).getAsJsonObject().entrySet().stream() - .forEach(entry -> { - String section = entry.getKey(); - entry.getValue().getAsJsonObject().entrySet().stream() - .forEach(sect -> configPresets.setSymbolSection(section, - sect.getKey(), sect.getValue())); - }); - } - - final JsonObject spawnDataFixed = new JsonObject(); - for (final Entry elem : spawnData.get(Constants.ConfigNames.SPAWNS) - .getAsJsonObject().entrySet()) { - spawnDataFixed.add(elem.getKey(), doPresetFix(elem.getValue(), configPresets)); - } - return spawnData; - } - - private static JsonElement doPresetForArray(final JsonArray value, - final PresetsStorage configPresets) { - final JsonArray rv = new JsonArray(); - value.forEach(it -> rv.add(doPresetFix(it, configPresets))); - return rv; - } - - private static JsonElement doPresetForObject(final JsonObject value, - final PresetsStorage configPresets) { - final JsonObject rv = new JsonObject(); - - value.entrySet().stream().forEach( - entry -> rv.add(entry.getKey(), doPresetFix(entry.getValue(), configPresets))); - return rv; - } - - public static void loadFromJson(final String name, final JsonElement json) { - final Entry t = new AbstractMap.SimpleEntry<>(name, json); - try { - loadSingleEntry(t); - } catch (UnknownFieldException | BadValueException | UnknownNameException e) { - final CrashReport report = CrashReport.makeCrashReport(e, - "Error parsing an manual JSON read for " + name); - report.getCategory().addCrashSection(ORE_SPAWN_VERSION, Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - } - - private static void loadSingleEntry(final Entry entry) - throws UnknownFieldException, BadValueException, UnknownNameException { - final ISpawnBuilder sb = OreSpawn.API.getSpawnBuilder(); - final IFeatureBuilder fb = OreSpawn.API.getFeatureBuilder(); - sb.setName(entry.getKey()); - for (final Entry ent : entry.getValue().getAsJsonObject().entrySet()) { - switch (ent.getKey()) { - case Constants.ConfigNames.RETROGEN: - sb.setRetrogen(ent.getValue().getAsBoolean()); - break; - case Constants.ConfigNames.ENABLED: - sb.setEnabled(ent.getValue().getAsBoolean()); - break; - case Constants.ConfigNames.DIMENSIONS: - final IDimensionBuilder db = OreSpawn.API.getDimensionBuilder(); - loadDimensionEntry(db, ent); - sb.setDimensions(db.create()); - break; - case Constants.ConfigNames.BIOMES: - if (!ent.getValue().isJsonObject()) { - throw new BadValueException(Constants.ConfigNames.BIOMES, - ent.getValue().toString()); - } - final IBiomeBuilder bb = OreSpawn.API.getBiomeBuilder(); - loadBiomes(bb, ent.getValue().getAsJsonObject()); - sb.setBiomes(bb.create()); - break; - case Constants.ConfigNames.FEATURE: - fb.setFeature(loadFeatureEntry(ent)); - break; - case Constants.ConfigNames.REPLACEMENT: - final IReplacementBuilder rb = OreSpawn.API.getReplacementBuilder(); - loadReplacements(rb, ent); - - if (rb.hasEntries()) { - sb.setReplacement(rb.create()); - } - break; - case Constants.ConfigNames.BLOCK: - loadBlocks(sb, ent); - break; - case Constants.ConfigNames.PARAMETERS: - if (ent.getValue().isJsonObject()) { - ent.getValue().getAsJsonObject().entrySet().stream() - .forEach(e -> fb.setParameter(e.getKey(), e.getValue())); - } - break; - default: - throw new UnknownFieldException(ent.getKey()); - } - } - sb.setFeature(fb.create()); - OreSpawn.API.addSpawn(sb.create()); - } - - private static String loadFeatureEntry(Entry ent) throws BadValueException, UnknownNameException { - if (ent.getValue().isJsonPrimitive() - && !ent.getValue().getAsJsonPrimitive().isString()) { - throw new BadValueException(Constants.ConfigNames.FEATURE, - ent.getValue().toString()); - } - final String featureName = ent.getValue().getAsString(); - if (!OreSpawn.API.featureExists(featureName)) { - throw new UnknownNameException(Constants.ConfigNames.FEATURE, featureName); - } - return featureName; - } - - @SuppressWarnings("deprecation") - private static void loadBlocks(ISpawnBuilder sb, Entry ent) throws BadValueException { - if (ent.getValue().isJsonArray()) { - for (final JsonElement elem : ent.getValue().getAsJsonArray()) { - final IBlockBuilder block = OreSpawn.API.getBlockBuilder(); - if (elem.isJsonObject()) { - final JsonObject bl = elem.getAsJsonObject(); - if (bl.has(Constants.ConfigNames.STATE)) { - block.setFromNameWithChance( - bl.get(Constants.ConfigNames.NAME).getAsString(), - bl.get(Constants.ConfigNames.STATE).getAsString(), - bl.get(Constants.ConfigNames.CHANCE).getAsInt()); - } else if (bl.has(Constants.ConfigNames.METADATA)) { - block.setFromNameWithChance( - bl.get(Constants.ConfigNames.NAME).getAsString(), - bl.get(Constants.ConfigNames.METADATA).getAsInt(), - bl.get(Constants.ConfigNames.CHANCE).getAsInt()); - } else { - block.setFromNameWithChance( - bl.get(Constants.ConfigNames.NAME).getAsString(), - bl.get(Constants.ConfigNames.CHANCE).getAsInt()); - } - sb.addBlock(block.create()); - } else { - OreSpawn.LOGGER.error( - "Skipping value {} in blocks list as it is not the correct format", - elem.toString()); - } - } - } else { - throw new BadValueException(Constants.ConfigNames.BLOCK, - ent.getValue().toString()); - } - } - - private static void loadReplacements(IReplacementBuilder rb, Entry ent) throws BadValueException { - if (!ent.getValue().isJsonArray() - && !ent.getValue().getAsJsonPrimitive().isString()) { - throw new BadValueException(Constants.ConfigNames.REPLACEMENT, - ent.getValue().toString()); - } else if (ent.getValue().isJsonPrimitive() - && ent.getValue().getAsJsonPrimitive().isString()) { - if (OreSpawn.API.hasReplacement(ent.getValue().getAsString())) { - rb.setFromName(ent.getValue().getAsString()); - } - } else { - for (final JsonElement e : ent.getValue().getAsJsonArray()) { - if (e.isJsonObject()) { - loadBlock(e.getAsJsonObject()).stream().forEach(rb::addEntry); - } else { - OreSpawn.LOGGER.error( - "Skipping value {} in replacements list as it is not the correct format", - e.toString()); - } - } - } - } - - private static void loadDimensionEntry(IDimensionBuilder db, Entry ent) throws BadValueException { - if (ent.getValue().isJsonArray()) { - final JsonArray dims = ent.getValue().getAsJsonArray(); - if (dims.size() == 0) { - // blank list, accept all overworld - db.setAcceptAllOverworld(); - } else { - dims.forEach(item -> { - if (item.isJsonPrimitive() - && item.getAsJsonPrimitive().isNumber()) { - db.addWhitelistEntry(item.getAsInt()); - } - }); - } - } else if (ent.getValue().isJsonObject()) { - loadDimensions(db, ent.getValue().getAsJsonObject()); - } else { - throw new BadValueException(Constants.ConfigNames.DIMENSIONS, - ent.getValue().toString()); - } - } - - @SuppressWarnings("deprecation") - private static List loadBlock(final JsonObject json) { - final String blockName = json.get(Constants.ConfigNames.NAME).getAsString(); - if (json.has(Constants.ConfigNames.STATE)) { - final Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(blockName)); - try { - return Arrays.asList(StateUtil.deserializeState(block, - json.get(Constants.ConfigNames.STATE).getAsString())); - } catch (BadStateValueException e) { - StringBuilder p = new StringBuilder(); - for(StackTraceElement elem: e.getStackTrace()) p.append(String.format("%s.%s (%s:%u)\n", elem.getClassName(), elem.getMethodName(), elem.getFileName(), elem.getLineNumber())); - OreSpawn.LOGGER.error(String.format("Exception: %s\n%s", e.getMessage(), p.toString())); - return Arrays.asList(block.getDefaultState()); - } - } else if (json.has(Constants.ConfigNames.METADATA)) { - final Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(blockName)); - return Arrays.asList( - block.getStateFromMeta(json.get(Constants.ConfigNames.METADATA).getAsInt())); - } - - if (blockName.startsWith("ore:")) { - final String entry = blockName.split(":")[1]; - return ImmutableList.copyOf(OreDictionary.getOres(entry, false).stream().map(is -> { - final Block b = Block.getBlockFromItem(is.getItem()); - return b.getStateFromMeta(is.getMetadata()); - }).collect(Collectors.toList())); - } - final Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(blockName)); - return Arrays.asList(block.getDefaultState()); - } - - private static final String WHITELIST_ERROR = "Skipping entry (%s) in whitelist, not a proper value"; - private static final String BLACKLIST_ERROR = "Skipping entry (%s) in blacklist, not a proper value"; - private static void loadBiomes(final IBiomeBuilder bb, final JsonObject biomeList) { - boolean emptyWhitelist = false; - - if (biomeList.has(Constants.ConfigNames.WHITELIST) - && biomeList.get(Constants.ConfigNames.WHITELIST).getAsJsonArray().size() > 0) { - loadBiomeWhitelist(bb, biomeList.get(Constants.ConfigNames.WHITELIST).getAsJsonArray()); - } else { - emptyWhitelist = true; - } - - if (biomeList.has(Constants.ConfigNames.BLACKLIST) - && biomeList.get(Constants.ConfigNames.BLACKLIST).getAsJsonArray().size() > 0) { - loadBiomeBlacklist(bb, biomeList.get(Constants.ConfigNames.BLACKLIST).getAsJsonArray()); - } else if (emptyWhitelist) { - // empty whitelist and blacklist - accept everything - bb.setAcceptAll(); - } - } - - private static void loadBiomeBlacklist(IBiomeBuilder bb, JsonArray blacklist) { - for (final JsonElement elem : blacklist) { - if (elem.isJsonPrimitive() && elem.getAsJsonPrimitive().isString()) { - final String xN = elem.getAsString(); - if (xN.contains(":")) { - // not a BiomeDictionary entry (we hope) - bb.addBlacklistEntry(xN); - } else { - BiomeDictionary.getBiomes(BiomeDictionary.Type.getType(xN)).stream() - .forEach(bb::addBlacklistEntry); - } - } else { - OreSpawn.LOGGER.error(BLACKLIST_ERROR, elem.getAsString()); - } - } - } - - private static void loadBiomeWhitelist(IBiomeBuilder bb, JsonArray whitelist) { - for (final JsonElement elem : whitelist) { - if (elem.isJsonPrimitive() && elem.getAsJsonPrimitive().isString()) { - final String xN = elem.getAsString(); - if (xN.contains(":")) { - // not a BiomeDictionary entry (we hope) - bb.addWhitelistEntry(xN); - } else { - BiomeDictionary.getBiomes(BiomeDictionary.Type.getType(xN)).stream() - .forEach(bb::addWhitelistEntry); - } - } else { - OreSpawn.LOGGER.error(WHITELIST_ERROR, elem.getAsString()); - } - } - } - - private static void loadDimensions(final IDimensionBuilder db, final JsonObject dimensionList) { - boolean emptyWhitelist = false; - - if (dimensionList.has(Constants.ConfigNames.WHITELIST) - && dimensionList.get(Constants.ConfigNames.WHITELIST).getAsJsonArray().size() > 0) { - loadDimensionWhitelist(db, dimensionList.get(Constants.ConfigNames.WHITELIST).getAsJsonArray()); - } else { - emptyWhitelist = true; - } - - if (dimensionList.has(Constants.ConfigNames.BLACKLIST) - && dimensionList.get(Constants.ConfigNames.BLACKLIST).getAsJsonArray().size() > 0) { - loadDimensionBlacklist(db, dimensionList.get(Constants.ConfigNames.BLACKLIST).getAsJsonArray()); - } else if (emptyWhitelist) { - db.setAcceptAllOverworld(); - } - } - - private static void loadDimensionBlacklist(IDimensionBuilder db, JsonArray blacklist) { - for (final JsonElement elem : blacklist) { - if (elem.isJsonPrimitive() && elem.getAsJsonPrimitive().isNumber()) { - db.addBlacklistEntry(elem.getAsInt()); - } else { - OreSpawn.LOGGER.error(WHITELIST_ERROR, elem.getAsString()); - } - } - } - - private static void loadDimensionWhitelist(IDimensionBuilder db, JsonArray whitelist) { - for (final JsonElement elem : whitelist) { - if (elem.isJsonPrimitive() && elem.getAsJsonPrimitive().isNumber()) { - db.addWhitelistEntry(elem.getAsInt()); - } else { - OreSpawn.LOGGER.error(BLACKLIST_ERROR, elem.getAsString()); - } - } - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/json/OreSpawnWriter.java b/src/main/java/com/mcmoddev/orespawn/json/OreSpawnWriter.java deleted file mode 100644 index f8edba4..0000000 --- a/src/main/java/com/mcmoddev/orespawn/json/OreSpawnWriter.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.mcmoddev.orespawn.json; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.util.List; -import java.util.Map; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.os3.ISpawnEntry; -import com.mcmoddev.orespawn.data.Constants; -import com.mcmoddev.orespawn.data.Constants.ConfigNames; - -import net.minecraft.crash.CrashReport; - -public class OreSpawnWriter { - - /* - * Write out the configs as the system knows them to the 'forced-saves' directory - */ - public static void saveConfigs() { - final Map> configs = OreSpawn.API.getSpawnsByFile(); - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - configs.entrySet().stream().forEach(ent -> saveSingle(ent.getKey(), gson)); - } - - private static void saveSingle(final Path filePath, final Gson gson) { - final JsonObject root = new JsonObject(); - root.addProperty(ConfigNames.FILE_VERSION, "2.0"); - final JsonObject spawns = new JsonObject(); - final String k = filePath.getFileName().toString(); - final Path saveDir = Constants.CONFDIR.resolve("forced-saves"); - final Path conf = saveDir.resolve(k); - if (!saveDir.toFile().exists()) { - saveDir.toFile().mkdirs(); - } - try (final BufferedWriter p = Files.newBufferedWriter(conf, StandardOpenOption.CREATE, - StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { - OreSpawn.API.getSpawnsForFile(k).stream().forEach(spawnName -> { - final JsonObject thisSpawn = new JsonObject(); - final ISpawnEntry spawnEntry = OreSpawn.API.getSpawn(spawnName); - thisSpawn.addProperty(ConfigNames.ENABLED, spawnEntry.isEnabled()); - thisSpawn.addProperty(ConfigNames.RETROGEN, spawnEntry.isRetrogen()); - thisSpawn.addProperty(ConfigNames.FEATURE, - spawnEntry.getFeature().getFeatureName()); - thisSpawn.add(ConfigNames.DIMENSIONS, spawnEntry.getDimensions().serialize()); - thisSpawn.add(ConfigNames.BIOMES, spawnEntry.getBiomes().serialize()); - thisSpawn.add(ConfigNames.REPLACEMENT, spawnEntry.getMatcher().serialize()); - thisSpawn.add(ConfigNames.PARAMETERS, - spawnEntry.getFeature().getFeatureParameters()); - spawns.add(spawnName, thisSpawn); - }); - root.add(ConfigNames.SPAWNS, spawns); - p.write(gson.toJson(root)); - } catch (final IOException e) { - CrashReport report = CrashReport.makeCrashReport(e, - "Failed writing config data " + conf.toString()); - report.getCategory().addCrashSection("OreSpawn Version", Constants.VERSION); - OreSpawn.LOGGER.info(report.getCompleteReport()); - } - - } - - public static void saveSingle(final String fileName) { - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - saveSingle(Constants.CONFDIR.resolve(fileName), gson); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/misc/M.java b/src/main/java/com/mcmoddev/orespawn/misc/M.java new file mode 100644 index 0000000..d5aa686 --- /dev/null +++ b/src/main/java/com/mcmoddev/orespawn/misc/M.java @@ -0,0 +1,23 @@ +package com.mcmoddev.orespawn.misc; + +import net.minecraft.util.RandomSource; + +public class M { + + public static double triangularDistribution(double a, double b, double c, RandomSource random) { + double base = (c - a) / (b - a); + double rand = random.nextDouble(); + + if (rand < base) { + return a + Math.sqrt(rand * (b - a) * (c - a)); + } else { + return b - Math.sqrt((1 - rand) * (b - a) * (b - c)); + } + } + public static int getPoint(int lowerBound, int upperBound, int median, RandomSource random) { + int t = (int)Math.round(triangularDistribution((float)lowerBound, (float)upperBound, (float)median, random)); + return t - median; + } + + +} diff --git a/src/main/java/com/mcmoddev/orespawn/util/Collectors2.java b/src/main/java/com/mcmoddev/orespawn/util/Collectors2.java deleted file mode 100644 index bbe8ade..0000000 --- a/src/main/java/com/mcmoddev/orespawn/util/Collectors2.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.mcmoddev.orespawn.util; - -import java.util.stream.Collector; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -public final class Collectors2 { - - private Collectors2() { - } - - public static Collector, ImmutableList> toImmutableList() { - return Collector.of(ImmutableList.Builder::new, ImmutableList.Builder::add, - (left, right) -> left.addAll(right.build()), ImmutableList.Builder::build); - } - - public static Collector, ImmutableSet> toImmutableSet() { - return Collector.of(ImmutableSet.Builder::new, ImmutableSet.Builder::add, - (left, right) -> left.addAll(right.build()), ImmutableSet.Builder::build); - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/util/StateUtil.java b/src/main/java/com/mcmoddev/orespawn/util/StateUtil.java deleted file mode 100644 index 1997dae..0000000 --- a/src/main/java/com/mcmoddev/orespawn/util/StateUtil.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.mcmoddev.orespawn.util; - -import com.google.common.base.Optional; -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.exceptions.BadStateValueException; - -import net.minecraft.block.Block; -import net.minecraft.block.properties.IProperty; -import net.minecraft.block.state.IBlockState; - -public class StateUtil { - - private StateUtil() { - throw new InstantiationError("This class cannot be instantiated!"); - } - - public static String serializeState(final IBlockState state) { - String string = state.toString(); - string = string.substring(string.indexOf('[') + 1, - string.length() - (string.endsWith("]") ? 1 : 0)); - - if (string.equals(state.getBlock().getRegistryName().toString())) { - string = "normal"; - } - - OreSpawn.LOGGER.debug("State is %s (for block %s)", string, - state.getBlock().getRegistryName()); - return string; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static IBlockState deserializeState(final Block block, final String state) throws BadStateValueException { - String bits[]; - if(state.contains(",")) bits = state.split(","); - else bits = new String[] { state }; - - IBlockState rv = block.getDefaultState(); - - for(String sv : bits) { - String kvp[] = sv.split("="); - IProperty prop = block.getBlockState().getProperty(kvp[0]); - if(prop != null) { - Optional propValue = prop.parseValue(kvp[1]); - if(propValue.isPresent()) - rv = rv.withProperty(prop, propValue.get()); - else - throw new BadStateValueException(String.format("%s is not a valid value for property %s", kvp[1], kvp[0])); - } else { - throw new BadStateValueException(String.format("%s is not a known property of %s", kvp[0], block.getRegistryName())); - } - } - - return rv; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/worldgen/FlatBedrock.java b/src/main/java/com/mcmoddev/orespawn/worldgen/FlatBedrock.java deleted file mode 100644 index 497069e..0000000 --- a/src/main/java/com/mcmoddev/orespawn/worldgen/FlatBedrock.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.mcmoddev.orespawn.worldgen; - -import java.util.Random; - -import com.mcmoddev.orespawn.data.Config; -import com.mcmoddev.orespawn.data.Constants; - -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.World; -import net.minecraft.world.WorldType; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; -import net.minecraftforge.fml.common.IWorldGenerator; - -public class FlatBedrock implements IWorldGenerator { - - @Override - public void generate(final Random random, final int chunkX, final int chunkZ, final World world, - final IChunkGenerator chunkGenerator, final IChunkProvider chunkProvider) { - // no need to do flat-bedrock on a "FLAT" world - if (world.getWorldType() != WorldType.FLAT) { - if (world.provider.getDimension() == -1) { - genTopPlate(world, new ChunkPos(chunkX, chunkZ), Blocks.NETHERRACK); - genBottomPlate(world, new ChunkPos(chunkX, chunkZ), Blocks.NETHERRACK); - } else if (world.provider.getDimension() >= 0 && world.provider.getDimension() != 1) { - genBottomPlate(world, new ChunkPos(chunkX, chunkZ), Blocks.STONE); - } - } - } - - public void retrogen(final World world, final int chunkX, final int chunkZ) { - if (world.getWorldType() != WorldType.FLAT) { - if (world.provider.getDimension() == -1) { - genTopPlate(world, new ChunkPos(chunkX, chunkZ), Blocks.NETHERRACK); - genBottomPlate(world, new ChunkPos(chunkX, chunkZ), Blocks.NETHERRACK); - } else if (world.provider.getDimension() >= 0 && world.provider.getDimension() != 1) { - genBottomPlate(world, new ChunkPos(chunkX, chunkZ), Blocks.STONE); - } - } - } - - private void genBottomPlate(final World world, final ChunkPos chunkPos, final Block repBlock) { - final int plateThickness = Config.getInt(Constants.BEDROCK_LAYERS); - - for (int xP = 0; xP < 16; xP++) { - for (int zP = 0; zP < 16; zP++) { - for (int yP = 5; yP > 0; yP--) { - final BlockPos target = new BlockPos(chunkPos.x * 16 + xP, yP, - chunkPos.z * 16 + zP); - - if (yP < plateThickness - && !world.getBlockState(target).getBlock().equals(Blocks.BEDROCK)) { - world.setBlockState(target, Blocks.BEDROCK.getDefaultState(), 26); - } else if (yP >= plateThickness - && world.getBlockState(target).getBlock().equals(Blocks.BEDROCK)) { - world.setBlockState(target, repBlock.getDefaultState(), 26); - } - } - } - } - } - - private void genTopPlate(final World world, final ChunkPos chunkPos, final Block repBlock) { - final int plateThickness = Config.getInt(Constants.BEDROCK_LAYERS); - final int thickness = 127 - plateThickness; // layer where the flat for the top starts - - for (int xP = 0; xP < 16; xP++) { - for (int zP = 0; zP < 16; zP++) { - for (int yP = 126; yP > 121; yP--) { - final BlockPos target = new BlockPos(chunkPos.x * 16 + xP, yP, - chunkPos.z * 16 + zP); - - if (yP > thickness - && !world.getBlockState(target).getBlock().equals(Blocks.BEDROCK)) { - world.setBlockState(target, Blocks.BEDROCK.getDefaultState(), 26); - } else if (yP <= thickness - && world.getBlockState(target).getBlock().equals(Blocks.BEDROCK)) { - world.setBlockState(target, repBlock.getDefaultState(), 26); - } - } - } - } - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/worldgen/OreSpawnFeatureGenerator.java b/src/main/java/com/mcmoddev/orespawn/worldgen/OreSpawnFeatureGenerator.java deleted file mode 100644 index a650109..0000000 --- a/src/main/java/com/mcmoddev/orespawn/worldgen/OreSpawnFeatureGenerator.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.mcmoddev.orespawn.worldgen; - -import java.util.Random; - -import com.mcmoddev.orespawn.api.os3.ISpawnEntry; -import com.mcmoddev.orespawn.api.os3.OS3FeatureGenerator; -import com.mcmoddev.orespawn.data.Config; -import com.mcmoddev.orespawn.data.Constants; - -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; -import net.minecraftforge.fml.common.IWorldGenerator; -import net.minecraft.util.math.ChunkPos; - -public class OreSpawnFeatureGenerator implements IWorldGenerator, OS3FeatureGenerator { - private final ISpawnEntry spawn; - private final String name; - - public OreSpawnFeatureGenerator( final ISpawnEntry spawn, final String name ) { - this.spawn = spawn; - this.name = name; - } - - @Override - public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, - IChunkProvider chunkProvider) { - final int thisDim = world.provider.getDimension(); - - if ((Config.getBoolean(Constants.RETROGEN_KEY) && - ((this.spawn.isRetrogen() || Config.getBoolean(Constants.FORCE_RETROGEN_KEY)))) || - (this.spawn.isEnabled() && this.spawn.dimensionAllowed(thisDim))) { - this.spawn.generate(random, world, chunkGenerator, chunkProvider, new ChunkPos(chunkX, chunkZ)); - } - } - - @Override - public ISpawnEntry getSpawnData() { - return this.spawn; - } - - @Override - public String getSpawnName() { - return this.name; - } -} diff --git a/src/main/java/com/mcmoddev/orespawn/worldgen/OreSpawnWorldGen.java b/src/main/java/com/mcmoddev/orespawn/worldgen/OreSpawnWorldGen.java deleted file mode 100644 index 94d5e05..0000000 --- a/src/main/java/com/mcmoddev/orespawn/worldgen/OreSpawnWorldGen.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.mcmoddev.orespawn.worldgen; - -import java.util.Random; - -import com.mcmoddev.orespawn.OreSpawn; -import com.mcmoddev.orespawn.api.os3.ISpawnEntry; -import com.mcmoddev.orespawn.data.Config; -import com.mcmoddev.orespawn.data.Constants; - -import net.minecraft.util.math.ChunkPos; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.gen.IChunkGenerator; -import net.minecraftforge.fml.common.IWorldGenerator; - -public class OreSpawnWorldGen implements IWorldGenerator { - - @Override - public void generate(final Random random, final int chunkX, final int chunkZ, final World world, - final IChunkGenerator chunkGenerator, final IChunkProvider chunkProvider) { - - final int thisDim = world.provider.getDimension(); - - OreSpawn.API.getSpawns(thisDim).stream().filter(ISpawnEntry::isEnabled) - .filter(sb -> !Config.getBoolean(Constants.RETROGEN_KEY) - || (sb.isRetrogen() || Config.getBoolean(Constants.FORCE_RETROGEN_KEY))) - .forEach(spawn -> spawn.generate(random, world, chunkGenerator, chunkProvider, - new ChunkPos(chunkX, chunkZ))); - } -} diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..f0156b6 --- /dev/null +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,100 @@ +# This is an example neoforge.mods.toml file. It contains the data relating to the loading mods. +# There are several mandatory fields (#mandatory), and many more that are optional (#optional). +# The overall format is standard TOML format, v0.5.0. +# Note that there are a couple of TOML lists in this file. +# Find more information on toml format here: https://github.com/toml-lang/toml +# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml +modLoader="javafml" #mandatory + +# A version range to match for said mod loader - for regular FML @Mod it will be the FML version. This is currently 2. +loaderVersion="${loader_version_range}" #mandatory + +# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties. +# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here. +license="${mod_license}" + +# A URL to refer people to when problems occur with this mod +#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional + +# A list of mods - how many allowed here is determined by the individual mod loader +[[mods]] #mandatory + +# The modid of the mod +modId="${mod_id}" #mandatory + +# The version number of the mod +version="${mod_version}" #mandatory + +# A display name for the mod +displayName="${mod_name}" #mandatory + +# A URL to query for updates for this mod. See the JSON update specification https://docs.neoforged.net/docs/misc/updatechecker/ +#updateJSONURL="https://change.me.example.invalid/updates.json" #optional + +# A URL for the "homepage" for this mod, displayed in the mod UI +#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional + +# A file name (in the root of the mod JAR) containing a logo for display +#logoFile="examplemod.png" #optional + +# A text field displayed in the mod UI +#credits="" #optional + +# A text field displayed in the mod UI +authors="${mod_authors}" #optional + +# Display Test controls the display for your mod in the server connection screen +# MATCH_VERSION means that your mod will cause a red X if the versions on client and server differ. This is the default behaviour and should be what you choose if you have server and client elements to your mod. +# IGNORE_SERVER_VERSION means that your mod will not cause a red X if it's present on the server but not on the client. This is what you should use if you're a server only mod. +# IGNORE_ALL_VERSION means that your mod will not cause a red X if it's present on the client or the server. This is a special case and should only be used if your mod has no server component. +# NONE means that no display test is set on your mod. You need to do this yourself, see IExtensionPoint.DisplayTest for more information. You can define any scheme you wish with this value. +# IMPORTANT NOTE: this is NOT an instruction as to which environments (CLIENT or DEDICATED SERVER) your mod loads on. Your mod should load (and maybe do nothing!) whereever it finds itself. +#displayTest="MATCH_VERSION" # MATCH_VERSION is the default if nothing is specified (#optional) + +# The description text for the mod (multi line!) (#mandatory) +description='''${mod_description}''' + +# The [[mixins]] block allows you to declare your mixin config to FML so that it gets loaded. +#[[mixins]] +#config="${mod_id}.mixins.json" + +# The [[accessTransformers]] block allows you to declare where your AT file is. +# If this block is omitted, a fallback attempt will be made to load an AT from META-INF/accesstransformer.cfg +#[[accessTransformers]] +#file="META-INF/accesstransformer.cfg" + +# The coremods config file path is not configurable and is always loaded from META-INF/coremods.json + +# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional. +[[dependencies.${mod_id}]] #optional + # the modid of the dependency + modId="neoforge" #mandatory + # The type of the dependency. Can be one of "required", "optional", "incompatible" or "discouraged" (case insensitive). + # 'required' requires the mod to exist, 'optional' does not + # 'incompatible' will prevent the game from loading when the mod exists, and 'discouraged' will show a warning + type="required" #mandatory + # Optional field describing why the dependency is required or why it is incompatible + # reason="..." + # The version range of the dependency + versionRange="${neo_version_range}" #mandatory + # An ordering relationship for the dependency. + # BEFORE - This mod is loaded BEFORE the dependency + # AFTER - This mod is loaded AFTER the dependency + ordering="NONE" + # Side this dependency is applied on - BOTH, CLIENT, or SERVER + side="BOTH" + +# Here's another dependency +[[dependencies.${mod_id}]] + modId="minecraft" + type="required" + # This version range declares a minimum of the current minecraft version up to but not including the next major version + versionRange="${minecraft_version_range}" + ordering="NONE" + side="BOTH" + +# Features are specific properties of the game environment, that you may want to declare you require. This example declares +# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't +# stop your mod loading on the server for example. +#[features.${mod_id}] +#openGLVersion="[3.2,)" diff --git a/src/main/resources/assets/orespawn/configs/_features.json b/src/main/resources/assets/orespawn/configs/_features.json deleted file mode 100644 index 09075a3..0000000 --- a/src/main/resources/assets/orespawn/configs/_features.json +++ /dev/null @@ -1,26 +0,0 @@ -[ - { - "name": "default", - "class": "com.mcmoddev.orespawn.impl.features.DefaultFeatureGenerator" - }, - { - "name": "vein", - "class": "com.mcmoddev.orespawn.impl.features.VeinGenerator" - }, - { - "name": "normal-cloud", - "class": "com.mcmoddev.orespawn.impl.features.NormalCloudGenerator" - }, - { - "name": "precision", - "class": "com.mcmoddev.orespawn.impl.features.PrecisionGenerator" - }, - { - "name": "clusters", - "class": "com.mcmoddev.orespawn.impl.features.ClusterGenerator" - }, - { - "name": "underfluids", - "class": "com.mcmoddev.orespawn.impl.features.UnderFluid" - } -] \ No newline at end of file diff --git a/src/main/resources/assets/orespawn/configs/_replacements.json b/src/main/resources/assets/orespawn/configs/_replacements.json deleted file mode 100644 index 8e378cf..0000000 --- a/src/main/resources/assets/orespawn/configs/_replacements.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "default": [ { "name": "minecraft:stone" }, - { "name": "minecraft:andesite" }, - { "name": "minecraft:diorite" }, - { "name": "minecraft:granite" }, - { "name": "minecraft:netherrack" }, - { "name": "minecraft:end_stone" } ] -} diff --git a/src/main/resources/assets/orespawn/configs/orespawn.json b/src/main/resources/assets/orespawn/configs/orespawn.json deleted file mode 100755 index 4021c4f..0000000 --- a/src/main/resources/assets/orespawn/configs/orespawn.json +++ /dev/null @@ -1,332 +0,0 @@ -{ - "version": "2.0", - "spawns": { - "quartz_ore": { - "retrogen": false, - "enabled": true, - "feature": "default", - "replaces": "default", - "dimensions": [ - -1 - ], - "biomes": { - "excludes": [] - }, - "parameters": { - "size": 15, - "variation": 4, - "frequency": 7, - "minHeight": 0, - "maxHeight": 128 - }, - "blocks": [ - { - "name": "minecraft:quartz_ore", - "chance": 100 - } - ] - }, - "coal_ore": { - "retrogen": false, - "enabled": true, - "feature": "default", - "replaces": "default", - "dimensions": [], - "biomes": { - "excludes": [] - }, - "parameters": { - "size": 25, - "variation": 12, - "frequency": 20, - "minHeight": 0, - "maxHeight": 128 - }, - "blocks": [ - { - "name": "minecraft:coal_ore", - "chance": 100 - } - ] - }, - "iron_ore": { - "retrogen": false, - "enabled": true, - "feature": "default", - "replaces": "default", - "dimensions": [], - "biomes": { - "excludes": [] - }, - "parameters": { - "size": 8, - "variation": 4, - "frequency": 20, - "minHeight": 0, - "maxHeight": 64 - }, - "blocks": [ - { - "name": "minecraft:iron_ore", - "chance": 100 - } - ] - }, - "gold_ore_standard": { - "retrogen": false, - "enabled": true, - "feature": "default", - "replaces": "default", - "dimensions": [], - "biomes": { - "excludes": [] - }, - "parameters": { - "size": 8, - "variation": 2, - "frequency": 2, - "minHeight": 0, - "maxHeight": 32 - }, - "blocks": [ - { - "name": "minecraft:gold_ore", - "chance": 100 - } - ] - }, - "gold_ore_mesa": { - "retrogen": false, - "enabled": true, - "feature": "default", - "replaces": "default", - "dimensions": [], - "biomes": { - "includes": [ "MESA" ] - }, - "parameters": { - "size": 8, - "variation": 2, - "frequency": 2, - "minHeight": 32, - "maxHeight": 79 - }, - "blocks": [ - { - "name": "minecraft:gold_ore", - "chance": 100 - } - ] - }, - "diamond_ore": { - "retrogen": false, - "enabled": true, - "feature": "precision", - "replaces": "default", - "dimensions": [], - "biomes": { - "excludes": [] - }, - "parameters": { - "size": 3, - "numObjects": 2, - "minHeight": 0, - "maxHeight": 16 - }, - "blocks": [ - { - "name": "minecraft:diamond_ore", - "chance": 100 - } - ] - }, - "redstone_ore": { - "retrogen": false, - "enabled": true, - "feature": "default", - "replaces": "default", - "dimensions": [], - "biomes": { - "excludes": [] - }, - "parameters": { - "size": 6, - "variation": 3, - "frequency": 8, - "minHeight": 0, - "maxHeight": 16 - }, - "blocks": [ - { - "name": "minecraft:redstone_ore", - "chance": 100 - } - ] - }, - "lapis_ore": { - "retrogen": false, - "enabled": false, - "feature": "default", - "replaces": "default", - "dimensions": [], - "biomes": { - "excludes": [] - }, - "parameters": { - "size": 5, - "variation": 2, - "frequency": 1, - "minHeight": 0, - "maxHeight": 32 - }, - "blocks": [ - { - "name": "minecraft:lapis_ore", - "chance": 100 - } - ] - }, - "emerald_ore": { - "retrogen": false, - "enabled": true, - "feature": "default", - "replaces": "default", - "dimensions": [], - "biomes": { - "includes": [ "MOUNTAIN" ] - }, - "parameters": { - "size": 1, - "variation": 0, - "frequency": 8, - "minHeight": 4, - "maxHeight": 32 - }, - "blocks": [ - { - "name": "minecraft:emerald_ore", - "chance": 100 - } - ] - }, - "dirt": { - "retrogen": false, - "enabled": true, - "feature": "default", - "replaces": "default", - "dimensions": [], - "biomes": { - "excludes": [] - }, - "parameters": { - "size": 112, - "variation": 50, - "frequency": 10, - "minHeight": 0, - "maxHeight": 255 - }, - "blocks": [ - { - "name": "minecraft:dirt", - "chance": 100, - "state": "snowy=false,variant=dirt" - } - ] - }, - "gravel": { - "retrogen": false, - "enabled": true, - "feature": "default", - "replaces": "default", - "dimensions": [], - "biomes": { - "excludes": [] - }, - "parameters": { - "size": 112, - "variation": 50, - "frequency": 8, - "minHeight": 0, - "maxHeight": 255 - }, - "blocks": [ - { - "name": "minecraft:gravel", - "chance": 100 - } - ] - }, - "andesite": { - "retrogen": false, - "enabled": true, - "feature": "default", - "replaces": "default", - "dimensions": [], - "biomes": { - "excludes": [] - }, - "parameters": { - "size": 112, - "variation": 50, - "frequency": 10, - "minHeight": 0, - "maxHeight": 255 - }, - "blocks": [ - { - "name": "minecraft:stone", - "chance": 100, - "state": "variant=andesite" - } - ] - }, - "diorite": { - "retrogen": false, - "enabled": true, - "feature": "default", - "replaces": "default", - "dimensions": [], - "biomes": { - "excludes": [] - }, - "parameters": { - "size": 112, - "variation": 50, - "frequency": 10, - "minHeight": 0, - "maxHeight": 255 - }, - "blocks": [ - { - "name": "minecraft:stone", - "chance": 100, - "state": "variant=diorite" - } - ] - }, - "granite": { - "retrogen": false, - "enabled": true, - "feature": "default", - "replaces": "default", - "dimensions": [], - "biomes": { - "excludes": [] - }, - "parameters": { - "size": 112, - "variation": 50, - "frequency": 10, - "minHeight": 0, - "maxHeight": 255 - }, - "blocks": [ - { - "name": "minecraft:stone", - "chance": 100, - "state": "variant=granite" - } - ] - } - } -} \ No newline at end of file diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info deleted file mode 100644 index c9bf053..0000000 --- a/src/main/resources/mcmod.info +++ /dev/null @@ -1,15 +0,0 @@ -[ - { - "modid": "orespawn", - "name": "OreSpawn", - "description": "A customizable ore-spawning system that uses JSON files to specify custom ore generation", - "version": "${version}", - "authorList": [ - "dshadowwolf", - "iLexiconn", - "jriwanek", - "DrCyano" - ], - "credits": "The MMD community" - } -] diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta deleted file mode 100644 index 6065f6d..0000000 --- a/src/main/resources/pack.mcmeta +++ /dev/null @@ -1,6 +0,0 @@ -{ - "pack":{ - "pack_format":2, - "description":"Ore Spawn" - } -}