Import all versions (#8)

* Import all versions

* Prepare first workflow

* Cleanup build scripts

* More cleanup

* Cleanup more stuff and 1.7 on server

* Run multiple tasks in parallel

* Use version in job name

* Error on missing files

* Backport EULA mixin

* Update upload artifact

* Prevent build getting stuck

* Cleanup code

* More code cleanup

* Update build.yml

* Fix compilation

---------

Co-authored-by: Romain Beaumont <romain.rom1@gmail.com>
This commit is contained in:
Alex
2023-12-31 20:25:13 +01:00
committed by GitHub
co-authored by Romain Beaumont
parent 5441b07c50
commit a48fb9912d
556 changed files with 30777 additions and 814 deletions
+31
View File
@@ -0,0 +1,31 @@
plugins {
id 'fabric-loom'
}
dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
// Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
}
processResources {
filteringCharset "UTF-8"
filesMatching("fabric.mod.json") {
expand "version": project.version
}
}
tasks.withType(JavaCompile).configureEach {
it.options.encoding = "UTF-8"
}
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
+8
View File
@@ -0,0 +1,8 @@
# Fabric Properties
# check these on https://modmuss50.me/fabric.html
minecraft_version=1.14
yarn_mappings=1.14+build.21
loader_version=0.13.3
# Dependencies
# check this on https://modmuss50.me/fabric.html
fabric_version=0.3.0-pre+build.156
@@ -0,0 +1,36 @@
package dev.u9g.minecraftdatagenerator.ClientSideAnnoyances;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.biome.Biome;
public class FoliageColors {
private static int[] colorMap = new int[65536];
public static void setColorMap(int[] pixels) {
colorMap = pixels;
}
public static int getColor(double temperature, double humidity) {
int i = (int) ((1.0 - temperature) * 255.0);
int j = (int) ((1.0 - (humidity *= temperature)) * 255.0);
return colorMap[j << 8 | i];
}
public static int getSpruceColor() {
return 0x619961;
}
public static int getBirchColor() {
return 8431445;
}
public static int getDefaultColor() {
return 4764952;
}
public static int getFoliageColor(Biome biome) {
double d = MathHelper.clamp(biome.getTemperature(), 0.0f, 1.0f);
double e = MathHelper.clamp(biome.getRainfall(), 0.0f, 1.0f);
return getColor(d, e);
}
}
@@ -0,0 +1,29 @@
package dev.u9g.minecraftdatagenerator.ClientSideAnnoyances;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.biome.Biome;
public class GrassColors {
private static int[] colorMap = new int[65536];
public static void setColorMap(int[] is) {
colorMap = is;
}
public static int getColor(double d, double e) {
int j = (int) ((1.0 - (e *= d)) * 255.0);
int i = (int) ((1.0 - d) * 255.0);
int k = j << 8 | i;
if (k > colorMap.length) {
return -65281;
}
return colorMap[k];
}
public static int getGrassColorAt(Biome biome) {
double d = MathHelper.clamp(biome.getTemperature(), 0.0f, 1.0f);
double e = MathHelper.clamp(biome.getRainfall(), 0.0f, 1.0f);
return getColor(d, e);
}
}
@@ -0,0 +1,25 @@
package dev.u9g.minecraftdatagenerator.ClientSideAnnoyances;
import net.minecraft.util.math.MathHelper;
public class ServerSideRedstoneWireBlock {
public static int getWireColor(int powerLevel) {
float f = (float) powerLevel / 15.0f;
float g = f * 0.6f + 0.4f;
if (powerLevel == 0) {
g = 0.3f;
}
float h = f * f * 0.7f - 0.5f;
float j = f * f * 0.6f - 0.7f;
if (h < 0.0f) {
h = 0.0f;
}
if (j < 0.0f) {
j = 0.0f;
}
int k = MathHelper.clamp((int) (g * 255.0f), 0, 255);
int l = MathHelper.clamp((int) (h * 255.0f), 0, 255);
int m = MathHelper.clamp((int) (j * 255.0f), 0, 255);
return 0xFF000000 | k << 16 | l << 8 | m;
}
}
@@ -0,0 +1,14 @@
package dev.u9g.minecraftdatagenerator;
import net.fabricmc.api.ModInitializer;
import java.util.logging.Logger;
public class Main implements ModInitializer {
public static final Logger LOGGER = Logger.getLogger("mc-data-gen-serv");
@Override
public void onInitialize() {
}
}
@@ -0,0 +1,139 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.biome.Biome;
import java.util.Objects;
public class BiomesDataGenerator implements IDataGenerator {
private static String guessBiomeDimensionFromCategory(Biome biome) {
return switch (biome.getCategory()) {
case NETHER -> "nether";
case THEEND -> "end";
default -> "overworld";
};
}
private static int getBiomeColorFor(String biomeName) {
return switch (biomeName) {
case "ocean" -> 112;
case "plains" -> 9286496;
case "desert" -> 16421912;
case "mountains" -> 6316128;
case "forest" -> 353825;
case "taiga" -> 747097;
case "swamp" -> 522674;
case "river" -> 255;
case "nether_wastes" -> 12532539;
case "the_end" -> 8421631;
case "frozen_ocean" -> 7368918;
case "frozen_river" -> 10526975;
case "snowy_tundra" -> 16777215;
case "snowy_mountains" -> 10526880;
case "mushroom_fields" -> 16711935;
case "mushroom_field_shore" -> 10486015;
case "beach" -> 16440917;
case "desert_hills" -> 13786898;
case "wooded_hills" -> 2250012;
case "taiga_hills" -> 1456435;
case "mountain_edge" -> 7501978;
case "jungle" -> 5470985;
case "jungle_hills" -> 2900485;
case "jungle_edge" -> 6458135;
case "deep_ocean" -> 48;
case "stone_shore" -> 10658436;
case "snowy_beach" -> 16445632;
case "birch_forest" -> 3175492;
case "birch_forest_hills" -> 2055986;
case "dark_forest" -> 4215066;
case "snowy_taiga" -> 3233098;
case "snowy_taiga_hills" -> 2375478;
case "giant_tree_taiga" -> 5858897;
case "giant_tree_taiga_hills" -> 4542270;
case "wooded_mountains" -> 5271632;
case "savanna" -> 12431967;
case "savanna_plateau" -> 10984804;
case "badlands" -> 14238997;
case "wooded_badlands_plateau" -> 11573093;
case "badlands_plateau" -> 13274213;
case "small_end_islands" -> 42;
case "end_midlands" -> 15464630;
case "end_highlands" -> 12828041;
case "end_barrens" -> 9474162;
case "warm_ocean" -> 172;
case "lukewarm_ocean" -> 144;
case "cold_ocean" -> 2105456;
case "deep_warm_ocean" -> 80;
case "deep_lukewarm_ocean" -> 64;
case "deep_cold_ocean" -> 2105400;
case "deep_frozen_ocean" -> 4210832;
case "the_void" -> 0;
case "sunflower_plains" -> 11918216;
case "desert_lakes" -> 16759872;
case "gravelly_mountains" -> 8947848;
case "flower_forest" -> 2985545;
case "taiga_mountains" -> 3378817;
case "swamp_hills" -> 3145690;
case "ice_spikes" -> 11853020;
case "modified_jungle" -> 8102705;
case "modified_jungle_edge" -> 9089855;
case "tall_birch_forest" -> 5807212;
case "tall_birch_hills" -> 4687706;
case "dark_forest_hills" -> 6846786;
case "snowy_taiga_mountains" -> 5864818;
case "giant_spruce_taiga" -> 8490617;
case "giant_spruce_taiga_hills" -> 7173990;
case "modified_gravelly_mountains" -> 7903352;
case "shattered_savanna" -> 15063687;
case "shattered_savanna_plateau" -> 13616524;
case "eroded_badlands" -> 16739645;
case "modified_wooded_badlands_plateau" -> 14204813;
case "modified_badlands_plateau" -> 15905933;
case "bamboo_jungle" -> 7769620;
case "bamboo_jungle_hills" -> 3884810;
case "nether" -> 16711680;
default -> throw new Error("Unexpected biome, with name: '" + biomeName + "'");
};
}
public static JsonObject generateBiomeInfo(Registry<Biome> registry, Biome biome) {
JsonObject biomeDesc = new JsonObject();
Identifier registryKey = registry.getId(biome);
String localizationKey = String.format("biome.%s.%s", Objects.requireNonNull(registryKey).getNamespace(), registryKey.getPath());
biomeDesc.addProperty("id", registry.getRawId(biome));
biomeDesc.addProperty("name", registryKey.getPath());
biomeDesc.addProperty("category", biome.getCategory().getName());
biomeDesc.addProperty("temperature", biome.getTemperature());
biomeDesc.addProperty("precipitation", biome.getPrecipitation().getName());
biomeDesc.addProperty("depth", biome.getDepth());
biomeDesc.addProperty("dimension", guessBiomeDimensionFromCategory(biome));
biomeDesc.addProperty("displayName", DGU.translateText(localizationKey));
biomeDesc.addProperty("color", getBiomeColorFor(registryKey.getPath()));
biomeDesc.addProperty("rainfall", biome.getRainfall());
return biomeDesc;
}
@Override
public String getDataName() {
return "biomes";
}
@Override
public JsonArray generateDataJson() {
JsonArray biomesArray = new JsonArray();
Registry<Biome> biomeRegistry = Registry.BIOME;
biomeRegistry.stream()
.map(biome -> generateBiomeInfo(biomeRegistry, biome))
.forEach(biomesArray::add);
return biomesArray;
}
}
@@ -0,0 +1,108 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.shape.VoxelShape;
import net.minecraft.world.EmptyBlockView;
import java.util.*;
public class BlockCollisionShapesDataGenerator implements IDataGenerator {
@Override
public String getDataName() {
return "blockCollisionShapes";
}
@Override
public JsonObject generateDataJson() {
Registry<Block> blockRegistry = Registry.BLOCK;
BlockShapesCache blockShapesCache = new BlockShapesCache();
blockRegistry.forEach(blockShapesCache::processBlock);
JsonObject resultObject = new JsonObject();
resultObject.add("blocks", blockShapesCache.dumpBlockShapeIndices(blockRegistry));
resultObject.add("shapes", blockShapesCache.dumpShapesObject());
return resultObject;
}
private static class BlockShapesCache {
public final Map<VoxelShape, Integer> uniqueBlockShapes = new HashMap<>();
public final Map<Block, List<Integer>> blockCollisionShapes = new HashMap<>();
private int lastCollisionShapeId = 0;
public void processBlock(Block block) {
List<BlockState> blockStates = block.getStateFactory().getStates();
List<Integer> blockCollisionShapes = new ArrayList<>();
for (BlockState blockState : blockStates) {
VoxelShape blockShape = blockState.getCollisionShape(EmptyBlockView.INSTANCE, BlockPos.ORIGIN);
Integer blockShapeIndex = uniqueBlockShapes.get(blockShape);
if (blockShapeIndex == null) {
blockShapeIndex = lastCollisionShapeId++;
uniqueBlockShapes.put(blockShape, blockShapeIndex);
}
blockCollisionShapes.add(blockShapeIndex);
}
this.blockCollisionShapes.put(block, blockCollisionShapes);
}
public JsonObject dumpBlockShapeIndices(Registry<Block> blockRegistry) {
JsonObject resultObject = new JsonObject();
for (var entry : blockCollisionShapes.entrySet()) {
List<Integer> blockCollisions = entry.getValue();
long distinctShapesCount = blockCollisions.stream().distinct().count();
JsonElement blockCollision;
if (distinctShapesCount == 1L) {
blockCollision = new JsonPrimitive(blockCollisions.get(0));
} else {
blockCollision = new JsonArray();
for (int collisionId : blockCollisions) {
((JsonArray) blockCollision).add(collisionId);
}
}
Identifier registryKey = blockRegistry.getId(entry.getKey());
resultObject.add(Objects.requireNonNull(registryKey).getPath(), blockCollision);
}
return resultObject;
}
public JsonObject dumpShapesObject() {
JsonObject shapesObject = new JsonObject();
for (var entry : uniqueBlockShapes.entrySet()) {
JsonArray boxesArray = new JsonArray();
entry.getKey().forEachBox((x1, y1, z1, x2, y2, z2) -> {
JsonArray oneBoxJsonArray = new JsonArray();
oneBoxJsonArray.add(x1);
oneBoxJsonArray.add(y1);
oneBoxJsonArray.add(z1);
oneBoxJsonArray.add(x2);
oneBoxJsonArray.add(y2);
oneBoxJsonArray.add(z2);
boxesArray.add(oneBoxJsonArray);
});
shapesObject.add(Integer.toString(entry.getValue()), boxesArray);
}
return shapesObject;
}
}
}
@@ -0,0 +1,157 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.common.base.CaseFormat;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.Main;
import dev.u9g.minecraftdatagenerator.mixin.MiningToolItemAccessor;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.block.AirBlock;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.MiningToolItem;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.state.property.BooleanProperty;
import net.minecraft.state.property.EnumProperty;
import net.minecraft.state.property.IntegerProperty;
import net.minecraft.state.property.Property;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.shape.VoxelShape;
import net.minecraft.world.EmptyBlockView;
import net.minecraft.world.loot.context.LootContext;
import net.minecraft.world.loot.context.LootContextParameters;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class BlocksDataGenerator implements IDataGenerator {
private static final Logger logger = Main.LOGGER;
private static List<Item> getItemsEffectiveForBlock(Block block) {
return Registry.ITEM.stream()
.filter(item -> item instanceof MiningToolItem)
.filter(item -> ((MiningToolItemAccessor) item).getEffectiveBlocks().contains(block))
.collect(Collectors.toList());
}
private static List<ItemStack> populateDropsIfPossible(BlockState blockState, Item firstToolItem) {
//If we have local world context, we can actually evaluate loot tables and determine actual data
ServerWorld serverWorld = (ServerWorld) DGU.getWorld();
var lootContext = new LootContext.Builder(serverWorld)
.put(LootContextParameters.POSITION, BlockPos.ORIGIN)
.put(LootContextParameters.TOOL, DGU.stackFor(firstToolItem));
blockState.getDroppedStacks(lootContext);
return blockState.getDroppedStacks(lootContext);
}
private static String getPropertyTypeName(Property<?> property) {
//Explicitly handle default minecraft properties
if (property instanceof BooleanProperty) {
return "bool";
}
if (property instanceof IntegerProperty) {
return "int";
}
if (property instanceof EnumProperty) {
return "enum";
}
//Use simple class name as fallback, this code will give something like
//example_type for ExampleTypeProperty class name
String rawPropertyName = property.getClass().getSimpleName().replace("Property", "");
return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, rawPropertyName);
}
private static <T extends Comparable<T>> JsonObject generateStateProperty(Property<T> property) {
JsonObject propertyObject = new JsonObject();
Collection<T> propertyValues = property.getValues();
propertyObject.addProperty("name", property.getName());
propertyObject.addProperty("type", getPropertyTypeName(property));
propertyObject.addProperty("num_values", propertyValues.size());
//Do not add values for vanilla boolean properties, they are known by default
if (!(property instanceof BooleanProperty)) {
JsonArray propertyValuesArray = new JsonArray();
for (T propertyValue : propertyValues) {
propertyValuesArray.add(property.getValueAsString(propertyValue));
}
propertyObject.add("values", propertyValuesArray);
}
return propertyObject;
}
public static JsonObject generateBlock(Registry<Block> blockRegistry, Block block) {
JsonObject blockDesc = new JsonObject();
List<BlockState> blockStates = block.getStateFactory().getStates();
BlockState defaultState = block.getDefaultState();
Identifier registryKey = blockRegistry.getId(block);
String localizationKey = block.getTranslationKey();
List<Item> effectiveTools = getItemsEffectiveForBlock(block);
blockDesc.addProperty("id", blockRegistry.getRawId(block));
blockDesc.addProperty("name", Objects.requireNonNull(registryKey).getPath());
blockDesc.addProperty("displayName", DGU.translateText(localizationKey));
float hardness = block.getDefaultState().getHardness(null, null);
blockDesc.addProperty("hardness", hardness);
blockDesc.addProperty("resistance", block.getBlastResistance());
blockDesc.addProperty("stackSize", block.asItem().getMaxAmount());
blockDesc.addProperty("diggable", hardness != -1.0f && !(block instanceof AirBlock));
JsonObject effTools = new JsonObject();
effectiveTools.forEach(item -> effTools.addProperty(
String.valueOf(Registry.ITEM.getRawId(item)), // key
item.getBlockBreakingSpeed(DGU.stackFor(item), defaultState) // value
));
blockDesc.add("effectiveTools", effTools);
blockDesc.addProperty("transparent", !defaultState.isFullOpaque(EmptyBlockView.INSTANCE, BlockPos.ORIGIN));
blockDesc.addProperty("emitLight", defaultState.getLuminance());
blockDesc.addProperty("filterLight", block.getLightSubtracted(block.getDefaultState(), EmptyBlockView.INSTANCE, BlockPos.ORIGIN));
blockDesc.addProperty("defaultState", Block.getRawIdFromState(defaultState));
blockDesc.addProperty("minStateId", Block.getRawIdFromState(blockStates.get(0)));
blockDesc.addProperty("maxStateId", Block.getRawIdFromState(blockStates.get(blockStates.size() - 1)));
JsonArray stateProperties = new JsonArray();
for (Property<?> property : block.getStateFactory().getProperties()) {
stateProperties.add(generateStateProperty(property));
}
blockDesc.add("states", stateProperties);
List<ItemStack> drops = populateDropsIfPossible(defaultState, effectiveTools.stream().findFirst().orElse(Items.AIR));
JsonArray dropsArray = new JsonArray();
drops.forEach(dropped -> dropsArray.add(Item.getRawIdByItem(dropped.getItem())));
blockDesc.add("drops", dropsArray);
VoxelShape blockCollisionShape = defaultState.getCollisionShape(EmptyBlockView.INSTANCE, BlockPos.ORIGIN);
blockDesc.addProperty("boundingBox", blockCollisionShape.isEmpty() ? "empty" : "block");
return blockDesc;
}
@Override
public String getDataName() {
return "blocks";
}
@Override
public JsonArray generateDataJson() {
JsonArray resultBlocksArray = new JsonArray();
Registry<Block> blockRegistry = Registry.BLOCK;
blockRegistry.forEach(block -> resultBlocksArray.add(generateBlock(blockRegistry, block)));
return resultBlocksArray;
}
}
@@ -0,0 +1,79 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonElement;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonWriter;
import dev.u9g.minecraftdatagenerator.Main;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DataGenerators {
private static final List<IDataGenerator> GENERATORS = new ArrayList<>();
private static final Logger logger = Main.LOGGER;
static {
register(new BiomesDataGenerator());
register(new BlockCollisionShapesDataGenerator());
register(new BlocksDataGenerator());
register(new EffectsDataGenerator());
register(new EnchantmentsDataGenerator());
register(new EntitiesDataGenerator());
register(new FoodsDataGenerator());
register(new ItemsDataGenerator());
register(new ParticlesDataGenerator());
register(new TintsDataGenerator());
register(new LanguageDataGenerator());
register(new InstrumentsDataGenerator());
}
public static void register(IDataGenerator generator) {
GENERATORS.add(generator);
}
public static boolean runDataGenerators(Path outputDirectory) {
try {
Files.createDirectories(outputDirectory);
} catch (IOException exception) {
logger.log(Level.INFO, "Failed to create data generator output directory at " + outputDirectory);
exception.printStackTrace();
return false;
}
int generatorsFailed = 0;
logger.log(Level.INFO, MessageFormat.format("Running minecraft data generators, output at {0}", outputDirectory));
for (IDataGenerator dataGenerator : GENERATORS) {
logger.log(Level.INFO, MessageFormat.format("Running generator {0}", dataGenerator.getDataName()));
try {
String outputFileName = String.format("%s.json", dataGenerator.getDataName());
JsonElement outputElement = dataGenerator.generateDataJson();
Path outputFilePath = outputDirectory.resolve(outputFileName);
try (Writer writer = Files.newBufferedWriter(outputFilePath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
JsonWriter jsonWriter = new JsonWriter(writer);
jsonWriter.setIndent(" ");
Streams.write(outputElement, jsonWriter);
}
logger.log(Level.INFO, MessageFormat.format("Generator: {0} -> {1}", dataGenerator.getDataName(), outputFileName));
} catch (Throwable exception) {
logger.log(Level.INFO, MessageFormat.format("Failed to run data generator {0}", dataGenerator.getDataName()));
exception.printStackTrace();
generatorsFailed++;
}
}
logger.log(Level.INFO, "Finishing running data generators");
return generatorsFailed == 0;
}
}
@@ -0,0 +1,48 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.mixin.StatusEffectAccessor;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectType;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.stream.Collectors;
public class EffectsDataGenerator implements IDataGenerator {
public static JsonObject generateEffect(Registry<StatusEffect> registry, StatusEffect statusEffect) {
JsonObject effectDesc = new JsonObject();
Identifier registryKey = registry.getId(statusEffect);
effectDesc.addProperty("id", registry.getRawId(statusEffect));
if (statusEffect == StatusEffects.UNLUCK) {
effectDesc.addProperty("name", "BadLuck");
effectDesc.addProperty("displayName", "Bad Luck");
} else {
effectDesc.addProperty("name", Arrays.stream(registryKey.getPath().split("_")).map(StringUtils::capitalize).collect(Collectors.joining()));
effectDesc.addProperty("displayName", DGU.translateText(statusEffect.getTranslationKey()));
}
effectDesc.addProperty("type", ((StatusEffectAccessor) statusEffect).type() == StatusEffectType.BENEFICIAL ? "good" : "bad");
return effectDesc;
}
@Override
public String getDataName() {
return "effects";
}
@Override
public JsonArray generateDataJson() {
JsonArray resultsArray = new JsonArray();
Registry<StatusEffect> statusEffectRegistry = Registry.STATUS_EFFECT;
statusEffectRegistry.forEach(effect -> resultsArray.add(generateEffect(statusEffectRegistry, effect)));
return resultsArray;
}
}
@@ -0,0 +1,111 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentTarget;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
public class EnchantmentsDataGenerator implements IDataGenerator {
private static final ImmutableMap<EnchantmentTarget, String> ENCHANTMENT_TARGET_NAMES = ImmutableMap.<EnchantmentTarget, String>builder()
.put(EnchantmentTarget.ARMOR, "armor")
.put(EnchantmentTarget.ARMOR_FEET, "armor_feet")
.put(EnchantmentTarget.ARMOR_LEGS, "armor_legs")
.put(EnchantmentTarget.ARMOR_CHEST, "armor_chest")
.put(EnchantmentTarget.ARMOR_HEAD, "armor_head")
.put(EnchantmentTarget.WEAPON, "weapon")
.put(EnchantmentTarget.DIGGER, "digger")
.put(EnchantmentTarget.FISHING_ROD, "fishing_rod")
.put(EnchantmentTarget.TRIDENT, "trident")
.put(EnchantmentTarget.BREAKABLE, "breakable")
.put(EnchantmentTarget.BOW, "bow")
.put(EnchantmentTarget.WEARABLE, "wearable")
.put(EnchantmentTarget.CROSSBOW, "crossbow")
.put(EnchantmentTarget.ALL, "vanishable") // according to VanishingCurseEnchantment
.build();
public static String getEnchantmentTargetName(EnchantmentTarget target) {
return ENCHANTMENT_TARGET_NAMES.getOrDefault(target, target.name().toLowerCase(Locale.ROOT));
}
// Equation enchantment costs follow is a * level + b, so we can easily retrieve a and b by passing zero level
private static JsonObject generateEnchantmentMinPowerCoefficients(Enchantment enchantment) {
int b = enchantment.getMinimumPower(0);
int a = enchantment.getMinimumPower(1) - b;
JsonObject resultObject = new JsonObject();
resultObject.addProperty("a", a);
resultObject.addProperty("b", b);
return resultObject;
}
private static JsonObject generateEnchantmentMaxPowerCoefficients(Enchantment enchantment) {
int b = getMaximumPower(enchantment, 0);
int a = getMaximumPower(enchantment, 1) - b;
JsonObject resultObject = new JsonObject();
resultObject.addProperty("a", a);
resultObject.addProperty("b", b);
return resultObject;
}
public static JsonObject generateEnchantment(Registry<Enchantment> registry, Enchantment enchantment) {
JsonObject enchantmentDesc = new JsonObject();
Identifier registryKey = registry.getId(enchantment);
enchantmentDesc.addProperty("id", registry.getRawId(enchantment));
enchantmentDesc.addProperty("name", Objects.requireNonNull(registryKey).getPath());
enchantmentDesc.addProperty("displayName", DGU.translateText(enchantment.getTranslationKey()));
enchantmentDesc.addProperty("maxLevel", enchantment.getMaximumLevel());
enchantmentDesc.add("minCost", generateEnchantmentMinPowerCoefficients(enchantment));
enchantmentDesc.add("maxCost", generateEnchantmentMaxPowerCoefficients(enchantment));
enchantmentDesc.addProperty("treasureOnly", enchantment.isTreasure());
enchantmentDesc.addProperty("curse", enchantment.isCursed());
List<Enchantment> incompatibleEnchantments = registry.stream()
.filter(other -> !enchantment.isDifferent(other))
.filter(other -> other != enchantment).toList();
JsonArray excludes = new JsonArray();
for (Enchantment excludedEnchantment : incompatibleEnchantments) {
Identifier otherKey = registry.getId(excludedEnchantment);
excludes.add(Objects.requireNonNull(otherKey).getPath());
}
enchantmentDesc.add("exclude", excludes);
enchantmentDesc.addProperty("category", getEnchantmentTargetName(enchantment.type));
enchantmentDesc.addProperty("weight", enchantment.getWeight().getWeight());
enchantmentDesc.addProperty("tradeable", true); // the first non-tradeable enchant came in 1.16, soul speed
enchantmentDesc.addProperty("discoverable", true); // the first non-enchantable enchant came in 1.16, soul speed
return enchantmentDesc;
}
private static int getMaximumPower(Enchantment ench, int level) {
return ench.getMinimumPower(level) + 5;
}
@Override
public String getDataName() {
return "enchantments";
}
@Override
public JsonArray generateDataJson() {
JsonArray resultsArray = new JsonArray();
Registry<Enchantment> enchantmentRegistry = Registry.ENCHANTMENT;
enchantmentRegistry.stream()
.forEach(enchantment -> resultsArray.add(generateEnchantment(enchantmentRegistry, enchantment)));
return resultsArray;
}
}
@@ -0,0 +1,121 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.WaterCreatureEntity;
import net.minecraft.entity.mob.AmbientEntity;
import net.minecraft.entity.mob.HostileEntity;
import net.minecraft.entity.mob.MobEntity;
import net.minecraft.entity.passive.AnimalEntity;
import net.minecraft.entity.passive.PassiveEntity;
import net.minecraft.entity.projectile.ProjectileEntity;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.ParameterizedType;
import java.util.Objects;
public class EntitiesDataGenerator implements IDataGenerator {
public static JsonObject generateEntity(Registry<EntityType<?>> entityRegistry, EntityType<?> entityType) {
JsonObject entityDesc = new JsonObject();
Identifier registryKey = entityRegistry.getId(entityType);
int entityRawId = entityRegistry.getRawId(entityType);
entityDesc.addProperty("id", entityRawId);
entityDesc.addProperty("internalId", entityRawId);
entityDesc.addProperty("name", Objects.requireNonNull(registryKey).getPath());
entityDesc.addProperty("displayName", DGU.translateText(entityType.getTranslationKey()));
entityDesc.addProperty("width", entityType.getWidth());
entityDesc.addProperty("height", entityType.getHeight());
String entityTypeString = "UNKNOWN";
Entity entityObject = entityType.create(DGU.getWorld());
entityTypeString = entityObject != null ? getEntityTypeForClass(entityObject.getClass()) : "player";
entityDesc.addProperty("type", entityTypeString);
entityDesc.addProperty("category", getCategoryFrom(entityType));
return entityDesc;
}
private static String getCategoryFrom(@NotNull EntityType<?> entityType) {
if (entityType == EntityType.PLAYER) return "other"; // fail early for player entities
Class<? extends Entity> entityClazz = null;
try {
for (var field : EntityType.class.getFields())
if (entityType == field.get(EntityType.class))
entityClazz = (Class<? extends Entity>) ((ParameterizedType) TypeToken.get(field.getGenericType()).getType()).getActualTypeArguments()[0];
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if (entityClazz == null) throw new RuntimeException("Shouldn't be null...");
return switch (entityClazz.getPackageName()) {
case "net.minecraft.entity.decoration", "net.minecraft.entity.decoration.painting" -> "Immobile";
case "net.minecraft.entity.boss", "net.minecraft.entity.mob", "net.minecraft.entity.boss.dragon" ->
"Hostile mobs";
case "net.minecraft.entity.projectile", "net.minecraft.entity.thrown" -> "Projectiles";
case "net.minecraft.entity.passive" -> "Passive mobs";
case "net.minecraft.entity.vehicle" -> "Vehicles";
case "net.minecraft.entity" -> "other";
default -> throw new Error("Unexpected entity type: " + entityClazz.getPackageName());
};
}
//Honestly, both "type" and "category" fields in the schema and examples do not contain any useful information
//Since category is optional, I will just leave it out, and for type I will assume general entity classification
//by the Entity class hierarchy (which has some weirdness too by the way)
private static String getEntityTypeForClass(Class<? extends Entity> entityClass) {
//Top-level classifications
if (WaterCreatureEntity.class.isAssignableFrom(entityClass)) {
return "water_creature";
}
if (AnimalEntity.class.isAssignableFrom(entityClass)) {
return "animal";
}
if (HostileEntity.class.isAssignableFrom(entityClass)) {
return "hostile";
}
if (AmbientEntity.class.isAssignableFrom(entityClass)) {
return "ambient";
}
//Second level classifications. PathAwareEntity is not included because it
//doesn't really make much sense to categorize by it
if (PassiveEntity.class.isAssignableFrom(entityClass)) {
return "passive";
}
if (MobEntity.class.isAssignableFrom(entityClass)) {
return "mob";
}
//Other classifications only include living entities and projectiles. everything else is categorized as other
if (LivingEntity.class.isAssignableFrom(entityClass)) {
return "living";
}
if (ProjectileEntity.class.isAssignableFrom(entityClass)) {
return "projectile";
}
return "other";
}
@Override
public String getDataName() {
return "entities";
}
@Override
public JsonArray generateDataJson() {
JsonArray resultArray = new JsonArray();
Registry<EntityType<?>> entityTypeRegistry = Registry.ENTITY_TYPE;
entityTypeRegistry.forEach(entity -> resultArray.add(generateEntity(entityTypeRegistry, entity)));
return resultArray;
}
}
@@ -0,0 +1,50 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.item.Item;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import java.util.Objects;
public class FoodsDataGenerator implements IDataGenerator {
public static JsonObject generateFoodDescriptor(Registry<Item> registry, Item foodItem) {
JsonObject foodDesc = new JsonObject();
Identifier registryKey = registry.getId(foodItem);
foodDesc.addProperty("id", registry.getRawId(foodItem));
foodDesc.addProperty("name", Objects.requireNonNull(registryKey).getPath());
foodDesc.addProperty("stackSize", foodItem.getMaxAmount());
foodDesc.addProperty("displayName", DGU.translateText(foodItem.getTranslationKey()));
var foodSettings = Objects.requireNonNull(foodItem.getFoodSetting());
float foodPoints = foodSettings.getHunger();
float saturationRatio = foodSettings.getSaturationModifier() * 2.0F;
float saturation = foodPoints * saturationRatio;
foodDesc.addProperty("foodPoints", foodPoints);
foodDesc.addProperty("saturation", saturation);
foodDesc.addProperty("effectiveQuality", foodPoints + saturation);
foodDesc.addProperty("saturationRatio", saturationRatio);
return foodDesc;
}
@Override
public String getDataName() {
return "foods";
}
public JsonArray generateDataJson() {
JsonArray resultsArray = new JsonArray();
Registry<Item> itemRegistry = Registry.ITEM;
itemRegistry.stream()
.filter(Item::isFood)
.forEach(food -> resultsArray.add(generateFoodDescriptor(itemRegistry, food)));
return resultsArray;
}
}
@@ -0,0 +1,10 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonElement;
public interface IDataGenerator {
String getDataName();
JsonElement generateDataJson();
}
@@ -0,0 +1,25 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.block.enums.Instrument;
public class InstrumentsDataGenerator implements IDataGenerator {
@Override
public String getDataName() {
return "instruments";
}
@Override
public JsonElement generateDataJson() {
JsonArray array = new JsonArray();
for (Instrument instrument : Instrument.values()) {
JsonObject object = new JsonObject();
object.addProperty("id", instrument.ordinal());
object.addProperty("name", instrument.toSnakeCase());
array.add(object);
}
return array;
}
}
@@ -0,0 +1,82 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.enchantment.EnchantmentTarget;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class ItemsDataGenerator implements IDataGenerator {
private static List<Item> calculateItemsToRepairWith(Registry<Item> itemRegistry, Item sourceItem) {
ItemStack sourceItemStack = DGU.stackFor(sourceItem);
return itemRegistry.stream()
.filter(otherItem -> sourceItem.canRepair(sourceItemStack, DGU.stackFor(otherItem)))
.collect(Collectors.toList());
}
private static List<EnchantmentTarget> getApplicableEnchantmentTargets(Item sourceItem) {
return Arrays.stream(EnchantmentTarget.values())
.filter(target -> target.isAcceptableItem(sourceItem))
.collect(Collectors.toList());
}
public static JsonObject generateItem(Registry<Item> itemRegistry, Item item) {
JsonObject itemDesc = new JsonObject();
Identifier registryKey = itemRegistry.getId(item);
itemDesc.addProperty("id", itemRegistry.getRawId(item));
itemDesc.addProperty("name", Objects.requireNonNull(registryKey).getPath());
itemDesc.addProperty("displayName", DGU.translateText(item.getTranslationKey()));
itemDesc.addProperty("stackSize", item.getMaxAmount());
List<EnchantmentTarget> enchantmentTargets = getApplicableEnchantmentTargets(item);
JsonArray enchantCategoriesArray = new JsonArray();
for (EnchantmentTarget target : enchantmentTargets) {
enchantCategoriesArray.add(EnchantmentsDataGenerator.getEnchantmentTargetName(target));
}
if (enchantCategoriesArray.size() > 0) {
itemDesc.add("enchantCategories", enchantCategoriesArray);
}
if (item.canDamage()) {
List<Item> repairWithItems = calculateItemsToRepairWith(itemRegistry, item);
JsonArray fixedWithArray = new JsonArray();
for (Item repairWithItem : repairWithItems) {
Identifier repairWithName = itemRegistry.getId(repairWithItem);
fixedWithArray.add(Objects.requireNonNull(repairWithName).getPath());
}
if (fixedWithArray.size() > 0) {
itemDesc.add("repairWith", fixedWithArray);
}
int maxDurability = item.getMaxAmount();
itemDesc.addProperty("maxDurability", maxDurability);
}
return itemDesc;
}
@Override
public String getDataName() {
return "items";
}
@Override
public JsonArray generateDataJson() {
JsonArray resultArray = new JsonArray();
Registry<Item> itemRegistry = Registry.ITEM;
itemRegistry.stream().forEach(item -> resultArray.add(generateItem(itemRegistry, item)));
return resultArray;
}
}
@@ -0,0 +1,27 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
public class LanguageDataGenerator implements IDataGenerator {
@Override
public String getDataName() {
return "language";
}
@Override
public JsonElement generateDataJson() {
try {
InputStream inputStream = Objects.requireNonNull(this.getClass().getResourceAsStream("/assets/minecraft/lang/en_us.json"));
return new Gson().fromJson(new InputStreamReader(inputStream, StandardCharsets.UTF_8), JsonObject.class);
} catch (Exception ignored) {
}
throw new RuntimeException("Failed to generate language file");
}
}
@@ -0,0 +1,34 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.minecraft.particle.ParticleType;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import java.util.Objects;
public class ParticlesDataGenerator implements IDataGenerator {
public static JsonObject generateParticleType(Registry<ParticleType<?>> registry, ParticleType<?> particleType) {
JsonObject effectDesc = new JsonObject();
Identifier registryKey = registry.getId(particleType);
effectDesc.addProperty("id", registry.getRawId(particleType));
effectDesc.addProperty("name", Objects.requireNonNull(registryKey).getPath());
return effectDesc;
}
@Override
public String getDataName() {
return "particles";
}
@Override
public JsonArray generateDataJson() {
JsonArray resultsArray = new JsonArray();
Registry<ParticleType<?>> particleTypeRegistry = Registry.PARTICLE_TYPE;
particleTypeRegistry.forEach(particleType -> resultsArray.add(generateParticleType(particleTypeRegistry, particleType)));
return resultsArray;
}
}
@@ -0,0 +1,121 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import net.minecraft.item.Item;
import net.minecraft.util.registry.Registry;
public class RecipeDataGenerator implements IDataGenerator {
private static int getRawIdFor(Item item) {
return Registry.ITEM.getRawId(item);
}
@Override
public String getDataName() {
return "recipes";
}
@Override
public JsonElement generateDataJson() {
// JsonObject finalObj = new JsonObject();
// Multimap<Integer, JsonObject> recipes = ArrayListMultimap.create();
// for (Recipe<?> recipe : Objects.requireNonNull(DGU.getWorld()).getRecipeManager().values()) {
// if (recipe instanceof ShapedRecipe sr) {
// var ingredients = sr.getIngredients();
// List<Integer> ingr = new ArrayList<>();
// for (int i = 0; i < 9; i++) {
// if (i >= ingredients.size()) {
// ingr.add(-1);
// continue;
// }
// var stacks = ingredients.get(i);
//// var matching = stacks.getMatchingStacks();
//// if (matching.length == 0) {
//// ingr.add(-1);
//// } else {
//// ingr.add(getRawIdFor(matching[0].getItem()));
//// }
// }
// Lists.reverse(ingr);
//
// JsonArray inShape = new JsonArray();
//
// var iter = ingr.iterator();
// for (int y = 0; y < 3; y++) {
// var jsonRow = new JsonArray();
// int one = iter.next();
// int two = iter.next();
// int three = iter.next();
// if (y > 0 && one == -1 && two == -1 && three == -1) continue;
// jsonRow.add(one);
// jsonRow.add(two);
// jsonRow.add(three);
// inShape.add(jsonRow);
// }
//
// JsonObject finalRecipe = new JsonObject();
// finalRecipe.add("inShape", inShape);
//
// var resultObject = new JsonObject();
// resultObject.addProperty("id", getRawIdFor(sr.getOutput().getItem()));
// resultObject.addProperty("count", sr.getOutput().getCount());
// finalRecipe.add("result", resultObject);
//
// String id = ((Integer) getRawIdFor(sr.getOutput().getItem())).toString();
//
// if (!finalObj.has(id)) {
// finalObj.add(id, new JsonArray());
// }
// finalObj.get(id).getAsJsonArray().add(finalRecipe);
//// var input = new JsonArray();
//// var ingredients = sr.getIngredients().stream().toList();
//// for (int y = 0; y < sr.getHeight(); y++) {
//// var arr = new JsonArray();
//// for (int x = 0; x < sr.getWidth(); x++) {
//// if ((y*3)+x >= ingredients.size()) {
//// arr.add(JsonNull.INSTANCE);
//// continue;
//// }
//// var ingredient = ingredients.get((y*3)+x).getMatchingStacks(); // FIXME: fix when there are more than one matching stack
//// if (ingredient.length == 0) {
//// arr.add(JsonNull.INSTANCE);
//// } else {
//// arr.add(getRawIdFor(ingredient[0].getItem()));
//// }
//// }
//// input.add(arr);
//// }
//// var rootRecipeObject = new JsonObject();
//// rootRecipeObject.add("inShape", input);
//// var resultObject = new JsonObject();
//// resultObject.addProperty("id", getRawIdFor(sr.getOutput().getItem()));
//// resultObject.addProperty("count", sr.getOutput().getCount());
//// rootRecipeObject.add("result", resultObject);
//// recipes.put(getRawIdFor(sr.getOutput().getItem()), rootRecipeObject);
// } else if (recipe instanceof ShapelessRecipe sl) {
// var ingredients = new JsonArray();
// for (Ingredient ingredient : sl.getIngredients()) {
// if (ingredient.isEmpty()) continue;
//// ingredients.add(getRawIdFor(ingredient.getMatchingStacks()[0].getItem()));
// }
// var rootRecipeObject = new JsonObject();
// rootRecipeObject.add("ingredients", ingredients);
// var resultObject = new JsonObject();
// resultObject.addProperty("id", getRawIdFor(sl.getOutput().getItem()));
// resultObject.addProperty("count", sl.getOutput().getCount());
// rootRecipeObject.add("result", resultObject);
// recipes.put(getRawIdFor(sl.getOutput().getItem()), rootRecipeObject);
// }
// }
// recipes.forEach((a, b) -> {
// if (!finalObj.has(a.toString())) {
// finalObj.add(a.toString(), new JsonArray());
// }
// finalObj.get(a.toString()).getAsJsonArray().add(b);
// });
// return finalObj;
return JsonNull.INSTANCE;
}
}
@@ -0,0 +1,166 @@
package dev.u9g.minecraftdatagenerator.generators;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import dev.u9g.minecraftdatagenerator.ClientSideAnnoyances.FoliageColors;
import dev.u9g.minecraftdatagenerator.ClientSideAnnoyances.GrassColors;
import dev.u9g.minecraftdatagenerator.ClientSideAnnoyances.ServerSideRedstoneWireBlock;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.fabricmc.api.EnvType;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.block.RedstoneWireBlock;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.biome.Biome;
import java.util.*;
public class TintsDataGenerator implements IDataGenerator {
public static BiomeTintColors generateBiomeTintColors(Registry<Biome> biomeRegistry) {
BiomeTintColors colors = new BiomeTintColors();
biomeRegistry.forEach(biome -> {
int biomeGrassColor = GrassColors.getGrassColorAt(biome);
int biomeFoliageColor = FoliageColors.getFoliageColor(biome);
int biomeWaterColor = biome.getWaterColor();
colors.grassColoursMap.computeIfAbsent(biomeGrassColor, k -> new ArrayList<>()).add(biome);
colors.foliageColoursMap.computeIfAbsent(biomeFoliageColor, k -> new ArrayList<>()).add(biome);
colors.waterColourMap.computeIfAbsent(biomeWaterColor, k -> new ArrayList<>()).add(biome);
});
return colors;
}
public static Map<Integer, Integer> generateRedstoneTintColors() {
Map<Integer, Integer> resultColors = new HashMap<>();
for (int redstoneLevel : RedstoneWireBlock.POWER.getValues()) {
int color = ServerSideRedstoneWireBlock.getWireColor(redstoneLevel);
resultColors.put(redstoneLevel, color);
}
return resultColors;
}
private static int getBlockColor(Block block, BlockColors blockColors) {
return blockColors.getColor(block.getDefaultState(), DGU.getWorld(), BlockPos.ORIGIN);
}
public static Map<Block, Integer> generateConstantTintColors() {
Map<Block, Integer> resultColors = new HashMap<>();
BlockColors blockColors = BlockColors.create();
resultColors.put(Blocks.BIRCH_LEAVES, FoliageColors.getBirchColor());
resultColors.put(Blocks.SPRUCE_LEAVES, FoliageColors.getSpruceColor());
resultColors.put(Blocks.LILY_PAD, getBlockColor(Blocks.LILY_PAD, blockColors));
resultColors.put(Blocks.ATTACHED_MELON_STEM, getBlockColor(Blocks.ATTACHED_MELON_STEM, blockColors));
resultColors.put(Blocks.ATTACHED_PUMPKIN_STEM, getBlockColor(Blocks.ATTACHED_PUMPKIN_STEM, blockColors));
//not really constant, depend on the block age, but kinda have to be handled since textures are literally white without them
resultColors.put(Blocks.MELON_STEM, getBlockColor(Blocks.MELON_STEM, blockColors));
resultColors.put(Blocks.PUMPKIN_STEM, getBlockColor(Blocks.PUMPKIN_STEM, blockColors));
return resultColors;
}
private static JsonObject encodeBiomeColorMap(Registry<Biome> biomeRegistry, Map<Integer, List<Biome>> colorsMap) {
JsonArray resultColorsArray = new JsonArray();
for (var entry : colorsMap.entrySet()) {
JsonObject entryObject = new JsonObject();
JsonArray keysArray = new JsonArray();
for (Biome biome : entry.getValue()) {
Identifier registryKey = biomeRegistry.getId(biome);
keysArray.add(Objects.requireNonNull(registryKey).getPath());
}
entryObject.add("keys", keysArray);
entryObject.addProperty("color", entry.getKey());
resultColorsArray.add(entryObject);
}
JsonObject resultObject = new JsonObject();
resultObject.add("data", resultColorsArray);
return resultObject;
}
private static JsonObject encodeRedstoneColorMap(Map<Integer, Integer> colorsMap) {
JsonArray resultColorsArray = new JsonArray();
for (var entry : colorsMap.entrySet()) {
JsonObject entryObject = new JsonObject();
JsonArray keysArray = new JsonArray();
keysArray.add(entry.getKey());
entryObject.add("keys", keysArray);
entryObject.addProperty("color", entry.getValue());
resultColorsArray.add(entryObject);
}
JsonObject resultObject = new JsonObject();
resultObject.add("data", resultColorsArray);
return resultObject;
}
private static JsonObject encodeBlocksColorMap(Registry<Block> blockRegistry, Map<Block, Integer> colorsMap) {
JsonArray resultColorsArray = new JsonArray();
for (var entry : colorsMap.entrySet()) {
JsonObject entryObject = new JsonObject();
JsonArray keysArray = new JsonArray();
Identifier registryKey = blockRegistry.getId(entry.getKey());
keysArray.add(Objects.requireNonNull(registryKey).getPath());
entryObject.add("keys", keysArray);
entryObject.addProperty("color", entry.getValue());
resultColorsArray.add(entryObject);
}
JsonObject resultObject = new JsonObject();
resultObject.add("data", resultColorsArray);
return resultObject;
}
@Override
public String getDataName() {
return "tints";
}
@Override
public JsonObject generateDataJson() {
// DynamicRegistryManager registryManager = DynamicRegistryManager.create();
Registry<Biome> biomeRegistry = Registry.BIOME;
Registry<Block> blockRegistry = Registry.BLOCK;
BiomeTintColors biomeTintColors = generateBiomeTintColors(biomeRegistry);
Map<Integer, Integer> redstoneColors = generateRedstoneTintColors();
Map<Block, Integer> constantTintColors = Collections.emptyMap();
EnvType currentEnvironment = FabricLoader.getInstance().getEnvironmentType();
if (currentEnvironment == EnvType.CLIENT) {
constantTintColors = generateConstantTintColors();
}
JsonObject resultObject = new JsonObject();
resultObject.add("grass", encodeBiomeColorMap(biomeRegistry, biomeTintColors.grassColoursMap));
resultObject.add("foliage", encodeBiomeColorMap(biomeRegistry, biomeTintColors.foliageColoursMap));
resultObject.add("water", encodeBiomeColorMap(biomeRegistry, biomeTintColors.waterColourMap));
resultObject.add("redstone", encodeRedstoneColorMap(redstoneColors));
resultObject.add("constant", encodeBlocksColorMap(blockRegistry, constantTintColors));
return resultObject;
}
public static class BiomeTintColors {
final Map<Integer, List<Biome>> grassColoursMap = new HashMap<>();
final Map<Integer, List<Biome>> foliageColoursMap = new HashMap<>();
final Map<Integer, List<Biome>> waterColourMap = new HashMap<>();
}
}
@@ -0,0 +1,15 @@
package dev.u9g.minecraftdatagenerator.mixin;
import net.minecraft.server.dedicated.EulaReader;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(EulaReader.class)
public class EULAMixin {
@Inject(method = "isEulaAgreedTo()Z", at = @At("TAIL"), cancellable = true)
public void init(CallbackInfoReturnable<Boolean> cir) {
cir.setReturnValue(true);
}
}
@@ -0,0 +1,15 @@
package dev.u9g.minecraftdatagenerator.mixin;
import net.minecraft.block.Block;
import net.minecraft.item.MiningToolItem;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.Set;
@Mixin(MiningToolItem.class)
public interface MiningToolItemAccessor {
@Accessor
Set<Block> getEffectiveBlocks();
}
@@ -0,0 +1,28 @@
package dev.u9g.minecraftdatagenerator.mixin;
import dev.u9g.minecraftdatagenerator.Main;
import dev.u9g.minecraftdatagenerator.generators.DataGenerators;
import dev.u9g.minecraftdatagenerator.util.DGU;
import net.minecraft.MinecraftVersion;
import net.minecraft.server.dedicated.MinecraftDedicatedServer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.nio.file.Path;
import java.util.logging.Level;
@Mixin(MinecraftDedicatedServer.class)
public class ReadyMixin {
@Inject(method = "setupServer()Z", at = @At("TAIL"))
private void init(CallbackInfoReturnable<Boolean> cir) {
Main.LOGGER.log(Level.INFO, "Starting data generation!");
String versionName = MinecraftVersion.create().getName();
Path serverRootDirectory = DGU.getCurrentlyRunningServer().getRunDirectory().toPath().toAbsolutePath();
Path dataDumpDirectory = serverRootDirectory.resolve("minecraft-data").resolve(versionName);
DataGenerators.runDataGenerators(dataDumpDirectory);
Main.LOGGER.log(Level.INFO, "Done data generation!");
DGU.getCurrentlyRunningServer().stop(false);
}
}
@@ -0,0 +1,12 @@
package dev.u9g.minecraftdatagenerator.mixin;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectType;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(StatusEffect.class)
public interface StatusEffectAccessor {
@Accessor("type")
StatusEffectType type();
}
@@ -0,0 +1,69 @@
package dev.u9g.minecraftdatagenerator.util;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.resource.language.I18n;
import net.minecraft.item.ItemConvertible;
import net.minecraft.item.ItemStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.Language;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import org.jetbrains.annotations.NotNull;
public class DGU {
private static final Language language = Language.getInstance();
@Environment(EnvType.CLIENT)
private static MinecraftServer getCurrentlyRunningServerClient() {
return MinecraftClient.getInstance().getServer();
}
@SuppressWarnings("deprecation")
private static MinecraftServer getCurrentlyRunningServerDedicated() {
return (MinecraftServer) FabricLoader.getInstance().getGameInstance();
}
public static MinecraftServer getCurrentlyRunningServer() {
EnvType environmentType = FabricLoader.getInstance().getEnvironmentType();
if (environmentType == EnvType.CLIENT) {
return getCurrentlyRunningServerClient();
} else if (environmentType == EnvType.SERVER) {
return getCurrentlyRunningServerDedicated();
}
throw new UnsupportedOperationException();
}
@Environment(EnvType.CLIENT)
private static String translateTextClient(String translationKey) {
return I18n.translate(translationKey);
}
private static String translateTextFallback(String translationKey) {
try {
return language.translate(translationKey);
} catch (Exception ignored) {
}
throw new RuntimeException("Failed to translate: '" + translationKey + "'");
}
public static String translateText(String translationKey) {
EnvType environmentType = FabricLoader.getInstance().getEnvironmentType();
if (environmentType == EnvType.CLIENT) {
return translateTextClient(translationKey);
}
return translateTextFallback(translationKey);
}
@NotNull
public static World getWorld() {
return getCurrentlyRunningServer().getWorld(DimensionType.OVERWORLD);
}
public static ItemStack stackFor(ItemConvertible ic) {
return new ItemStack(ic);
}
}
@@ -0,0 +1,57 @@
//package dev.u9g.minecraftdatagenerator.util;
//
//import net.minecraft.block.BlockState;
//import net.minecraft.block.Blocks;
//import net.minecraft.block.entity.BlockEntity;
//import net.minecraft.fluid.FluidState;
//import net.minecraft.fluid.Fluids;
//import net.minecraft.util.math.BlockPos;
//import net.minecraft.world.LightType;
//import net.minecraft.world.biome.Biomes;
//import net.minecraft.world.chunk.light.LightingProvider;
//import org.jetbrains.annotations.Nullable;
//
//public enum EmptyRenderBlockView implements BlockRenderView {
// INSTANCE;
//
// @Nullable
// public BlockEntity getBlockEntity(BlockPos pos) {
// return null;
// }
//
// public BlockState getBlockState(BlockPos pos) {
// return Blocks.AIR.getDefaultState();
// }
//
// public FluidState getFluidState(BlockPos pos) {
// return Fluids.EMPTY.getDefaultState();
// }
//
// public int getBottomY() {
// return 0;
// }
//
// public int getHeight() {
// return 0;
// }
//
// @Override
// public LightingProvider getLightingProvider() {
// return null;
// }
//
// @Override
// public int getColor(BlockPos pos, ColorResolver colorResolver) {
// return colorResolver.getColor(Biomes.PLAINS, pos.getX(), pos.getY());
// }
//
// @Override
// public int getLightLevel(LightType type, BlockPos pos) {
// return type == LightType.SKY ? getMaxLightLevel() : 0;
// }
//
// @Override
// public int getBaseLightLevel(BlockPos pos, int ambientDarkness) {
// return ambientDarkness;
// }
//}
+27
View File
@@ -0,0 +1,27 @@
{
"schemaVersion": 1,
"id": "minecraft-data-generator",
"version": "${version}",
"name": "Minecraft Data Generator",
"description": "",
"authors": [
"Archengius",
"U9G"
],
"contact": {},
"license": "MIT",
"environment": "server",
"entrypoints": {
"main": [
"dev.u9g.minecraftdatagenerator.Main"
]
},
"mixins": [
"minecraft-data-generator.mixins.json"
],
"depends": {
"fabricloader": ">=0.13.3",
"fabric": "*",
"minecraft": "1.14"
}
}
@@ -0,0 +1,19 @@
{
"required": true,
"minVersion": "0.8",
"package": "dev.u9g.minecraftdatagenerator.mixin",
"compatibilityLevel": "JAVA_17",
"mixins": [
"MiningToolItemAccessor",
"ReadyMixin",
"StatusEffectAccessor"
],
"client": [
],
"injectors": {
"defaultRequire": 1
},
"server": [
"EULAMixin"
]
}