Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 39 additions & 3 deletions docs/xml-machines.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
An installed mod can declare a machine with optional item, energy and fluid storage in
`src/main/resources/mmdlib/machine/<path>.xml`. Its ID is `<modid>:<path>`.
MMDLib registers the block, item, block-entity type, declared recipe type and
serializer, capabilities, screen and JEI catalyst. All instances use the shared
`DefinedMachineBlock` and `DefinedMachineEntity`; no machine-specific Java class
is needed.
serializer, capabilities, screen and JEI catalyst. By default, the XML block creates a
`DefinedMachineEntity`. A mod can supply a subclass for an individual machine.

Definitions load at startup on both sides. Changing a machine's storage, screen,
appearance or recipe generator configuration requires a restart. Recipe JSON and
Expand All @@ -19,6 +18,43 @@ configuration or a slot's role/limit is detected even if the screen looks identi
XML attribute order, comments, whitespace and local source paths do not affect the CRC.
Different definitions are rejected before constructing the client menu.

## Porting an existing block entity

Keep the machine XML at the existing block and block-entity registry ID when
those IDs match. Let MMDLib own the registrations. In your mod constructor on
both sides, register the entity constructor under the concrete XML machine ID:

```java
MachineContent.registerEntityFactory(ResourceLocation.parse("example:boiler"),
BoilerEntity::new);
```

Extend `DefinedMachineEntity` and forward its five constructor arguments
(`BlockEntityType<?>`, `BlockPos`, `BlockState`, `MachineDefinition`, and the
primary `MachineRecipeType`, which can be null) to `super`. Both placement and
world loading use this constructor. The XML definition still supplies the
machine's storage, processors, capabilities and screen.

For legacy save keys, override `migrateMachineData`. It receives the persistent
root tag before storage and processors restore their state. For example, a mod
whose old boiler stored FE in a numeric `BoilerFE` field could use:

```java
@Override
protected CompoundTag migrateMachineData(CompoundTag tag, HolderLookup.Provider registries) {
if (tag.contains("energy") || !tag.contains("BoilerFE", Tag.TAG_ANY_NUMERIC))
return tag;
var converted = tag.copy();
converted.putLong("energy", tag.getLong("BoilerFE"));
converted.remove("BoilerFE");
return converted;
}
```

The next save writes the current format. Client update tags bypass migration.
If an old save uses a different block or block-entity registry ID, the mod must
also arrange for that ID to resolve before Minecraft can load the entity.

## SimpleCrusher

The playable example is
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package zone.moddev.mc.companion.test;

import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.gametest.framework.GameTest;
import net.minecraft.gametest.framework.GameTestHelper;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;

import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.event.lifecycle.FMLConstructModEvent;
import net.neoforged.neoforge.gametest.GameTestHolder;
import net.neoforged.neoforge.gametest.PrefixGameTestTemplate;

import zone.moddev.mc.companion.CompanionMod;
import zone.moddev.mc.lib.machine.definition.MachineDefinition;
import zone.moddev.mc.lib.machine.neoforge.DefinedMachineEntity;
import zone.moddev.mc.lib.machine.neoforge.MachineContent;
import zone.moddev.mc.lib.machine.recipe.MachineRecipeType;

@EventBusSubscriber(modid = CompanionMod.ID, bus = EventBusSubscriber.Bus.MOD)
@GameTestHolder("mmdlib_porting")
@PrefixGameTestTemplate(false)
public final class LegacyMachineEntityTests {
@SubscribeEvent
public static void register(FMLConstructModEvent event) {
MachineContent.registerEntityFactory(
CompanionMod.id("test/upgraded_fluid_still"), LegacyStill::new);
}

public static final class LegacyStill extends DefinedMachineEntity {
private int migrations;

public LegacyStill(BlockEntityType<?> type, BlockPos pos,
BlockState state, MachineDefinition definition,
MachineRecipeType recipes) {
super(type, pos, state, definition, recipes);
}

@Override
protected CompoundTag migrateMachineData(CompoundTag tag,
HolderLookup.Provider registries) {
if (tag.contains("energy")
|| !tag.contains("StillFE", Tag.TAG_ANY_NUMERIC))
return tag;
migrations++;
var converted = tag.copy();
converted.putLong("energy", tag.getLong("StillFE"));
converted.remove("StillFE");
return converted;
}
}

@GameTest(template = "empty")
public static void legacyEnergySurvivesAnXmlMachineRoundTrip(
GameTestHelper h) {
var placed = PortingHooksTests.place(h, "test/upgraded_fluid_still");
h.assertTrue(placed instanceof LegacyStill,
"Placement uses the registered subclass");
var registries = h.getLevel().registryAccess();
var pos = placed.getBlockPos();
var state = placed.getBlockState();
var legacy = new CompoundTag();
legacy.putString("id", "mmdlib_companion:test/upgraded_fluid_still");
legacy.putInt("StillFE", 625);
var imported = (LegacyStill) BlockEntity.loadStatic(pos, state, legacy,
registries);
h.assertTrue(
imported != null && imported.migrations == 1
&& imported.energy.stored() == 625,
"World load translates the legacy value before XML storage reads it");
var saved = imported.saveWithFullMetadata(registries);
h.assertTrue(
saved.getLong("energy") == 625 && !saved.contains("StillFE"),
"Saving writes current XML storage");
var restored = (LegacyStill) BlockEntity.loadStatic(pos, state, saved,
registries);
h.assertTrue(
restored != null && restored.migrations == 0
&& restored.energy.stored() == 625,
"Current saves retain the imported energy without a second migration");
var update = restored.getUpdateTag(registries);
update.putInt("StillFE", 999);
restored.loadWithComponents(update, registries);
h.assertTrue(
restored.migrations == 0 && restored.energy.stored() == 625,
"Client updates bypass the persistence hook");
h.succeed();
}
}
15 changes: 15 additions & 0 deletions src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtOps;
import net.minecraft.nbt.Tag;
Expand Down Expand Up @@ -280,6 +282,16 @@ protected void loadMachineData(CompoundTag tag,
HolderLookup.Provider registries) {
}

/**
* Translates a persistent root tag before shared storage and features load.
* Return the original for current saves or a converted copy for legacy
* saves. Client synchronization bypasses this hook.
*/
protected CompoundTag migrateMachineData(CompoundTag tag,
HolderLookup.Provider registries) {
return tag;
}

/**
* Maps old numeric item/tank indices before storage and processor
* restoration. Stable IDs bypass it.
Expand Down Expand Up @@ -353,6 +365,9 @@ protected final void loadAdditional(CompoundTag tag,
loadClientData(tag.getCompound(CLIENT_DATA), registries);
return;
}
tag = Objects.requireNonNull(migrateMachineData(tag, registries),
() -> "migrateMachineData must return a tag for "
+ BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(getType()));
super.loadAdditional(tag, registries);
var inventory = configuredInventory();
if (inventory != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,11 @@
import zone.moddev.mc.lib.machine.presentation.VisualVariables;
import zone.moddev.mc.lib.machine.recipe.MachineRecipeType;

/** Shared runtime assembled from XML. There is no per-machine Java subclass. */
public final class DefinedMachineEntity extends BaseMachine
/**
* Shared XML runtime. Mods can supply a subclass through
* {@link MachineContent#registerEntityFactory}.
*/
public class DefinedMachineEntity extends BaseMachine
implements zone.moddev.mc.lib.machine.feature.ProcessorMachine,
zone.moddev.mc.lib.machine.presentation.VisualizerStyle.Provider {
public final MachineDefinition definition;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
import java.util.Objects;
import java.util.TreeMap;

import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Fluids;

import net.neoforged.bus.api.IEventBus;
Expand Down Expand Up @@ -52,6 +54,43 @@ public final class MachineContent {
private static final Map<ResourceLocation, DefinedMachineItem> items = new TreeMap<>();
private static final Map<ResourceLocation, BlockEntityType<DefinedMachineEntity>> entities = new TreeMap<>();

private static final Map<ResourceLocation, EntityFactory> entityFactories = new TreeMap<>();
private static boolean entityFactoriesFrozen;

@FunctionalInterface
public interface EntityFactory {
/**
* Construct the XML entity with the supplied arguments. Recipes may be
* null.
*/
DefinedMachineEntity create(BlockEntityType<?> type, BlockPos pos,
BlockState state, MachineDefinition definition,
@org.jetbrains.annotations.Nullable MachineRecipeType recipes);
}

/**
* Selects the block entity constructor for a concrete XML machine. Register
* during mod construction, before machine definitions are loaded.
*/
public static synchronized void registerEntityFactory(ResourceLocation id,
EntityFactory factory) {
if (entityFactoriesFrozen)
throw new IllegalStateException(
"XML machine entity factories are frozen: " + id);
if (entityFactories.putIfAbsent(Objects.requireNonNull(id),
Objects.requireNonNull(factory)) != null)
throw new IllegalArgumentException(
"Duplicate XML machine entity factory: " + id);
}

private static synchronized void freezeEntityFactories() {
for (var id : entityFactories.keySet())
if (!definitions.containsKey(id))
throw new IllegalArgumentException(
"No concrete XML machine for entity factory: " + id);
entityFactoriesFrozen = true;
}

private MachineContent() {
}

Expand Down Expand Up @@ -139,6 +178,7 @@ private static void checkEvent(MachineDefinition machine, String attribute,

public static void load(List<SourceRoot> roots) {
definitions = MachineDefinitions.load(roots);
freezeEntityFactories();
var declarations = new TreeMap<ResourceLocation, MachineDefinition.RecipeType>();
for (var machine : definitions.values())
machine.processingTypes().stream()
Expand Down Expand Up @@ -220,13 +260,24 @@ private static void registries(RegisterEvent event) {
});
event.register(Registries.BLOCK_ENTITY_TYPE,
helper -> definitions.forEach((id, definition) -> {
var type = BlockEntityType.Builder.of(
(pos, state) -> new DefinedMachineEntity(entities.get(id),
pos, state, definition,
definition.processingType()
.map(recipe -> recipeType(recipe.id()))
.orElse(null)),
blocks.get(id)).build(null);
var factory = entityFactories.getOrDefault(id,
DefinedMachineEntity::new);
var primary = definition.processingType()
.map(recipe -> recipeType(recipe.id())).orElse(null);
var type = BlockEntityType.Builder
.<DefinedMachineEntity>of((pos, state) -> {
var registered = entityType(id);
var entity = factory.create(registered, pos, state,
definition, primary);
if (entity == null || entity.getType() != registered
|| !entity.getBlockPos().equals(pos)
|| entity.getBlockState() != state
|| entity.definition != definition)
throw new IllegalStateException(
"XML machine factory must use the supplied type, position, state and definition: "
+ id);
return entity;
}, blocks.get(id)).build(null);
helper.register(id, type);
entities.put(id, type);
}));
Expand Down
Loading