Datageneration/Loot Tables

From Forge Community Wiki

This page is under construction.

This page is incomplete, and needs more work. Feel free to edit and improve this page!

Loot Tables are not so polished like the other Providers. You need need to do some work to get them to a good state.

Preperation

First you would need a new Class that extend the LootTableProvider. In this class you would override the act and optionally getName Method. In the getName you just return the Name shown in the Logs. Also you should create a abstract Method which you would override in subclasses but this is not strickly needded. Also you need a Gson constant. You would create it like this private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); You should also save the DataGenerator for later use since you can't access from the LootTableProvider. Also you would need two Maps, one with the the Class witch is used to get the Lootable Resource Location in this example the Block and one the Loot Table Builder. The second Map consist of a ResourceLocation and the actual LootTable. Look at the Code for more info.

private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();

  protected final Map<Block, LootTable.Builder> lootTables = new HashMap<>();
  public static Map<ResourceLocation, LootTable> tables = new HashMap<>();
  protected final DataGenerator generator;

Also you would need a Function to save the Tables

private void writeTables(DirectoryCache cache, Map<ResourceLocation, LootTable> tables) {
    Path outputFolder = this.generator.getOutputFolder();
    tables.forEach((key, lootTable) -> {
      Path path = outputFolder.resolve("data/" + key.getNamespace() + "/loot_tables/" + key.getPath() + ".json");
      try {
        IDataProvider.save(GSON, cache, LootTableManager.serialize(lootTable), path);
      } catch (IOException e) {
        LOGGER.error("Couldn't write loot table {}", path, (Object) e);
      }
    });
  }

For the writeTables method you would need to convert the First Map to the second map, for this we need to iterate over the first map.

lootTables.forEach(blockBuilderMap -> {
      for (Map.Entry<Block, LootTable.Builder> entry : blockBuilderMap.entrySet()) {
        tables.put(entry.getKey().getLootTable(), entry.getValue().build());
      }
    });

in the act Method you would then first call the Method where you create the tables or just create them in there (if you do you can ignore the next section), then you would convert the Tables and at last you would save the loottables.

The actual Class for Lootables

Here's an example Lootprovider class. The class is abstract and will be extended by the actual lootprovider class. This is however, optional. The class could also be used directly.

public abstract class BaseLootTableProvider extends LootTableProvider {

    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
    private static final Logger LOGGER = LogManager.getLogger();

    protected final Map<Block, LootTable.Builder> lootTables = new HashMap<>();
    private final DataGenerator generator;

    public BaseLootTableProvider(DataGenerator dataGeneratorIn) {
        super(dataGeneratorIn);
        this.generator = dataGeneratorIn;
    }

    protected abstract void addTables();
    
    @Override
    public void run(DirectoryCache cache) {
        addTables();

        Map<ResourceLocation, LootTable> tables = new HashMap<>();
        for (Map.Entry<Block, LootTable.Builder> entry : lootTables.entrySet()) {
            tables.put(entry.getKey().getLootTable(), entry.getValue().build());
        }
        writeTables(cache, tables);
    }

    private void writeTables(DirectoryCache cache, Map<ResourceLocation, LootTable> tables) {
        Path outputFolder = this.generator.getOutputFolder();
        tables.forEach((key, lootTable) -> {
            Path path = outputFolder.resolve("data/" + key.getNamespace() + "/loot_tables/" + key.getPath() + ".json");
            try {
                IDataProvider.save(GSON, cache, LootTableManager.serialize(lootTable), path);
            } catch (IOException e) {
                LOGGER.error("Couldn't write loot table {}", path, (Object) e);

            }
        });
    }

    @Override
    public String getName() {
        return "Example LootTables";
    }
}

Another class (Optional)

Create a new class that extends from the Class you created in the Section above and override the abstract function in there you can begin to create your Lootables.

public class LootTables extends BaseLootTableProvider{

    @Override
    protected void addTables() {
	lootTables.put(BLOCK, LootTable.Builder);
	}
}

The LootPool Builder

This is where you actually make a loottable (this is an explanation for a block loottable). If you have multiple blocks with similar loottables, making a general method could be a good idea. The Method should return a LootTable.Builder. This builder can be made by using the LootPool.lootPool() method, but you still need to add attributes. You need a name for the pool, the amount you get and also "what" you get. The "what" can modified using functions and/or conditions (see https://minecraft.fandom.com/wiki/Loot_table for possible vanilla funtions and conditions). After having made the builder, you return LootTable.lootTable().withPool(builder). A example of a "shulkerbox-like" block, copying its name, inventory and "energy" data to the block and restoring its contents.

protected LootTable.Builder createTable(String name, Block block) {
        LootPool.Builder builder = LootPool.lootPool()
                .name(name)
                .setRolls(ConstantRange.exactly(1))
                .add(ItemLootEntry.lootTableItem(block)
                        .apply(CopyName.copyName(CopyName.Source.BLOCK_ENTITY))
                        .apply(CopyNbt.copyData(CopyNbt.Source.BLOCK_ENTITY)
                                .copy("inv", "BlockEntityTag.inv", CopyNbt.Action.REPLACE)
                                .copy("energy", "BlockEntityTag.energy", CopyNbt.Action.REPLACE))
                        .apply(SetContents.setContents()
                                .withEntry(DynamicLootEntry.dynamicEntry(new ResourceLocation("minecraft", "contents"))))
                );
        return LootTable.lootTable().withPool(builder).setParamSet(LootParameterSets.BLOCK);
    }

Thanks and creddits to McJty with his amazing tutorials: https://wiki.mcjty.eu/modding/index.php?title=YouTube-Tutorials and https://github.com/McJty/YouTubeModding14/tree/1.16/src/main/java/com/mcjty/mytutorial/datagen