diff --git a/docs/xml-machines.md b/docs/xml-machines.md index 5fd8ef51..986fa375 100644 --- a/docs/xml-machines.md +++ b/docs/xml-machines.md @@ -1639,3 +1639,196 @@ emit world light. Default is false. Use transparency around glowing pixels. MMDLib expands the declaration into conditional model parts, reusing tracking snapshots and model invalidation when the selected frame changes. No per-machine renderer or full-face variants are needed. Inventory models keep the base casing. + +## Allowed facing and placement + +`` is the default. +`facing="all"` allows all six directions. A space-separated list allows any +nonempty subset, such as `up`, `down`, `up down`, or `north east up`. +`placement-facing="away-from-player"` reverses the placement preference. +Placement picks the nearest allowed look direction (opposite the look direction +for toward-player); a fixed direction always wins. Rotation/mirroring retains +its old direction when the transformed front is forbidden. Loaded states outside +the declared set normalize to north if allowed, otherwise the first allowed +Minecraft direction (down, up, north, south, west, east). + +Vertical fronts use north as local top. Shapes, models, displays and working +areas share that orientation. Range upgrades expand the area's local plane. +The companion's Facing Demo machines illustrate all, away, up-only, down-only, +vertical and asymmetric sets; the existing crushers show horizontal defaults. + +## Dynamic storage admission + +Real slots accept `filter-class="your.ModAdmission"` or +`filter-processor="processor_id"`, alongside existing `item-tag` restrictions. +Tanks accept the same hooks and `fluid-tag="namespace:tag"` alongside exact `fluid`. +All applicable rules must pass. Recipe admission still accepts the union of linked +recipe inputs. Rules do not delete contents when tags, recipes or configuration change. + +Implement `StorageAdmission` with `acceptsItem(ProcessorMachine, memberId, ItemStack)` +and/or `acceptsFluid(ProcessorMachine, memberId, FluidAmount)`. Unimplemented kinds +refuse insertion. A class needs a public no-argument constructor and is instantiated +per machine; a processor binding names a custom processor implementing that interface. +The member ID is the stable storage slot/tank ID, such as `fuel/0`. Values are detached; +the host can have a null level during construction/loading. Queries must not mutate +storage and must handle simulated operations. Read live config/recipes or invalidate +any private caches on reload. These hooks govern external admission; machine-product +transactions retain their existing internal insertion semantics. + +The companion Admission Demo shows furnace fuel, vanilla smelting, item/fluid tags, +a mod-config-selected fluid tag and recipe-based fluid admission. Its custom processor +supplies rules without a recipe processor. `AdmissionDemo.fuelTag` illustrates the +mod-owned configuration value; the fixture itself is an inspection/storage machine. + +## Typed processor storage + +`ProcessorMachine.resources()` exposes the host's existing `MachineInventory`. +Use `items("group")`, `fluids("group")` and `energy("group")` for typed access; +missing or wrong-kind names fail explicitly. Indexes are local to that group. +Use `try (var tx = resources.begin())` and commit only when every operation succeeds. +Closing without commit rolls all changes back. These are internal processing +operations: they honor reservations but bypass external roles and item admission. +Use copied `peek` values for inspection. Declaration prototypes have no live host. + +The companion Porting Workshop converts one cobblestone and 25 mB water into stone +using one transaction. A blocked output leaves both inputs unchanged. Its processor +uses only the common host API, with no cast to the XML block entity. + +## Placement callbacks + +Custom processors can override `placementFacing(BlockPlaceContext, Direction)`. +This pure preference hook runs on the declaration prototype (no live host), on +both sides. Its result must be allowed by the machine's `facing` declaration. +`placed(MachinePlacement)` runs on live processors once after successful server +item placement and portable payload restoration. `StoredProcessor` subclasses override +`onPlaced(MachinePlacement)` inside the supplied state-update scope. It receives the final state, +position, nullable placer, level and a copied placing stack. It does not run when +loading a chunk or when a placement event cancels. Direct world `setBlock` calls +are not item placement and do not initialize ownership. + +The Porting Workshop records the placing player's UUID/team in processor state. +Sneak placement chooses the clicked face; ordinary placement faces the player. + +## Comparator readout + +`` selects one existing +`IRedstoneOutput` descriptor by its stable ID. The source is sampled together +with per-face outputs, once per selected source per tick. Comparator readout is +block-wide and independent of Emit faces and their inversion. Unknown source +IDs fail during definition loading with the source file and line. Custom processors +contribute descriptors through `redstoneOutputs()`; their IDs must be available +on the host-free schema prototype. Loading reads the IDs without sampling their +live value suppliers. No second provider is needed. +The Porting Workshop exposes output fullness to both the redstone drawer and +comparators, including comparators reading through an adjacent solid block. + +## Several processors per machine + +Declare repeated `` elements with unique stable IDs. They tick +in declaration order and persist separately. Recipe and custom processors can run +together. Repeated `` declarations provide the types used by recipe +lanes. The first processor is the default primary unless one declares `primary="true"`; +portable or secondary-use machines with several processors require an explicit primary. +Primary selection controls item/placement behavior, keyless processor controls, +and the no-argument progress/time/pause getters. It does not change tick order or +explicitly indexed lane bindings. + +Recipe lanes can declare `bindings="input=left_input output=left_output"` to map +recipe group names to the machine's physical groups. A binding list defines the +lane's view; `energy=energy` is included automatically when available. Without a +list, all resource groups retain their names. Custom processors use named host +resources directly. Shared targets retain common reservation/transaction identity. +Recipe admission unions participating lanes by physical slot/tank, then intersects +that union with authored admission rules. `filter-inputs` names recipe-side aliases; +omitting it filters all bound input groups. + +Generated progress displays and default processor buttons address each lane. +Per-lane sounds, visuals, statistics and persistence use the same stable IDs. +JEI registers every used recipe type and routes transfer to its bound inputs. +Default selection by legacy keyless runtime APIs remains first-in-registration-order; +use explicit processor keys when choosing a particular lane. + +Inheritance merges repeated processors/types by ID. For compatibility, when both +parent and child declare exactly one processor (or one recipe type), that child +still overrides the parent singleton even when renaming it. To append to such a +parent, repeat its existing ID alongside the new declaration. + +The companion Parallel Workshop runs two crushing lanes plus a custom water-powered +Charge Pump (one mB supplies 100 FE). The Shared Workshop rebinds the second lane +to the first lane's input to demonstrate contention without duplicate products. + + +### Java recipe cycle callbacks + +`on-start` and `on-finish` use the ordinary `MaterialExtensions.GLOBAL.events()` +registry. Mods can register Java callbacks with `MaterialEventTypes.MACHINE_CYCLE_START` +and `MACHINE_CYCLE_FINISH`; CraftTweaker is optional. `MachineCycle.processor()` +identifies the lane. Callbacks fire for every actual transition, including multiple +transitions in one accelerated tick. Loading or resuming a cycle does not replay +its start, and interruption/failed output does not report a finish. A finish sees +the committed recipe resources. Java-created recipe processors can use +`RecipeProcessor.cycleCallbacks(start, finish)` directly. + +The companion Parallel Workshop registers both Java callbacks in `CompanionMod` +and records their counts and lane identity in its charge pump's saved state. + + +### Processor-owned energy + +An energy declaration uses the built-in buffer by default (`provider="builtin"`). +To give ownership to a custom processor, set `provider` to its stable processor ID: + +```xml + + + + +``` + +The processor implements `ProcessorEnergy.createEnergyStorage(capacity, inputRate, +outputRate)` and returns its authoritative `EnergyBuffer` (or subclass). This runs +once during construction, before host resources are available. The same store +backs recipe transactions, energy gauges, statistics, visual values, saving and +the library's single NeoForge capability registration. Do not separately register +another energy capability or save a second copy. A subclass backed by another +storage must implement the buffer's transactional checkpoint, consumption, +telemetry and serialization contracts consistently. + +`energyMode(side)` adds live restrictions to ordinary side configuration; null +means unsided access. Cached views query it on every transfer, so temporary +unavailability can return `IoMode.DISABLED` without swapping storage or invalidating +capabilities. The source itself stays stable for the machine's lifetime. + +Custom sources default to `capacitors="false"`; their automatic capacitor socket +is omitted and explicit incompatible sockets are rejected. Opt in only when the +source supports the standard capacity/rate upgrades. Built-in buffers retain the +existing capacitor behavior. Machines without an energy declaration expose no +energy capability. The companion Battery Workshop reuses the two recipe lanes +and supplies their energy through its BatteryBank processor, including live side +restrictions and capacitor support. + + +### Per-processor operating energy + +`` adds a nonnegative FE cost per successful +work step. It defaults to zero and requires the machine's `energy` resource. +Recipe lanes add it to the recipe's scheduled energy; different machines or lanes +can reuse the same recipe with different operating costs. Gearbox-accelerated +steps each pay their cost. Starting, idle, paused, held, stalled and blocked steps +do not charge. Recipe and operating charges commit together: insufficient power +leaves both energy and progress unchanged. For a costed recipe, a blocked final +step also rolls back that step's charges and progress until completion succeeds. + +Custom `StoredProcessor` implementations use the same option. The cost is reserved +before `process` runs and retained only when `performedWork(result)` returns true +(default: `RUNNING`). Override that hook if a successful completion reports `IDLE`. +Use resource transactions for custom work; return a failure status without committing +partial resource mutations. On failure, the reserved energy and its telemetry roll +back. The custom processor sees the remaining energy after its operating reservation. +Java machines can configure `operatingCost(amount)` directly on either processor type. + +The companion Paid Workshop runs the Parallel Workshop's unchanged recipes at 5 +and 9 FE/step overhead, alongside a custom charge pump costing 3 FE/step. Its focused +tests cover combined-cost starvation, accelerated work, pause/idle, failed final +output, successful completion and custom-processor refunds. diff --git a/scripts/companion.gradle b/scripts/companion.gradle index f2755cc7..d8305233 100644 --- a/scripts/companion.gradle +++ b/scripts/companion.gradle @@ -18,6 +18,9 @@ sourceSets { } } +// Unit definition tests load the real companion XML and its mod-owned processors. +sourceSets.test.runtimeClasspath += sourceSets.companion.output + neoForge.addModdingDependenciesTo(sourceSets.companion) neoForge.addModdingDependenciesTo(sourceSets.companionTest) neoForge.addModdingDependenciesTo(sourceSets.companionServerTest) @@ -94,7 +97,7 @@ neoForge { gameDirectory = layout.buildDirectory.dir('companion-gametest') sourceSet = sourceSets.companionServerTest loadedMods = [neoForge.mods.named(mod_id).get(), neoForge.mods.mmdlib_companion_test] - systemProperty 'neoforge.enabledGameTestNamespaces', 'mmdlib_companion' + systemProperty 'neoforge.enabledGameTestNamespaces', project.hasProperty('portingHooksOnly') ? 'mmdlib_porting' : 'mmdlib_companion,mmdlib_porting' } multiblockClientSmoke { client() diff --git a/src/companion/java/zone/moddev/mc/companion/AdmissionDemo.java b/src/companion/java/zone/moddev/mc/companion/AdmissionDemo.java new file mode 100644 index 00000000..840eb5c3 --- /dev/null +++ b/src/companion/java/zone/moddev/mc/companion/AdmissionDemo.java @@ -0,0 +1,63 @@ +package zone.moddev.mc.companion; + +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.item.crafting.SingleRecipeInput; + +import zone.moddev.mc.lib.machine.feature.ProcessorMachine; +import zone.moddev.mc.lib.machine.feature.ProcessorState; +import zone.moddev.mc.lib.machine.feature.StorageAdmission; +import zone.moddev.mc.lib.machine.feature.StoredProcessor; +import zone.moddev.mc.lib.machine.ingredient.FluidAmount; +import zone.moddev.mc.lib.machine.ingredient.MachineIngredient; +import zone.moddev.mc.lib.machine.recipe.MachineRecipeEntry; + +/** A custom processor can also supply live insertion rules without casts. */ +public final class AdmissionDemo extends StoredProcessor + implements StorageAdmission { + /** A consuming mod can supply this value from its own reloadable config. */ + public static volatile ResourceLocation fuelTag = ResourceLocation + .parse("minecraft:lava"); + + @Override + public boolean acceptsItem(ProcessorMachine host, String member, + ItemStack stack) { + if (member.startsWith("fuel/")) + return stack.getBurnTime(RecipeType.SMELTING) > 0; + return host.level() != null + && host.level().getRecipeManager().getRecipeFor(RecipeType.SMELTING, + new SingleRecipeInput(stack), host.level()).isPresent(); + } + + @Override + public boolean acceptsFluid(ProcessorMachine host, String member, + FluidAmount fluid) { + if (member.equals("oil")) + return fluid.fluid().is(TagKey.create(Registries.FLUID, fuelTag)); + if (host.level() == null) + return false; + return host.level().getRecipeManager().getRecipes().stream().anyMatch( + holder -> holder.value() instanceof MachineRecipeEntry entry + && entry.type().id().equals( + ResourceLocation.parse("mmdlib_companion:lava_smelting")) + && entry.recipe().inputs() + .getOrDefault("fuel", java.util.List.of()).stream() + .anyMatch( + part -> part instanceof MachineIngredient.FluidPart input + && input.fluids().contains(fluid.fluid()))); + } + + @Override + public boolean canStart(ProcessorState state, ProcessorMachine context) { + return false; + } + + @Override + public ProcessState process(ProcessorState state, ProcessorMachine context, + int ticks) { + return ProcessState.IDLE; + } +} diff --git a/src/companion/java/zone/moddev/mc/companion/BatteryBank.java b/src/companion/java/zone/moddev/mc/companion/BatteryBank.java new file mode 100644 index 00000000..0e000b06 --- /dev/null +++ b/src/companion/java/zone/moddev/mc/companion/BatteryBank.java @@ -0,0 +1,43 @@ +package zone.moddev.mc.companion; + +import net.minecraft.core.Direction; + +import zone.moddev.mc.lib.api.capabilities.EnergyBuffer; +import zone.moddev.mc.lib.api.capabilities.IoMode; +import zone.moddev.mc.lib.machine.feature.ProcessorEnergy; +import zone.moddev.mc.lib.machine.feature.ProcessorMachine; +import zone.moddev.mc.lib.machine.feature.ProcessorState; +import zone.moddev.mc.lib.machine.feature.StoredProcessor; + +/** + * Processor-owned energy, with side policy applied to cached capability views. + */ +public final class BatteryBank extends StoredProcessor + implements ProcessorEnergy { + private EnergyBuffer buffer; + public EnergyBuffer createEnergyStorage(long capacity, long input, + long output) { + if (buffer != null) + throw new IllegalStateException("Already bound"); + return buffer = new EnergyBuffer(capacity, input, output); + } + public EnergyBuffer buffer() { + return buffer; + } + public IoMode energyMode(Direction side) { + if (paused()) + return IoMode.DISABLED; + return side == null + ? IoMode.BOTH + : side == Direction.UP + ? IoMode.INPUT + : side == Direction.DOWN ? IoMode.OUTPUT : IoMode.DISABLED; + } + public boolean canStart(ProcessorState state, ProcessorMachine machine) { + return false; + } + public ProcessState process(ProcessorState state, ProcessorMachine machine, + int ticks) { + return ProcessState.IDLE; + } +} diff --git a/src/companion/java/zone/moddev/mc/companion/ChargePump.java b/src/companion/java/zone/moddev/mc/companion/ChargePump.java new file mode 100644 index 00000000..325c38f9 --- /dev/null +++ b/src/companion/java/zone/moddev/mc/companion/ChargePump.java @@ -0,0 +1,45 @@ +package zone.moddev.mc.companion; + +import zone.moddev.mc.lib.machine.feature.ProcessorMachine; +import zone.moddev.mc.lib.machine.feature.ProcessorState; +import zone.moddev.mc.lib.machine.feature.StoredProcessor; + +/** Example charging alongside recipe lanes: one mB water supplies 100 FE. */ +public final class ChargePump extends StoredProcessor { + private final ProcessorState.Key starts = variables.define( + "starts", com.mojang.serialization.Codec.INT, 0, + java.util.function.UnaryOperator.identity(), false, true); + private final ProcessorState.Key finishes = variables.define( + "finishes", com.mojang.serialization.Codec.INT, 0, + java.util.function.UnaryOperator.identity(), false, true); + private final ProcessorState.Key lastLane = variables.define( + "last_lane", com.mojang.serialization.Codec.STRING, "", + java.util.function.UnaryOperator.identity(), false, true); + + public void recordCycle(String lane, boolean finished) { + variables.update(() -> { + var counter = finished ? finishes : starts; + variables.set(counter, variables.get(counter) + 1); + variables.set(lastLane, lane); + }); + } + + @Override + public boolean canStart(ProcessorState state, ProcessorMachine host) { + return host.resources().fluids("coolant").free(0) > 0; + } + + @Override + public ProcessState process(ProcessorState state, ProcessorMachine host, + int ticks) { + var resources = host.resources(); + try (var tx = resources.begin()) { + if (resources.energy("energy").insert(100, tx) != 100) + return ProcessState.BLOCKED; + if (resources.fluids("coolant").extract(0, 1, tx) != 1) + return ProcessState.IDLE; + tx.commit(); + } + return ProcessState.RUNNING; + } +} diff --git a/src/companion/java/zone/moddev/mc/companion/CompanionMod.java b/src/companion/java/zone/moddev/mc/companion/CompanionMod.java index 2e427027..a6e89e97 100644 --- a/src/companion/java/zone/moddev/mc/companion/CompanionMod.java +++ b/src/companion/java/zone/moddev/mc/companion/CompanionMod.java @@ -80,6 +80,12 @@ public final class CompanionMod { } public CompanionMod(IEventBus bus) { + MaterialExtensions.GLOBAL.events().registerCallback( + id("workshop_start"), MaterialEventTypes.MACHINE_CYCLE_START, + event -> recordWorkshopCycle(event, false)); + MaterialExtensions.GLOBAL.events().registerCallback( + id("workshop_finish"), MaterialEventTypes.MACHINE_CYCLE_FINISH, + event -> recordWorkshopCycle(event, true)); MultiblockDemo.register(bus); CompanionWidgets.register(); CompanionAddons.register(bus); @@ -100,6 +106,16 @@ public CompanionMod(IEventBus bus) { }); } + private static void recordWorkshopCycle( + zone.moddev.mc.lib.api.MaterialEventContexts.MachineCycle event, + boolean finished) { + if (event + .machine() instanceof zone.moddev.mc.lib.machine.neoforge.DefinedMachineEntity machine) + machine.features.findProcessor("charge", ChargePump.class) + .ifPresent( + pump -> pump.recordCycle(event.processor(), finished)); + } + private static void capabilities(RegisterCapabilitiesEvent event) { CompanionAddons.capabilities(event); for (var machine : MACHINES) { diff --git a/src/companion/java/zone/moddev/mc/companion/WorkshopProcessor.java b/src/companion/java/zone/moddev/mc/companion/WorkshopProcessor.java new file mode 100644 index 00000000..240113f4 --- /dev/null +++ b/src/companion/java/zone/moddev/mc/companion/WorkshopProcessor.java @@ -0,0 +1,90 @@ +package zone.moddev.mc.companion; + +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.material.Fluids; + +import zone.moddev.mc.lib.machine.feature.ProcessorMachine; +import zone.moddev.mc.lib.machine.feature.ProcessorState; +import zone.moddev.mc.lib.machine.feature.StoredProcessor; + +/** A small transactional consumer of typed host resources; no entity cast. */ +public final class WorkshopProcessor extends StoredProcessor + implements zone.moddev.mc.lib.api.redstone.IRedstoneOutput { + private final ProcessorState.Key placements = variables.define( + "placements", com.mojang.serialization.Codec.INT, 0, + java.util.function.UnaryOperator.identity(), false, true); + private final ProcessorState.Key owner = variables.define("owner", + com.mojang.serialization.Codec.STRING, "", + java.util.function.UnaryOperator.identity(), false, true); + private final ProcessorState.Key team = variables.define("team", + com.mojang.serialization.Codec.STRING, "", + java.util.function.UnaryOperator.identity(), false, true); + + @Override + public java.util.List redstoneOutputs() { + return java.util.List + .of(new zone.moddev.mc.lib.api.redstone.RedstoneOutput( + "workshop/output", + net.minecraft.network.chat.Component.literal("Workshop output"), + net.minecraft.network.chat.Component + .literal("Stone output fullness"), + 0xc07040, java.util.Optional.empty(), + () -> machine == null + ? 0 + : zone.moddev.mc.lib.api.redstone.RedstoneControl.level( + machine.resources().items("output").peek(0).getCount() + / 64.0))); + } + + @Override + public net.minecraft.core.Direction placementFacing( + net.minecraft.world.item.context.BlockPlaceContext context, + net.minecraft.core.Direction suggested) { + // Sneak placement demonstrates a consumer choosing the clicked face. + return context.getPlayer() != null + && context.getPlayer().isShiftKeyDown() + ? context.getClickedFace() + : suggested; + } + + @Override + protected void onPlaced( + zone.moddev.mc.lib.machine.feature.MachinePlacement placement) { + variables.set(placements, variables.get(placements) + 1); + var player = placement.placer(); + variables.set(owner, player == null ? "" : player.getUUID().toString()); + variables.set(team, + player == null || player.getTeam() == null + ? "" + : player.getTeam().getName()); + } + + @Override + public boolean canStart(ProcessorState state, ProcessorMachine host) { + var resources = host.resources(); + return resources.items("input").peek(0).is(Items.COBBLESTONE) + && resources.items("input").free(0) > 0 + && resources.fluids("water").peek(0).fluid().value() == Fluids.WATER + && resources.fluids("water").free(0) >= 25; + } + + @Override + public ProcessState process(ProcessorState state, ProcessorMachine host, + int ticks) { + var resources = host.resources(); + for (int step = 0; step < ticks; step++) { + if (!canStart(state, host)) + return ProcessState.IDLE; + try (var tx = resources.begin()) { + if (resources.items("input").extract(0, 1, tx) != 1 + || resources.fluids("water").extract(0, 25, tx) != 25 + || resources.items("output") + .insert(new ItemStack(Items.STONE), tx) != 1) + return ProcessState.BLOCKED; + tx.commit(); + } + } + return ProcessState.RUNNING; + } +} diff --git a/src/companion/resources/META-INF/neoforge.mods.toml b/src/companion/resources/META-INF/neoforge.mods.toml index 4497db97..43a44da0 100644 --- a/src/companion/resources/META-INF/neoforge.mods.toml +++ b/src/companion/resources/META-INF/neoforge.mods.toml @@ -6,7 +6,7 @@ license="LGPL-2.1-only" modId="mmdlib_companion" version="${file.jarVersion}" displayName="MMDLib Machine Companion" -description='''Four playable examples of MMDLib's recipe processors and reservations.''' +description='''Playable examples of MMDLib machines, recipes, storage, automation, placement and processor extensions. Open each machine's Info panel for its purpose and a hands-on check.''' [[dependencies.mmdlib_companion]] modId="neoforge" diff --git a/src/companion/resources/assets/mmdlib_companion/lang/en_us.json b/src/companion/resources/assets/mmdlib_companion/lang/en_us.json index cdeb6ad6..ce6eb94f 100644 --- a/src/companion/resources/assets/mmdlib_companion/lang/en_us.json +++ b/src/companion/resources/assets/mmdlib_companion/lang/en_us.json @@ -19,7 +19,7 @@ "screen.mmdlib_companion.lane_b": "Lane B", "screen.mmdlib_companion.single": "One iron in, one gold out", "screen.mmdlib_companion.power": "Powers adjacent blocks on enabled sides", - "mmdlib_companion:creative_power.info": "*Creative Power Source*\n\nSupplies up to 1,000 FE per enabled face each tick.\n\nUse the side configuration panel to enable or disable outputs. Statistics shows the measured output rate.", + "mmdlib_companion:creative_power.info": "*Creative Power Source*\n\nTests automatic energy export, per-face side settings and transfer statistics. Its buffer refills every tick without fuel.\n\nPlace it beside a powered companion machine and enable the connecting output face. It supplies up to 1,000 FE per enabled face per tick, subject to the receiving machine's input rules.\n\nDisable one face and confirm that receiver stops charging while other enabled faces continue. Check Statistics for the actual transferred energy.", "screen.mmdlib_companion.rate": "1,000 FE per face per tick", "block.mmdlib_companion.crusher": "Crusher", "block.mmdlib_companion.transmuter": "Iron-to-Gold Converter", @@ -45,9 +45,9 @@ "screen.mmdlib_companion.recipes.tip": "Show crushing recipes in JEI, when installed.", "screen.mmdlib_companion.tank.tip": "Water or lava: {value} / {max} mB. Left-click to fill; right-click to drain with a fluid container.", "screen.mmdlib_companion.tank.refused": "Cannot transfer fluid. The tank holds water or lava, one type at a time, up to 4 buckets.", - "mmdlib_companion:crusher.info": "*Crusher*\n\nCrush ore into raw materials, or stone into gravel and sand.\n\nPlace a power source beside the machine. Pause to release reserved items.\n\nThe left tank holds 4 buckets of water or lava for display. Left-click the gauge with a fluid container on the cursor to fill it; right-click to drain it, or right-click the block with a bucket. Empty the tank before changing fluids. Crushing does not use the fluid.", - "mmdlib_companion:transmuter.info": "*Iron to gold*\n\nInsert one iron ingot. The same slot holds the gold when the cycle finishes.\n\nSupply power from an adjacent block. Pause to release the input.", - "mmdlib_companion:dual_crusher.info": "*Dual crusher*\n\nTwo lanes share the input and output slots. Each lane reserves its own items and space.\n\nPause either lane independently to release its share.", + "mmdlib_companion:crusher.info": "*Crusher*\n\nTests Java recipe processing, item reservations, a custom progress dial and editable screen controls. Supply FE and insert cobblestone to make gravel, gravel to make sand, or a supported ore to make raw material. The Recipes button opens JEI when installed.\n\nClick the progress dial or processor button to pause and release reserved items. Resume to reclaim them. Settings lets you rename the machine, set its energy reserve and pause its lane; a reserve above the current charge holds processing.\n\nThe separate 4,000 mB tank tests fluid-container interactions and accepts water or lava, one fluid at a time. Left-click its gauge with a filled container to fill it; right-click with an empty container to drain it. You can also use a bucket on the block. Crushing does not consume this fluid.", + "mmdlib_companion:transmuter.info": "*Iron-to-Gold Converter*\n\nTests consuming an input and placing its product in the same physical slot, including reservations and a one-item slot limit.\n\nSupply 4,000 FE and insert one iron ingot. After 200 work ticks, one gold ingot replaces it in that slot. Remove the gold before starting another cycle.\n\nPause during processing to release the input, then resume. With insufficient power, progress should stall without consuming the ingot.", + "mmdlib_companion:dual_crusher.info": "*Dual Crusher*\n\nTests two Java recipe lanes competing for the same input stack, output space and energy buffer.\n\nSupply FE and insert several cobblestone or gravel items. Both lanes can advance when enough unreserved input and output space remain. Each lane has its own progress display and pause button.\n\nTry a single input item: only one lane may claim it, and it must produce only one result. Pause one lane to release its reservations while the other keeps working. A full output must prevent new work without consuming input.", "item.mmdlib_companion.mechanical_puller": "Mechanical Puller", "item.mmdlib_companion.mechanical_pusher": "Mechanical Pusher", "item.mmdlib_companion.input_pump": "Input Pump", @@ -59,7 +59,7 @@ "item.mmdlib_companion.tag_filter": "Tag Filter", "item.mmdlib_companion.fluid_filter": "Fluid Filter", "block.mmdlib_companion.logistics": "Logistics Workbench", - "mmdlib_companion:logistics.info": "Seven independent inventories. Install a module, enable a side, and configure its optional filter.", + "mmdlib_companion:logistics.info": "*Logistics Workbench*\n\nTests automation modules, filters and independent side settings for seven resource groups: item input, item output, two input tanks, two output tanks and energy. Recipe processing is disabled.\n\nPlace a chest or tank beside it. Open the side configuration, select a resource group, enable the connecting face and install a suitable puller, pusher, pump or relay. Powered modules need FE; filters can restrict which items or fluids move.\n\nConfigure different groups and faces independently, then check that only the intended resources transfer. Try an allow-list or deny-list filter and compare accepted and rejected contents. The workbench does not move input contents to its outputs by itself.", "screen.mmdlib_companion.group.input": "Item input", "screen.mmdlib_companion.group.output": "Item output", "screen.mmdlib_companion.group.energy": "Energy", @@ -76,5 +76,19 @@ "screen.mmdlib_companion.structure": "Status in Info tab", "screen.mmdlib_companion.operations": "Active ticks", "screen.mmdlib_companion.operations.tip": "Active ticks: {value}", - "screen.mmdlib_companion.multiblock.info": "Keep the block above the middle part clear. Breaking any part dismantles this machine." + "screen.mmdlib_companion.multiblock.info": "*Multiblock Test Bench*\n\nTests automatic placement of a three-block structure, shared resource ports, structure validation and dismantling. Place the bench with room for its two attached parts and keep the block above the middle part clear.\n\nThe far end is the socket for items, fluids and energy; its ports access the controller's displayed stores. The middle belt is not a resource port. Try opening the screen through a part and transferring resources through the socket.\n\nWhile the structure is valid, Active ticks increases and the energy store gains 1 FE per tick. Obstruct the required clearance and check the status: work must stop until the structure is valid again.\n\nBreaking any member dismantles the structure. Stored items and remaining fluid or energy must be recovered rather than duplicated or silently lost.", + "mmdlib_companion:simple_crusher.info": "*Simple Crusher*\n\nTests a machine defined entirely in XML: generated inventory and progress controls, recipe admission, ore recipe generation, side settings and shared upgrades.\n\nSupply FE and insert cobblestone or gravel. Each produces gravel or sand respectively in 100 work ticks for 2,000 FE. Supported ore tags also generate ore-to-ingot recipes; JEI shows the recipes available in this pack.\n\nUnrelated items should be refused at the input. Fill both output slots to check that blocked work leaves resources intact. Try the pause button, gearbox upgrades for faster work and capacitor upgrades for a larger energy buffer.", + "mmdlib_companion:simple_lava_furnace.info": "*Simple Lava Furnace*\n\nTests fluid-powered recipes, a mod-provided smelting recipe generator, and recipe filters on both item and fluid inputs. It uses lava instead of FE.\n\nFill the 8,000 mB fuel tank with lava and insert an item with a smelting recipe, such as raw iron. The recipe reserves its item, lava and output space, then produces the smelted result when the cycle completes.\n\nWater and unrelated items should be refused. Pause to release reservations, or fill the output to check that a new cycle cannot consume resources. JEI shows the generated recipes and their lava amounts.", + "mmdlib_companion:admission_demo.info": "*Admission Demo*\n\nTests storage admission without a recipe processor. This machine only stores accepted contents; it does not burn, smelt or distill anything.\n\nTry coal in Burnable fuel, raw iron in Smeltable items and logs in Logs only. Stone should be refused by all three. The fuel slot uses a processor rule, the smelting slot uses a separate Java rule, and the log slot uses an item tag.\n\nThe Water tag tank accepts water. Configured fuel tag uses the lava tag by default. Recipe fluid accepts lava when the companion lava-smelting recipes are available. Water should be refused by those last two tanks.\n\nTry manual insertion, hoppers or pipes, and fluid containers. The same restrictions should apply. The developer check changes the supplied fuel tag at runtime and verifies that fluid already stored is preserved.", + "mmdlib_companion:porting_workshop.info": "*Porting Workshop*\n\nTests a custom processor using typed item/fluid transactions, six-way placement, placer ownership and comparator output from an existing redstone source. It needs no FE.\n\nInsert cobblestone and water: each work step converts one cobblestone and 25 mB of water into one stone. Fill the stone output and confirm that blocked work consumes neither input nor water.\n\nNormal placement faces toward you. Sneak while placing to choose the clicked face instead. Successful placement records the player's identity and team; loading the machine must not count as another placement.\n\nAttach a comparator, directly or through a solid block. Its strength follows stone output fullness: empty is 0 and a full stack is 15. No emitting redstone face needs to be enabled.", + "mmdlib_companion:parallel_workshop.info": "*Parallel Workshop*\n\nTests two XML recipe lanes running alongside a custom water-powered charge pump. Each lane has separate input/output slots and a pause control, while all three processors share one energy store.\n\nAdd water, or supply FE externally. Insert cobblestone in the left input and gravel in the right input. Expect gravel on the left and sand on the right. Each recipe takes 100 work ticks and 2,000 FE; the pump converts 1 mB of water into 100 FE per successful step.\n\nPause one recipe lane and confirm the other lane and pump can continue. Try gearboxes to accelerate work and reload the world to check saved state.\n\nJava start/finish callbacks also record cycle counts and the last lane in the charge pump's saved state; they do not require CraftTweaker.", + "mmdlib_companion:shared_workshop.info": "*Shared Workshop*\n\nTests two XML recipe lanes sharing the same physical input while keeping separate outputs. Both lanes use the left input; the visible right input is intentionally unused.\n\nAdd water to run the charge pump, or supply FE externally. Put one cobblestone in the left input: only one lane may reserve it and only one gravel should be produced. Add a larger stack to let both lanes work.\n\nThe left lane ticks first and can claim the last available item. Pause it to let the right lane claim shared input. Output space and reserved inputs must never be counted twice. This example also binds a second name to the same energy store.", + "mmdlib_companion:battery_workshop.info": "*Battery Workshop*\n\nTests energy supplied by a custom BatteryBank processor. The gauge, recipe lanes, charging pump, automation and saved energy must all use the same store. It starts with 200,000 FE capacity and supports capacitor upgrades.\n\nPut a Creative Power Source above it, or add water for the charge pump. Feed cobblestone or gravel to either recipe lane and watch the shared energy gauge fall as recipes work.\n\nFor manual play, charge it from above; this fixture currently exposes an input-only energy group to sided automation. Horizontal connections must refuse transfers. The developer checks also exercise unsided extraction. Pausing the battery processor disables direct energy connections, including existing ones, without pausing the recipe lanes or water pump.\n\nReload the world and check that the stored charge is preserved. It must not reveal a second, separate recipe buffer.", + "mmdlib_companion:paid_workshop.info": "*Paid Workshop*\n\nTests per-processor operating energy on the Parallel Workshop's unchanged recipes. Supply FE first, or seed at least 3 FE before relying on the water pump: the pump cannot start from an empty buffer.\n\nAdd water and cobblestone or gravel to the lane inputs. Each 100-step recipe still costs 2,000 FE, plus 5 FE per successful left-lane step or 9 FE per right-lane step: 2,500 FE left and 2,900 FE right per completed cycle.\n\nThe pump pays 3 FE before producing 100 FE from 1 mB of water, for a net gain of 97 FE. Pause the pump when comparing recipe costs in the gauge or Statistics.\n\nGearbox-accelerated steps each pay their cost. Idle, paused, held, stalled or blocked work must not charge operating energy. If a combined recipe and operating charge cannot be paid, energy and progress stay unchanged.", + "mmdlib_companion:facing_all.info": "*Facing Demo: All Directions*\n\nTests allowed facing directions and placement preference. Allows all six directions and faces toward the placer.\n\nPlace it while looking horizontally, up and down. The dispenser face should point back toward you.\n\nThe dispenser texture marks the front and gold marks the local top. For an upward or downward front, the gold top points north. Use the storage slot and side settings to check that resource faces follow the orientation. This is a storage-only example with no recipes or power requirement.", + "mmdlib_companion:facing_away.info": "*Facing Demo: Away from Player*\n\nTests allowed facing directions and placement preference. Allows all six directions and faces away from the placer.\n\nPlace it while looking horizontally, up and down. The dispenser face should point along your look direction, opposite to the All Directions demo.\n\nThe dispenser texture marks the front and gold marks the local top. For an upward or downward front, the gold top points north. Use the storage slot and side settings to check that resource faces follow the orientation. This is a storage-only example with no recipes or power requirement.", + "mmdlib_companion:facing_up.info": "*Facing Demo: Up Only*\n\nTests allowed facing directions and placement preference. Allows only an upward-facing front.\n\nPlace it from different sides and viewing angles. The dispenser face must always point up, regardless of where you stand.\n\nThe dispenser texture marks the front and gold marks the local top. For an upward or downward front, the gold top points north. Use the storage slot and side settings to check that resource faces follow the orientation. This is a storage-only example with no recipes or power requirement.", + "mmdlib_companion:facing_down.info": "*Facing Demo: Down Only*\n\nTests allowed facing directions and placement preference. Allows only a downward-facing front.\n\nPlace it from different sides and viewing angles. The dispenser face must always point down, regardless of where you stand.\n\nThe dispenser texture marks the front and gold marks the local top. For an upward or downward front, the gold top points north. Use the storage slot and side settings to check that resource faces follow the orientation. This is a storage-only example with no recipes or power requirement.", + "mmdlib_companion:facing_vertical.info": "*Facing Demo: Up or Down*\n\nTests allowed facing directions and placement preference. Allows only upward and downward fronts, preferring the direction toward the placer.\n\nLook down while placing to get an upward-facing front, or look up to get a downward-facing front. Horizontal fronts must never be selected.\n\nThe dispenser texture marks the front and gold marks the local top. For an upward or downward front, the gold top points north. Use the storage slot and side settings to check that resource faces follow the orientation. This is a storage-only example with no recipes or power requirement.", + "mmdlib_companion:facing_asymmetric.info": "*Facing Demo: North, East or Up*\n\nTests allowed facing directions and placement preference. Allows only north, east and up, preferring the allowed direction nearest to the placer.\n\nPlace it from several sides, including ones that would normally choose south, west or down. The front must always remain north, east or up.\n\nThe dispenser texture marks the front and gold marks the local top. For an upward or downward front, the gold top points north. Use the storage slot and side settings to check that resource faces follow the orientation. This is a storage-only example with no recipes or power requirement." } diff --git a/src/companion/resources/mmdlib/machine/admission_demo.xml b/src/companion/resources/mmdlib/machine/admission_demo.xml new file mode 100644 index 00000000..c3d2a51a --- /dev/null +++ b/src/companion/resources/mmdlib/machine/admission_demo.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + diff --git a/src/companion/resources/mmdlib/machine/battery_workshop.xml b/src/companion/resources/mmdlib/machine/battery_workshop.xml new file mode 100644 index 00000000..98b7e642 --- /dev/null +++ b/src/companion/resources/mmdlib/machine/battery_workshop.xml @@ -0,0 +1,5 @@ + + + + diff --git a/src/companion/resources/mmdlib/machine/facing_all.xml b/src/companion/resources/mmdlib/machine/facing_all.xml new file mode 100644 index 00000000..6747c3a0 --- /dev/null +++ b/src/companion/resources/mmdlib/machine/facing_all.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/src/companion/resources/mmdlib/machine/facing_asymmetric.xml b/src/companion/resources/mmdlib/machine/facing_asymmetric.xml new file mode 100644 index 00000000..69303e9f --- /dev/null +++ b/src/companion/resources/mmdlib/machine/facing_asymmetric.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/src/companion/resources/mmdlib/machine/facing_away.xml b/src/companion/resources/mmdlib/machine/facing_away.xml new file mode 100644 index 00000000..76c58fa4 --- /dev/null +++ b/src/companion/resources/mmdlib/machine/facing_away.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/src/companion/resources/mmdlib/machine/facing_down.xml b/src/companion/resources/mmdlib/machine/facing_down.xml new file mode 100644 index 00000000..8d32d077 --- /dev/null +++ b/src/companion/resources/mmdlib/machine/facing_down.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/src/companion/resources/mmdlib/machine/facing_up.xml b/src/companion/resources/mmdlib/machine/facing_up.xml new file mode 100644 index 00000000..216468e3 --- /dev/null +++ b/src/companion/resources/mmdlib/machine/facing_up.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/src/companion/resources/mmdlib/machine/facing_vertical.xml b/src/companion/resources/mmdlib/machine/facing_vertical.xml new file mode 100644 index 00000000..00d2436c --- /dev/null +++ b/src/companion/resources/mmdlib/machine/facing_vertical.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/src/companion/resources/mmdlib/machine/paid_workshop.xml b/src/companion/resources/mmdlib/machine/paid_workshop.xml new file mode 100644 index 00000000..07450b82 --- /dev/null +++ b/src/companion/resources/mmdlib/machine/paid_workshop.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/src/companion/resources/mmdlib/machine/parallel_workshop.xml b/src/companion/resources/mmdlib/machine/parallel_workshop.xml new file mode 100644 index 00000000..75f35495 --- /dev/null +++ b/src/companion/resources/mmdlib/machine/parallel_workshop.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + diff --git a/src/companion/resources/mmdlib/machine/porting_workshop.xml b/src/companion/resources/mmdlib/machine/porting_workshop.xml new file mode 100644 index 00000000..5f28dcd1 --- /dev/null +++ b/src/companion/resources/mmdlib/machine/porting_workshop.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + diff --git a/src/companion/resources/mmdlib/machine/shared_workshop.xml b/src/companion/resources/mmdlib/machine/shared_workshop.xml new file mode 100644 index 00000000..1c51a6e1 --- /dev/null +++ b/src/companion/resources/mmdlib/machine/shared_workshop.xml @@ -0,0 +1,4 @@ + + + diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/MachineRecipeLoadingTests.java b/src/companionTest/java/zone/moddev/mc/companion/test/MachineRecipeLoadingTests.java index 2d36d968..5839f923 100644 --- a/src/companionTest/java/zone/moddev/mc/companion/test/MachineRecipeLoadingTests.java +++ b/src/companionTest/java/zone/moddev/mc/companion/test/MachineRecipeLoadingTests.java @@ -27,6 +27,7 @@ import zone.moddev.mc.lib.machine.feature.RecipeProcessor; import zone.moddev.mc.lib.machine.neoforge.DefinedMachineEntity; import zone.moddev.mc.lib.machine.neoforge.GeneratedMachineRecipes; +import zone.moddev.mc.lib.machine.neoforge.MachineContent; import zone.moddev.mc.lib.machine.neoforge.MachineRecipeTypes; import zone.moddev.mc.lib.machine.recipe.MachineRecipe; import zone.moddev.mc.lib.machine.recipe.MachineRecipeEntry; @@ -114,11 +115,16 @@ public static void authoredRecipesValidateGroupsAndResourceKinds( load(h, read(h, "mmdlib_companion:bad_recipe", json)); throw new AssertionError("Invalid authored recipe accepted"); } catch (IllegalArgumentException expected) { + // Several companion machines now share this recipe type; the + // first invalid consumer need not be the original crusher. require( - expected.getMessage() - .contains("mmdlib_companion:bad_recipe") - && expected.getMessage().contains(MACHINE.toString()), - "Error identifies both recipe and machine"); + MachineContent.definitions().values().stream() + .filter(machine -> machine.processes(TYPE)) + .anyMatch(machine -> expected.getMessage() + .startsWith("Recipe mmdlib_companion:bad_recipe: " + + machine.id() + ": ")), + "Error identifies both recipe and an affected machine: " + + expected.getMessage()); } } require(load(h, read(h, "mmdlib_companion:valid_recipe", SINGLE)) diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/PortingHooksTests.java b/src/companionTest/java/zone/moddev/mc/companion/test/PortingHooksTests.java new file mode 100644 index 00000000..b124cf09 --- /dev/null +++ b/src/companionTest/java/zone/moddev/mc/companion/test/PortingHooksTests.java @@ -0,0 +1,491 @@ +package zone.moddev.mc.companion.test; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.gametest.framework.GameTest; +import net.minecraft.gametest.framework.GameTestHelper; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.material.Fluids; + +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler.FluidAction; +import net.neoforged.neoforge.gametest.GameTestHolder; +import net.neoforged.neoforge.gametest.PrefixGameTestTemplate; + +import zone.moddev.mc.companion.AdmissionDemo; +import zone.moddev.mc.lib.machine.neoforge.DefinedMachineEntity; + +@GameTestHolder("mmdlib_porting") +@PrefixGameTestTemplate(false) +public final class PortingHooksTests { + static DefinedMachineEntity place(GameTestHelper h, String name) { + var pos = h.absolutePos(new BlockPos(2, 2, 2)); + h.getLevel().setBlock(pos, + BuiltInRegistries.BLOCK + .get(ResourceLocation.parse("mmdlib_companion:" + name)) + .defaultBlockState(), + 3); + return (DefinedMachineEntity) h.getLevel().getBlockEntity(pos); + } + + @GameTest(template = "empty") + public static void loadingRepairsInvalidFacingWithoutReplacingTheEntity( + GameTestHelper h) { + var machine = place(h, "facing_up"); + machine.items.insertItem(0, new ItemStack(Items.DIAMOND, 3), false); + var property = net.minecraft.world.level.block.state.properties.BlockStateProperties.FACING; + h.getLevel().setBlock(machine.getBlockPos(), + machine.getBlockState().setValue(property, + net.minecraft.core.Direction.DOWN), + net.minecraft.world.level.block.Block.UPDATE_CLIENTS); + machine.onLoad(); + h.assertTrue(machine.facing() == net.minecraft.core.Direction.UP, + "Load repairs disallowed facing"); + h.assertTrue( + h.getLevel().getBlockEntity(machine.getBlockPos()) == machine + && machine.items.getStackInSlot(0).getCount() == 3, + "Facing repair preserves entity identity and inventory"); + h.succeed(); + } + + @GameTest(template = "empty") + public static void keylessBindingsSelectTheDeclaredPrimary( + GameTestHelper h) { + var machine = place(h, "parallel_workshop"); + var left = machine.features.processor("left").orElseThrow(); + var right = machine.features.processor("right").orElseThrow(); + machine.energy.setStored(10000); + machine.items.inventory("left_input").insertItem(0, + new ItemStack(Items.COBBLESTONE), false); + machine.serverTick(); + left.tick(machine.features, 4); + h.assertTrue(left.progress() > 0 && right.progress() == 0, + "Primary recipe has distinct progress"); + h.assertTrue( + machine.getProgress() == left.progress() + && machine.getTime() == left.time(), + "Keyless recipe getters use primary"); + h.assertTrue( + machine.features.findProcessor(java.util.Optional.empty()) + .orElseThrow() == left, + "Keyless controls select primary even after a custom processor"); + left.setPaused(true); + h.assertTrue(machine.getPaused(), + "Keyless pause uses primary, not the preceding charge processor"); + h.assertTrue( + machine.getProgress(0) == 0 + && machine.getProgress(1) == left.progress(), + "Indexed bindings keep declaration order"); + machine.features.primaryProcessor("right"); + h.assertTrue( + machine.getProgress() == right.progress() + && machine.getTime() == right.time() && !machine.getPaused(), + "Selecting the second recipe lane changes every keyless getter"); + h.succeed(); + } + + @GameTest(template = "empty") + public static void operatingCostIsAtomicAndTracksAcceleratedWork( + GameTestHelper h) { + var machine = place(h, "paid_workshop"); + machine.energy.setStored(10000); + machine.items.inventory("left_input").insertItem(0, + new ItemStack(Items.COBBLESTONE), false); + machine.serverTick(); + var lane = machine.features.processor("left").orElseThrow(); + h.assertTrue(lane.progress() == 0 && machine.energy.stored() == 10000, + "Starting is free"); + machine.energy.setStored(24); + machine.serverTick(); + h.assertTrue( + lane.progress() == 0 && machine.energy.stored() == 24 + && machine.energy.used().signum() == 0, + "Combined 20 recipe plus 5 operating FE cannot partially debit"); + machine.energy.setStored(75); + lane.tick(machine.features, 2); + h.assertTrue( + lane.progress() == 2 && machine.energy.stored() == 25 + && machine.energy.used().intValue() == 50, + "Accelerated steps each pay recipe plus operating cost"); + lane.setPaused(true); + lane.tick(machine.features, 2); + h.assertTrue(machine.energy.stored() == 25 && lane.progress() == 2, + "Pause is free"); + lane.setPaused(false); + machine.energy.setStored(10000); + lane.tick(machine.features, 98); + h.assertTrue( + machine.energy.stored() == 7550 + && machine.energy.used().intValue() == 2500, + "Full cycle costs recipe 2000 plus operating 500"); + h.assertTrue(machine.items.inventory("left_output").getStackInSlot(0) + .is(Items.GRAVEL), "Cycle completed"); + lane.tick(machine.features, 5); + h.assertTrue(machine.energy.stored() == 7550, "Idle steps are free"); + h.succeed(); + } + + @GameTest(template = "empty") + public static void blockedLastStepRollsBackOperatingAndRecipeEnergy( + GameTestHelper h) { + var machine = place(h, "paid_workshop"); + machine.energy.setStored(10000); + machine.items.inventory("left_input").insertItem(0, + new ItemStack(Items.COBBLESTONE), false); + machine.serverTick(); + var lane = machine.features.processor("left").orElseThrow(); + lane.tick(machine.features, 99); + long before = machine.energy.stored(); + var used = machine.energy.used(); + machine.items.inventory("left_output").restoreStack(0, + new ItemStack(Items.DIRT, 64)); + lane.tick(machine.features, 3); + h.assertTrue( + lane.progress() == 99 && machine.energy.stored() == before + && machine.energy.used().equals(used), + "Blocked final step rolls back both charges, progress and telemetry"); + machine.items.inventory("left_output").restoreStack(0, ItemStack.EMPTY); + lane.tick(machine.features, 1); + h.assertTrue( + machine.energy.stored() == before - 25 && machine.items + .inventory("left_output").getStackInSlot(0).is(Items.GRAVEL), + "Unblocking charges only once"); + h.succeed(); + } + + @GameTest(template = "empty") + public static void customProcessorOperatingCostRefundsFailedWork( + GameTestHelper h) { + var machine = place(h, "paid_workshop"); + machine.fluids.fill(new FluidStack(Fluids.WATER, 10), + FluidAction.EXECUTE); + machine.energy.setStored(2); + machine.serverTick(); + h.assertTrue( + machine.energy.stored() == 2 + && machine.fluids.getFluidInTank(0).getAmount() == 10, + "Custom processor stalls before work without operating power"); + machine.energy.setStored(3); + machine.serverTick(); + h.assertTrue( + machine.energy.stored() == 100 + && machine.fluids.getFluidInTank(0).getAmount() == 9 + && machine.energy.used().intValue() == 3, + "Custom work pays overhead then produces energy"); + machine.energy.setStored(machine.energy.capacity()); + var used = machine.energy.used(); + machine.serverTick(); + h.assertTrue( + machine.energy.stored() == machine.energy.capacity() + && machine.energy.used().equals(used) + && machine.fluids.getFluidInTank(0).getAmount() == 9, + "Blocked custom work refunds overhead and telemetry"); + h.succeed(); + } + + @GameTest(template = "empty") + public static void customEnergyHasOneOwnerAndLiveCapabilityPolicy( + GameTestHelper h) { + var machine = place(h, "battery_workshop"); + var bank = machine.features.findProcessor("battery", + zone.moddev.mc.companion.BatteryBank.class).orElseThrow(); + h.assertTrue( + bank.buffer() == machine.energy + && machine.screenEnergy() == machine.energy, + "Provider, recipes, persistence and screen share one buffer"); + var capability = h.getLevel().getCapability( + net.neoforged.neoforge.capabilities.Capabilities.EnergyStorage.BLOCK, + machine.getBlockPos(), null); + h.assertTrue( + capability != null && capability.receiveEnergy(2000, true) == 2000, + "Custom capability simulates"); + h.assertTrue(machine.energy.stored() == 0, + "Simulation leaves buffer empty"); + capability.receiveEnergy(2000, false); + h.assertTrue(machine.resources().energy("energy").stored() == 2000, + "Transactions see capability input"); + var east = h.getLevel().getCapability( + net.neoforged.neoforge.capabilities.Capabilities.EnergyStorage.BLOCK, + machine.getBlockPos(), net.minecraft.core.Direction.EAST); + h.assertTrue(east != null && east.receiveEnergy(100, false) == 0, + "Provider side policy enforced"); + bank.setPaused(true); + h.assertTrue( + capability.extractEnergy(100, false) == 0 + && capability.receiveEnergy(100, false) == 0, + "Cached view observes dynamic provider availability"); + bank.setPaused(false); + h.assertTrue(capability.extractEnergy(100, false) == 100, + "Provider permits export"); + capability.receiveEnergy(2000, false); + var saved = machine.saveWithFullMetadata(h.getLevel().registryAccess()); + machine.energy.setStored(0); + machine.loadWithComponents(saved, h.getLevel().registryAccess()); + h.assertTrue(capability.getEnergyStored() == 3900, + "Same capability sees restored authoritative energy"); + machine.items.inventory("left_input").insertItem(0, + new ItemStack(Items.COBBLESTONE), false); + for (int tick = 0; tick < 102; tick++) + machine.serverTick(); + h.assertTrue( + machine.items.inventory("left_output").getStackInSlot(0) + .is(Items.GRAVEL) && machine.energy.stored() == 1900, + "Recipe uses provider energy without a second buffer"); + h.succeed(); + } + + @GameTest(template = "empty") + public static void callbacksKeepEveryAcceleratedTransition( + GameTestHelper h) { + var machine = place(h, "parallel_workshop"); + machine.energy.setStored(100000); + machine.items.inventory("left_input").insertItem(0, + new ItemStack(Items.COBBLESTONE, 3), false); + machine.serverTick(); + var lane = machine.features.processor("left").orElseThrow(); + var observer = machine.features.findProcessor("charge").orElseThrow(); + lane.tick(machine.features, 303); + h.assertTrue( + observer.variable("starts").equals(3) + && observer.variable("finishes").equals(3), + "Every start and finish delivered during one accelerated tick"); + h.assertTrue(observer.variable("last_lane").equals("left"), + "Event identifies its lane"); + var saved = machine.saveWithFullMetadata(h.getLevel().registryAccess()); + machine.loadWithComponents(saved, h.getLevel().registryAccess()); + machine.serverTick(); + h.assertTrue( + observer.variable("starts").equals(3) + && observer.variable("finishes").equals(3), + "Loading and idle work do not replay callbacks"); + h.succeed(); + } + + @GameTest(template = "empty") + public static void recipeLanesAndChargingRunTogether(GameTestHelper h) { + var machine = place(h, "parallel_workshop"); + h.assertTrue(machine.features.allProcessors().size() == 3, + "Recipe and custom processors coexist"); + machine.items.inventory("left_input").insertItem(0, + new ItemStack(Items.COBBLESTONE), false); + machine.items.inventory("right_input").insertItem(0, + new ItemStack(Items.GRAVEL), false); + machine.fluids.fill(new FluidStack(Fluids.WATER, 200), + FluidAction.EXECUTE); + for (int tick = 0; tick < 102; tick++) + machine.serverTick(); + h.assertTrue(machine.items.inventory("left_output").getStackInSlot(0) + .is(Items.GRAVEL), "Left lane output"); + h.assertTrue(machine.items.inventory("right_output").getStackInSlot(0) + .is(Items.SAND), "Right lane output"); + h.assertTrue(machine.energy.stored() > 0, + "Charge pump supplies shared energy beside recipes"); + var player = h.makeMockServerPlayerInLevel(); + new zone.moddev.mc.lib.gui.runtime.MachineMenu(1, player.getInventory(), + machine); + var saved = machine.saveWithFullMetadata(h.getLevel().registryAccess()); + machine.loadWithComponents(saved, h.getLevel().registryAccess()); + h.assertTrue( + machine.features.processor("left").orElseThrow().completedCycles() + .intValue() == 1 + && machine.features.processor("right").orElseThrow() + .completedCycles().intValue() == 1, + "Lanes persist independently"); + h.succeed(); + } + + @GameTest(template = "empty") + public static void sharedInputCannotBeReservedTwice(GameTestHelper h) { + var machine = place(h, "shared_workshop"); + machine.energy.setStored(10000); + machine.items.inventory("left_input").insertItem(0, + new ItemStack(Items.COBBLESTONE), false); + for (int tick = 0; tick < 105; tick++) + machine.serverTick(); + int products = machine.items.inventory("left_output").getStackInSlot(0) + .getCount() + + machine.items.inventory("right_output").getStackInSlot(0) + .getCount(); + h.assertTrue(products == 1, + "Two lanes sharing physical input produce only one result"); + h.succeed(); + } + + @GameTest(template = "empty", timeoutTicks = 60) + public static void comparatorsReadSharedSourcesWithoutEmittingFaces( + GameTestHelper h) { + var machine = place(h, "porting_workshop"); + var origin = machine.getBlockPos(); + var comparator = origin.east(2); + h.getLevel().setBlock(origin.east(), + net.minecraft.world.level.block.Blocks.STONE.defaultBlockState(), + 3); + h.getLevel().setBlock(comparator.below(), + net.minecraft.world.level.block.Blocks.STONE.defaultBlockState(), + 3); + h.getLevel().setBlock(comparator, + net.minecraft.world.level.block.Blocks.COMPARATOR + .defaultBlockState().setValue( + net.minecraft.world.level.block.state.properties.BlockStateProperties.HORIZONTAL_FACING, + net.minecraft.core.Direction.WEST), + 3); + machine.items.insertResult(1, new ItemStack(Items.STONE, 32), false); + machine.serverTick(); + h.assertTrue(machine.getBlockState().hasAnalogOutputSignal(), + "XML block opts into comparator readout"); + h.assertTrue(machine.getBlockState().getAnalogOutputSignal(h.getLevel(), + origin) == 7, "Readout samples existing source"); + h.assertTrue( + machine.screenRedstone() + .signal(net.minecraft.core.Direction.WEST) == 0, + "No emitting face needed"); + h.runAfterDelay(4, () -> { + var reader = (net.minecraft.world.level.block.entity.ComparatorBlockEntity) h + .getLevel().getBlockEntity(comparator); + h.assertTrue(reader.getOutputSignal() == 7, + "Comparator reads through a solid block"); + machine.items.extractItem(1, 32, false); + machine.serverTick(); + h.runAfterDelay(4, () -> { + h.assertTrue(reader.getOutputSignal() == 0, + "Storage change notifies comparator"); + h.succeed(); + }); + }); + } + + @GameTest(template = "empty") + public static void placementHooksWaitForAcceptanceAndKeepOwner( + GameTestHelper h) { + var player = h.makeMockServerPlayerInLevel(); + player.gameMode.changeGameModeForPlayer( + net.minecraft.world.level.GameType.CREATIVE); + var pos = h.absolutePos(new BlockPos(2, 2, 2)); + player.setPos( + net.minecraft.world.phys.Vec3.atCenterOf(pos.offset(3, 0, 0))); + player.setShiftKeyDown(true); + h.getLevel().setBlock(pos.below(), + net.minecraft.world.level.block.Blocks.STONE.defaultBlockState(), + 3); + var item = zone.moddev.mc.lib.machine.neoforge.MachineContent + .item(ResourceLocation.parse("mmdlib_companion:porting_workshop")); + var stack = new ItemStack(item); + player.setItemInHand(net.minecraft.world.InteractionHand.MAIN_HAND, + stack); + var hit = new net.minecraft.world.phys.BlockHitResult( + net.minecraft.world.phys.Vec3.atCenterOf(pos.below()), + net.minecraft.core.Direction.UP, pos.below(), false); + DefinedMachineEntity[] captured = {null}; + java.util.function.Consumer cancel = event -> { + if (event.getEntity() == player && event.getPos().equals(pos)) { + captured[0] = (DefinedMachineEntity) h.getLevel() + .getBlockEntity(pos); + event.setCanceled(true); + } + }; + net.neoforged.neoforge.common.NeoForge.EVENT_BUS.addListener(cancel); + try { + player.gameMode.useItemOn(player, h.getLevel(), stack, + net.minecraft.world.InteractionHand.MAIN_HAND, hit); + } finally { + net.neoforged.neoforge.common.NeoForge.EVENT_BUS.unregister(cancel); + } + h.assertTrue(captured[0] != null, + "Cancellation saw the candidate machine"); + h.assertTrue( + captured[0].features.findProcessor("workshop").orElseThrow() + .variable("placements").equals(0), + "Rejected placement never calls placed"); + player.gameMode.useItemOn(player, h.getLevel(), stack, + net.minecraft.world.InteractionHand.MAIN_HAND, hit); + var machine = (DefinedMachineEntity) h.getLevel().getBlockEntity(pos); + var processor = machine.features.findProcessor("workshop") + .orElseThrow(); + h.assertTrue(machine.facing() == net.minecraft.core.Direction.UP, + "Custom placement chooses clicked face"); + h.assertTrue( + processor.variable("owner").equals(player.getUUID().toString()), + "Placer ownership recorded"); + machine.onLoad(); + h.assertTrue(processor.variable("placements").equals(1), + "Loading does not replay placement"); + h.succeed(); + } + + @GameTest(template = "empty") + public static void typedResourceTransactionsRollbackBlockedOutput( + GameTestHelper h) { + var machine = place(h, "porting_workshop"); + machine.items.insertItem(0, new ItemStack(Items.COBBLESTONE, 2), false); + machine.fluids.fill(new FluidStack(Fluids.WATER, 100), + FluidAction.EXECUTE); + machine.items.insertResult(1, new ItemStack(Items.DIRT, 64), false); + machine.serverTick(); + h.assertTrue(machine.items.getStackInSlot(0).getCount() == 2, + "Blocked output rolls back item input"); + h.assertTrue(machine.fluids.getFluidInTank(0).getAmount() == 100, + "Blocked output rolls back fluid input"); + machine.items.extractItem(1, 64, false); + machine.serverTick(); + h.assertTrue(machine.items.getStackInSlot(1).is(Items.STONE), + "Custom processor inserts its product"); + h.assertTrue(machine.items.getStackInSlot(0).getCount() == 1, + "One input consumed"); + h.assertTrue(machine.fluids.getFluidInTank(0).getAmount() == 75, + "Fluid consumed in same transaction"); + h.succeed(); + } + + @GameTest(template = "empty") + public static void admissionRulesRejectWrongInputsAndFollowConfig( + GameTestHelper h) { + var machine = place(h, "admission_demo"); + h.assertTrue(machine.items + .insertItem(0, new ItemStack(Items.STONE), false).getCount() == 1, + "Fuel slot refuses nonfuel"); + h.assertTrue(machine.items + .insertItem(0, new ItemStack(Items.COAL), true).isEmpty(), + "Fuel simulation accepts coal"); + h.assertTrue(machine.items.getStackInSlot(0).isEmpty(), + "Simulation does not insert"); + h.assertTrue(machine.items + .insertItem(1, new ItemStack(Items.RAW_IRON), false).isEmpty(), + "Smelting input accepted"); + h.assertTrue(machine.items + .insertItem(2, new ItemStack(Items.STONE), false).getCount() == 1, + "Item tag enforced"); + h.assertTrue( + !machine.fluids.isFluidValid(0, new FluidStack(Fluids.LAVA, 100)), + "Fluid tag enforced"); + var old = AdmissionDemo.fuelTag; + try { + AdmissionDemo.fuelTag = ResourceLocation.parse("minecraft:lava"); + h.assertTrue( + machine.fluids.isFluidValid(1, + new FluidStack(Fluids.LAVA, 100)), + "Configured tag accepts lava"); + h.assertTrue(machine.fluids.fill(new FluidStack(Fluids.LAVA, 100), + FluidAction.EXECUTE) == 100, "Fuel inserted"); + AdmissionDemo.fuelTag = ResourceLocation.parse("minecraft:water"); + h.assertTrue( + !machine.fluids.isFluidValid(1, + new FluidStack(Fluids.LAVA, 100)), + "Live config changes admission"); + h.assertTrue(machine.fluids.getFluidInTank(1).getAmount() == 100, + "Existing contents retained"); + h.assertTrue( + machine.fluids.isFluidValid(2, + new FluidStack(Fluids.LAVA, 100)), + "Custom recipe lookup accepts recipe fluid"); + h.assertTrue( + !machine.fluids.isFluidValid(2, + new FluidStack(Fluids.WATER, 100)), + "Recipe lookup rejects unrelated fluid"); + } finally { + AdmissionDemo.fuelTag = old; + } + h.succeed(); + } +} diff --git a/src/companionTest/resources/data/mmdlib_porting/structure/empty.nbt b/src/companionTest/resources/data/mmdlib_porting/structure/empty.nbt new file mode 100644 index 00000000..0a144900 Binary files /dev/null and b/src/companionTest/resources/data/mmdlib_porting/structure/empty.nbt differ diff --git a/src/main/java/zone/moddev/mc/lib/api/MaterialEventContexts.java b/src/main/java/zone/moddev/mc/lib/api/MaterialEventContexts.java index 695c292a..5832350f 100644 --- a/src/main/java/zone/moddev/mc/lib/api/MaterialEventContexts.java +++ b/src/main/java/zone/moddev/mc/lib/api/MaterialEventContexts.java @@ -550,12 +550,24 @@ public record BlockAction(Level level, BlockPos position, BlockState state, * @param machineId the machine definition's ID * @param recipe the cycle's recipe * @param time the cycle's length, in ticks + * @param processor the stable processor ID, empty for legacy Java callers */ public record MachineCycle( net.minecraft.world.level.block.entity.BlockEntity machine, ServerLevel level, BlockPos position, net.minecraft.resources.ResourceLocation machineId, - net.minecraft.resources.ResourceLocation recipe, int time) { + net.minecraft.resources.ResourceLocation recipe, int time, + String processor) { + /** + * Compatibility constructor for callers without a processor identity. + */ + public MachineCycle( + net.minecraft.world.level.block.entity.BlockEntity machine, + ServerLevel level, BlockPos position, + net.minecraft.resources.ResourceLocation machineId, + net.minecraft.resources.ResourceLocation recipe, int time) { + this(machine, level, position, machineId, recipe, time, ""); + } /** Requires every value. */ public MachineCycle { Objects.requireNonNull(machine); @@ -563,6 +575,7 @@ public record MachineCycle( position = Objects.requireNonNull(position).immutable(); Objects.requireNonNull(machineId); Objects.requireNonNull(recipe); + Objects.requireNonNull(processor); } } } diff --git a/src/main/java/zone/moddev/mc/lib/api/redstone/RedstoneControl.java b/src/main/java/zone/moddev/mc/lib/api/redstone/RedstoneControl.java index e7cab99b..6555844e 100644 --- a/src/main/java/zone/moddev/mc/lib/api/redstone/RedstoneControl.java +++ b/src/main/java/zone/moddev/mc/lib/api/redstone/RedstoneControl.java @@ -48,6 +48,28 @@ public enum Mode { // neighbours. private int connections = -1; private boolean paused, legacyAny; + private int comparatorSource = -1; + private int comparatorLevel; + + /** + * Machine-owned selection; independent of per-face settings and inversion. + */ + public RedstoneControl comparatorSource(String id) { + comparatorSource = -1; + if (id != null) { + for (int i = 0; i < outputs.size(); i++) + if (outputs.get(i).id().equals(id)) + comparatorSource = i; + if (comparatorSource < 0) + throw new IllegalArgumentException( + "Unknown comparator source: " + id); + } + return this; + } + + public int comparatorLevel() { + return comparatorLevel; + } public RedstoneControl(BlockEntity owner, List> groups, ToDoubleFunction> fullness) { @@ -295,6 +317,21 @@ public void updateOutputs() { outputsChanged |= outgoing[face] != output; outgoing[face] = output; } + int nextComparator = 0; + if (comparatorSource >= 0) { + int face = 0; + while (face < 6 && (mode(face) != Mode.EMIT + || source(face) != comparatorSource)) + face++; + nextComparator = face < 6 + ? sampledLevels[face] + : outputs.get(comparatorSource).level(); + } + if (nextComparator != comparatorLevel) { + comparatorLevel = nextComparator; + level.updateNeighbourForOutputSignal(owner.getBlockPos(), + owner.getBlockState().getBlock()); + } if (connections != newConnections) { boolean firstTick = connections < 0; connections = newConnections; diff --git a/src/main/java/zone/moddev/mc/lib/client/MachineSoundsClient.java b/src/main/java/zone/moddev/mc/lib/client/MachineSoundsClient.java index 91b66701..2ccac731 100644 --- a/src/main/java/zone/moddev/mc/lib/client/MachineSoundsClient.java +++ b/src/main/java/zone/moddev/mc/lib/client/MachineSoundsClient.java @@ -18,32 +18,44 @@ * is gone. */ public final class MachineSoundsClient { - private static final Map LOOPS = new WeakHashMap<>(); + private static final Map> LOOPS = new WeakHashMap<>(); private MachineSoundsClient() { } /** Starts {@code machine}'s loop if a cycle runs and it is not playing. */ public static void tick(DefinedMachineEntity machine) { - var id = machine.definition.sounds().running().orElse(null); - if (id == null || !machine.running()) - return; - var loop = LOOPS.get(machine); - if (loop != null && !loop.isStopped()) - return; - loop = new Loop(machine, id); - LOOPS.put(machine, loop); - Minecraft.getInstance().getSoundManager().play(loop); + for (var config : machine.processorConfigurations()) { + var id = config.sounds().running().orElse(null); + if (id == null || !running(machine, config.id())) + continue; + var loops = LOOPS.computeIfAbsent(machine, + ignored -> new java.util.HashMap<>()); + var loop = loops.get(config.id()); + if (loop != null && !loop.isStopped()) + continue; + loop = new Loop(machine, config.id(), id); + loops.put(config.id(), loop); + Minecraft.getInstance().getSoundManager().play(loop); + } + } + + private static boolean running(DefinedMachineEntity machine, String key) { + return machine.features.findProcessor(key) + .map(zone.moddev.mc.lib.machine.feature.Processor::processing) + .orElse(false); } private static final class Loop extends AbstractTickableSoundInstance { private final DefinedMachineEntity machine; + private final String processor; - Loop(DefinedMachineEntity machine, + Loop(DefinedMachineEntity machine, String processor, net.minecraft.resources.ResourceLocation id) { super(SoundDefinition.event(id), SoundSource.BLOCKS, RandomSource.create()); this.machine = machine; + this.processor = processor; var pos = machine.getBlockPos(); x = pos.getX() + .5; y = pos.getY() + .5; @@ -55,7 +67,7 @@ private static final class Loop extends AbstractTickableSoundInstance { @Override public void tick() { - if (machine.isRemoved() || !machine.running()) + if (machine.isRemoved() || !running(machine, processor)) stop(); } } diff --git a/src/main/java/zone/moddev/mc/lib/client/jei/MMDLibJeiPlugin.java b/src/main/java/zone/moddev/mc/lib/client/jei/MMDLibJeiPlugin.java index 15ea9198..56bb716e 100644 --- a/src/main/java/zone/moddev/mc/lib/client/jei/MMDLibJeiPlugin.java +++ b/src/main/java/zone/moddev/mc/lib/client/jei/MMDLibJeiPlugin.java @@ -101,7 +101,7 @@ public void registerRecipeCatalysts( IRecipeCatalystRegistration registration) { zone.moddev.mc.lib.machine.neoforge.MachineContent.definitions() .forEach( - (id, machine) -> machine.processingType().ifPresent(type -> { + (id, machine) -> machine.processingTypes().forEach(type -> { registration.addRecipeCatalyst( new net.minecraft.world.item.ItemStack( BuiltInRegistries.ITEM.get(id)), diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/AdmissionDeclaration.java b/src/main/java/zone/moddev/mc/lib/machine/definition/AdmissionDeclaration.java new file mode 100644 index 00000000..e506117a --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/AdmissionDeclaration.java @@ -0,0 +1,43 @@ +package zone.moddev.mc.lib.machine.definition; + +import zone.moddev.mc.lib.machine.feature.StorageAdmission; + +/** Either a per-machine rule instance or an explicitly named processor. */ +public record AdmissionDeclaration(Class type, + String processor) { + public AdmissionDeclaration { + if ((type == null) == (processor == null) + || processor != null && processor.isBlank()) + throw new IllegalArgumentException( + "Specify one filter-class or filter-processor"); + } + + public static AdmissionDeclaration load(String name, String processor, + ClassLoader loader) { + if (name == null) + return processor == null + ? null + : new AdmissionDeclaration(null, processor); + if (processor != null) + throw new IllegalArgumentException( + "Specify one filter-class or filter-processor"); + try { + var type = Class.forName(name, false, loader) + .asSubclass(StorageAdmission.class); + type.getConstructor(); + return new AdmissionDeclaration(type, null); + } catch (ReflectiveOperationException | ClassCastException ex) { + throw new IllegalArgumentException( + "Invalid admission class: " + name, ex); + } + } + + public StorageAdmission create() { + try { + return type.getConstructor().newInstance(); + } catch (ReflectiveOperationException ex) { + throw new IllegalArgumentException( + "Cannot instantiate admission class: " + type.getName(), ex); + } + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/EntityDisplay.java b/src/main/java/zone/moddev/mc/lib/machine/definition/EntityDisplay.java index a2cd060b..9ffc4351 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/definition/EntityDisplay.java +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/EntityDisplay.java @@ -45,13 +45,6 @@ public void validate(Map> processors) { public net.minecraft.world.phys.Vec3 offset( net.minecraft.core.Direction facing) { - return switch (facing) { - case NORTH -> new net.minecraft.world.phys.Vec3(x, y, z); - case EAST -> new net.minecraft.world.phys.Vec3(1 - z, y, x); - case SOUTH -> new net.minecraft.world.phys.Vec3(1 - x, y, 1 - z); - case WEST -> new net.minecraft.world.phys.Vec3(z, y, 1 - x); - default -> throw new IllegalArgumentException( - "Entity display requires horizontal facing"); - }; + return MachineFacing.point(facing, x, y, z); } } diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/ItemDisplay.java b/src/main/java/zone/moddev/mc/lib/machine/definition/ItemDisplay.java index b7c5f039..c8871efd 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/definition/ItemDisplay.java +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/ItemDisplay.java @@ -36,13 +36,6 @@ public void validate(Map> processors) { */ public net.minecraft.world.phys.Vec3 offset( net.minecraft.core.Direction facing) { - return switch (facing) { - case SOUTH -> new net.minecraft.world.phys.Vec3(x, y, 1.002); - case NORTH -> new net.minecraft.world.phys.Vec3(1 - x, y, -.002); - case EAST -> new net.minecraft.world.phys.Vec3(1.002, y, 1 - x); - case WEST -> new net.minecraft.world.phys.Vec3(-.002, y, x); - default -> throw new IllegalArgumentException( - "Item display requires horizontal facing"); - }; + return MachineFacing.point(facing, 1 - x, y, -.002); } } diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineBehavior.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineBehavior.java index 16f807f5..cffac47a 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineBehavior.java +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineBehavior.java @@ -10,7 +10,21 @@ public record MachineBehavior(ProcessorDeclaration processor, int stackSize, EntityDisplay entityDisplay, ItemDisplay itemDisplay, zone.moddev.mc.lib.machine.presentation.VisualizerStyle visualizers, String gearboxSlot, String capacitorSlot, List rangeSlots, - String legacyUpgradeStorage) { + String legacyUpgradeStorage, MachineFacing facing, String comparatorSource, + List processors) { + public MachineBehavior(ProcessorDeclaration processor, int stackSize, + boolean noOcclusion, boolean immovable, boolean portable, + boolean drawers, List shapes, + net.minecraft.resources.ResourceLocation secondaryAction, + EntityDisplay entityDisplay, ItemDisplay itemDisplay, + zone.moddev.mc.lib.machine.presentation.VisualizerStyle visualizers, + String gearboxSlot, String capacitorSlot, List rangeSlots, + String legacyUpgradeStorage) { + this(processor, stackSize, noOcclusion, immovable, portable, drawers, + shapes, secondaryAction, entityDisplay, itemDisplay, visualizers, + gearboxSlot, capacitorSlot, rangeSlots, legacyUpgradeStorage, + MachineFacing.DEFAULT, null, List.of()); + } public MachineBehavior(ProcessorDeclaration processor, int stackSize, boolean noOcclusion, boolean immovable, boolean portable, boolean drawers, List shapes, @@ -40,7 +54,9 @@ public MachineBehavior(ProcessorDeclaration processor, int stackSize, false, false, false, true, List.of(), null); public MachineBehavior { java.util.Objects.requireNonNull(visualizers); + java.util.Objects.requireNonNull(facing); rangeSlots = List.copyOf(rangeSlots); + processors = List.copyOf(processors); if (rangeSlots.size() > 9 || new java.util.HashSet<>(rangeSlots).size() != rangeSlots.size()) throw new IllegalArgumentException( diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinition.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinition.java index 6e2998ed..82554929 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinition.java +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinition.java @@ -54,10 +54,23 @@ public static Set ghostInputsFor( continue; var ghosts = new HashSet(); machine.ghosts().forEach(ghost -> ghosts.add(ghost.id())); - if (result == null) - result = ghosts; - else - result.retainAll(ghosts); + for (var config : machine.processors()) { + if (config.recipeType() == null + || !config.recipeType().id().equals(recipeType)) + continue; + var aliases = new HashSet(); + if (config.bindings().isEmpty()) + aliases.addAll(ghosts); + else + config.bindings().forEach((alias, target) -> { + if (ghosts.contains(target)) + aliases.add(alias); + }); + if (result == null) + result = aliases; + else + result.retainAll(aliases); + } } return result == null ? Set.of() : Set.copyOf(result); } @@ -232,6 +245,37 @@ public Map groupNames() { return Collections.unmodifiableMap(names); } + public List processors() { + if (!behavior.processors().isEmpty()) + return behavior.processors(); + if (processor == null) + return List.of(); + var inputGroups = new java.util.ArrayList(); + groups.stream().filter(g -> g.mode() == IoMode.INPUT) + .forEach(g -> inputGroups.add(g.id())); + if (fluids != null) + fluids.groups().stream().filter(g -> g.mode() == IoMode.INPUT) + .forEach(g -> inputGroups.add(g.id())); + return List.of(new ProcessorConfiguration(processor, processorName, + recipeType, behavior.processor(), Map.of(), inputGroups, + recipeSelection, sounds, events)); + } + + public List processingTypes() { + return processors().stream().map(ProcessorConfiguration::recipeType) + .filter(java.util.Objects::nonNull).distinct().toList(); + } + + public Map> processorSchemas() { + var result = new LinkedHashMap>(); + processors().forEach(config -> { + if (config.declaration() != null) + result.put(config.id(), + config.declaration().schema(config.id())); + }); + return Collections.unmodifiableMap(result); + } + public boolean hasProcessor() { return processor != null; } @@ -245,7 +289,8 @@ public Optional processingType() { } public boolean processes(ResourceLocation type) { - return recipeType != null && recipeType.id().equals(type); + return processingTypes().stream() + .anyMatch(recipe -> recipe.id().equals(type)); } public Map visualDefaults() { @@ -270,7 +315,11 @@ public List visualConditions() { } public record Power(String id, long capacity, long input, long output, - int color, String name) { + int color, String name, String provider, boolean capacitors) { + public Power(String id, long capacity, long input, long output, + int color, String name) { + this(id, capacity, input, output, color, name, null, true); + } public Power(String id, long capacity, long input, long output, int color) { this(id, capacity, input, output, color, "Energy"); @@ -327,14 +376,22 @@ public List inventorySlots(String name) { } public record Slot(String id, Role role, int limit, - ResourceLocation itemTag) { + ResourceLocation itemTag, AdmissionDeclaration admission) { + public Slot(String id, Role role, int limit, ResourceLocation itemTag) { + this(id, role, limit, itemTag, null); + } public Slot(String id, Role role, int limit) { this(id, role, limit, null); } } public record Tank(String id, Role role, int capacity, - ResourceLocation fluid) { + ResourceLocation fluid, ResourceLocation fluidTag, + AdmissionDeclaration admission) { + public Tank(String id, Role role, int capacity, + ResourceLocation fluid) { + this(id, role, capacity, fluid, null, null); + } } public record Fluids(String id, List tanks, List groups) { diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinitions.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinitions.java index 3376e1b4..740ad5e9 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinitions.java +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineDefinitions.java @@ -90,6 +90,100 @@ public static Map load( return Collections.unmodifiableMap(plans); } + private static ProcessorConfiguration processorConfiguration(Node node, + Map recipes, Set resources, + Set inputs, Map loaders, + String machineName) { + try { + String id = required(node, "id"); + long operatingCost = node.attributes() + .containsKey("energy-per-tick") + ? number(node, "energy-per-tick", 0, Long.MAX_VALUE) + : 0; + if (operatingCost > 0 && !resources.contains("energy")) + throw error(node, "energy-per-tick requires energy storage"); + var bindings = new LinkedHashMap(); + if (node.attributes().containsKey("bindings")) { + for (String pair : required(node, "bindings").split("\\s+")) { + String[] parts = pair.split("=", -1); + if (parts.length != 2 || parts[0].isBlank() + || !resources.contains(parts[1]) + || bindings.putIfAbsent(parts[0], parts[1]) != null) + throw error(node, "Invalid processor binding: " + pair); + } + if (resources.contains("energy")) + bindings.putIfAbsent("energy", "energy"); + } else + resources.forEach(key -> bindings.put(key, key)); + if (node.attributes().containsKey("class")) { + for (var option : List.of("recipe-type", "filter-inputs", + "selectable", "default-recipe", "running-sound", + "finish-sound", "on-start", "on-finish")) + if (node.attributes().containsKey(option)) + throw error(node, + "Custom processors cannot take " + option); + if (node.attributes().containsKey("bindings")) + throw error(node, + "Custom processors use named host resources directly"); + return new ProcessorConfiguration(id, + node.attributes().getOrDefault("name", machineName), null, + ProcessorDeclaration.load(required(node, "class"), + loaders.get(node.source())), + Map.of(), List.of(), null, MachineDefinition.Sounds.NONE, + MachineDefinition.Events.NONE, operatingCost); + } + var recipeNode = recipes.get(resource(node, "recipe-type")); + if (recipeNode == null) + throw error(node, "Unknown recipe type"); + var filterInputs = node.attributes().containsKey("filter-inputs") + ? List.of(required(node, "filter-inputs").split("\\s+")) + : bindings.entrySet().stream() + .filter(entry -> inputs.contains(entry.getValue())) + .map(Map.Entry::getKey).toList(); + var expectedInputs = bindings.entrySet().stream() + .filter(entry -> inputs.contains(entry.getValue())) + .map(Map.Entry::getKey) + .collect(java.util.stream.Collectors.toSet()); + if (!new HashSet<>(filterInputs).equals(expectedInputs)) + throw error(node, + "filter-inputs must name all bound input groups"); + for (var key : filterInputs) + if (!inputs.contains(bindings.get(key))) + throw error(node, + "filter-inputs must name bound input groups"); + boolean selectable = bool(node, "selectable", false); + if (!selectable && node.attributes().containsKey("default-recipe")) + throw error(node, "default-recipe requires selectable='true'"); + return new ProcessorConfiguration(id, + node.attributes().getOrDefault("name", machineName), + recipeType(recipeNode, loaders), null, bindings, filterInputs, + selectable + ? new MachineDefinition.RecipeSelection( + optionalResource(node, "default-recipe").orElse(null)) + : null, + new MachineDefinition.Sounds( + optionalResource(node, "running-sound"), + optionalResource(node, "finish-sound")), + new MachineDefinition.Events(optionalResource(node, "on-start"), + optionalResource(node, "on-finish")), + operatingCost); + } catch (IllegalArgumentException ex) { + throw error(node, ex.getMessage()); + } + } + + private static AdmissionDeclaration admission(Node node, + Map loaders) { + try { + return AdmissionDeclaration.load( + node.attributes().get("filter-class"), + node.attributes().get("filter-processor"), + loaders.get(node.source())); + } catch (IllegalArgumentException ex) { + throw error(node, ex.getMessage()); + } + } + private static Node resolve(ResourceLocation id, Map nodes, Map resolved, Set visiting) { @@ -116,6 +210,9 @@ private static Node resolve(ResourceLocation id, private static String key(Node parent, Node node) { // These sections contain singletons; their ID is configuration, not // merge identity. + if (parent.name().equals("machine") + && Set.of("processor", "recipe-type").contains(node.name())) + return node.name() + ":" + required(node, "id"); if (Set.of("machine", "storage", "recipe-type").contains(parent.name())) return node.name(); if (parent.name().equals("appearance") && isDisplay(node)) @@ -145,16 +242,28 @@ private static Node merge(Node base, Node child) { "model")) attrs.remove(attribute); attrs.putAll(child.attributes()); + var singletonOverrides = new HashSet(); + if (base.name().equals("machine")) + for (var kind : List.of("processor", "recipe-type")) + if (base.children().stream().filter(n -> n.name().equals(kind)) + .count() == 1 + && child.children().stream() + .filter(n -> n.name().equals(kind)).count() == 1) + singletonOverrides.add(kind); var children = new ArrayList<>(base.children()); var indexes = new HashMap(); for (int i = 0; i < children.size(); i++) { - var key = key(base, children.get(i)); + var key = singletonOverrides.contains(children.get(i).name()) + ? children.get(i).name() + : key(base, children.get(i)); if (key != null && indexes.putIfAbsent(key, i) != null) throw error(children.get(i), "Duplicate definition " + key); } var seen = new HashSet(); for (var node : child.children()) { - var key = key(child, node); + var key = singletonOverrides.contains(node.name()) + ? node.name() + : key(child, node); if (key != null && !seen.add(key)) throw error(node, "Duplicate definition " + key); var index = key == null ? null : indexes.get(key); @@ -173,9 +282,9 @@ private static Node merge(Node base, Node child) { private static final Map> ATTRIBUTES = Map.ofEntries( Map.entry("machine", Set.of("version", "abstract", "extends", "name")), Map.entry("block", - Set.of("hardness", "facing", "drop", "mineable", "requires-tool", - "stack-size", "no-occlusion", "immovable", "portable", - "on-secondary-use", "drawers")), + Set.of("hardness", "facing", "placement-facing", "drop", "mineable", + "requires-tool", "stack-size", "no-occlusion", "immovable", + "portable", "on-secondary-use", "drawers")), Map.entry("appearance", Set.of("preset", "front", "side", "top", "bottom", "model")), Map.entry("visualizers", Set.of("range-color", "work-color")), @@ -195,21 +304,22 @@ private static Node merge(Node base, Node child) { "frames", "variable", "emissive", "when")), Map.entry("storage", Set.of()), Map.entry("items", Set.of("id")), Map.entry("fluids", Set.of("id")), - Map.entry("tank", - Set.of("id", "capacity", "role", "fluid", "color", "automation", - "name")), + Map.entry("tank", Set.of("id", "capacity", "role", "fluid", "fluid-tag", + "filter-class", "filter-processor", "color", "automation", "name")), Map.entry("tanks", - Set.of("id", "count", "capacity", "role", "fluid", "color", - "automation", "name")), + Set.of("id", "count", "capacity", "role", "fluid", "fluid-tag", + "filter-class", "filter-processor", "color", "automation", + "name")), Map.entry("energy", Set.of("id", "capacity", "input-rate", "output-rate", "color", - "name")), + "name", "provider", "capacitors")), Map.entry("slots", Set.of("id", "count", "role", "limit", "color", "type", - "default-item", "name", "automation", "item-tag")), + "default-item", "name", "automation", "item-tag", + "filter-class", "filter-processor")), Map.entry("slot", Set.of("id", "count", "role", "limit", "type", "default-item", - "name", "item-tag")), + "name", "item-tag", "filter-class", "filter-processor")), Map.entry("groups", Set.of()), Map.entry("group", Set.of("id", "storage", "members", "mode", "color", "name")), @@ -217,8 +327,9 @@ private static Node merge(Node base, Node child) { Map.entry("processor", Set.of("id", "name", "recipe-type", "filter-inputs", "selectable", "default-recipe", "class", "running-sound", "finish-sound", - "on-start", "on-finish")), - Map.entry("redstone", Set.of("enabled", "pause")), + "on-start", "on-finish", "bindings", "primary", + "energy-per-tick")), + Map.entry("redstone", Set.of("enabled", "pause", "comparator-source")), Map.entry("shape", Set.of("id", "when", "bounds")), Map.entry("shapes", Set.of()), Map.entry("recovery", Set.of("policy"))); private static final Map> CHILDREN = Map.of("machine", @@ -262,7 +373,7 @@ private static void validateTree(Node node) { case "recipe-type" -> List.of("id"); case "processor" -> List.of("recipe-type", "default-recipe", "running-sound", "finish-sound", "on-start", "on-finish"); - case "tank", "tanks" -> List.of("fluid"); + case "tank", "tanks" -> List.of("fluid", "fluid-tag"); case "slot", "slots" -> List.of("default-item", "item-tag"); default -> List.of(); }; @@ -299,7 +410,7 @@ private static MachineDefinition plan(ResourceLocation id, Node root, if (!"1".equals(root.attributes().get("version"))) throw error(root, "Expected machine version=1"); var block = one(root, "block"); - requireChoice(block, "facing", "horizontal"); + requireChoice(block, "drop", "self"); var appearance = one(root, "appearance"); requireChoice(appearance, "preset", "cube-front", "model"); @@ -328,6 +439,13 @@ private static MachineDefinition plan(ResourceLocation id, Node root, } var storage = one(root, "storage"); var power = optional(storage, "energy"); + String energyProvider = power == null + ? null + : power.attributes().get("provider"); + if ("builtin".equals(energyProvider)) + energyProvider = null; + boolean energyCapacitors = power != null + && bool(power, "capacitors", energyProvider == null); var items = optional(storage, "items"); String itemId = items == null ? null : required(items, "id"); if (items != null && (itemId.equals("energy") @@ -376,7 +494,9 @@ private static MachineDefinition plan(ResourceLocation id, Node root, if (tankIds.putIfAbsent(member, tanks.size()) != null) throw error(node, "Duplicate tank " + member); members.add(tanks.size()); - tanks.add(new Tank(member, role, capacity, filter)); + tanks.add(new Tank(member, role, capacity, filter, + optionalResource(node, "fluid-tag").orElse(null), + admission(node, loaders))); } if (fluidGroups.putIfAbsent(tankId, new Group(tankId, members, mode(role), @@ -410,9 +530,11 @@ private static MachineDefinition plan(ResourceLocation id, Node root, if (!Set.of("item", "ghost").contains(slotType)) throw error(node, "Slot type must be item or ghost"); if (slotType.equals("ghost")) { - if (node.attributes().containsKey("item-tag")) + if (node.attributes().containsKey("item-tag") + || node.attributes().containsKey("filter-class") + || node.attributes().containsKey("filter-processor")) throw error(node, - "item-tag is only supported for real item slots"); + "Storage filters are only supported for real item slots"); if (node.attributes().containsKey("automation")) throw error(node, "Ghost slots do not expose automation"); if (role != Role.INPUT @@ -450,7 +572,8 @@ private static MachineDefinition plan(ResourceLocation id, Node root, slots.add(new Slot(memberId, role, limit, node.attributes().containsKey("item-tag") ? resource(node, "item-tag") - : null)); + : null, + admission(node, loaders))); } if (node.name().equals("slots")) { boolean automation = bool(node, "automation", true); @@ -588,26 +711,55 @@ else if (prior != null) "Group mode conflicts with tank role: " + group.id()); } } - var recipe = optional(root, "recipe-type"); - var processor = optional(root, "processor"); - boolean custom = processor != null - && processor.attributes().containsKey("class"); - if (custom && (recipe != null - || processor.attributes().containsKey("recipe-type") - || processor.attributes().containsKey("selectable") - || processor.attributes().containsKey("filter-inputs"))) - throw error(processor, - "Custom processors do not declare recipe processing options"); - if (custom) - for (var cycleOnly : List.of("running-sound", "finish-sound", - "on-start", "on-finish")) - if (processor.attributes().containsKey(cycleOnly)) - throw error(processor, "Custom processors have no recipe " - + "cycles, so they cannot take " + cycleOnly); - if (!custom && (recipe == null) != (processor == null)) - throw error(root, - "recipe-type and processor must be supplied together"); + var resourceKeys = new LinkedHashSet(); + resourceKeys.addAll(groups.keySet()); + resourceKeys.addAll(fluidGroups.keySet()); + ghosts.forEach(ghost -> resourceKeys.add(ghost.id())); + if (power != null) + resourceKeys.add("energy"); + var inputKeys = new LinkedHashSet(); + groups.values().stream().filter(g -> g.mode() == IoMode.INPUT) + .forEach(g -> inputKeys.add(g.id())); + fluidGroups.values().stream().filter(g -> g.mode() == IoMode.INPUT) + .forEach(g -> inputKeys.add(g.id())); + var processorNodes = root.children().stream() + .filter(n -> n.name().equals("processor")).toList(); + var primaryNodes = processorNodes.stream() + .filter(n -> bool(n, "primary", false)).toList(); + if (primaryNodes.size() > 1) + throw error(root, "Only one primary processor is allowed"); + if (processorNodes.size() > 1 && primaryNodes.isEmpty() + && (bool(block, "portable", false) + || block.attributes().containsKey("on-secondary-use"))) + throw error(block, + "Multiple processors require an explicit primary for portable/secondary actions"); + var processor = primaryNodes.isEmpty() + ? (processorNodes.isEmpty() ? null : processorNodes.getFirst()) + : primaryNodes.getFirst(); + var recipeNodes = new LinkedHashMap(); + for (var node : root.children()) + if (node.name().equals("recipe-type") + && recipeNodes.putIfAbsent(resource(node, "id"), node) != null) + throw error(node, "Duplicate recipe type"); + var processorConfigs = new ArrayList(); + var processorIds = new HashSet(); + for (var node : processorNodes) { + var config = processorConfiguration(node, recipeNodes, resourceKeys, + inputKeys, loaders, required(root, "name")); + if (!processorIds.add(config.id())) + throw error(node, "Duplicate processor ID " + config.id()); + processorConfigs.add(config); + } + var primary = processor == null + ? null + : processorConfigs.stream() + .filter(config -> config.id().equals(required(processor, "id"))) + .findFirst().orElseThrow(); + boolean custom = primary != null && primary.declaration() != null; + var recipeType = primary == null ? null : primary.recipeType(); if (processor == null) { + if (!recipeNodes.isEmpty()) + throw error(root, "recipe-type requires a processor"); if (slots.stream().anyMatch( slot -> slot.role() == Role.INPUT || slot.role() == Role.OUTPUT) || !ghosts.isEmpty()) @@ -618,20 +770,6 @@ else if (prior != null) throw error(fluidNode, "Machines without a processor require storage/manual tank roles"); } - var recipeType = recipe == null ? null : recipeType(recipe, loaders); - if (!custom && processor != null - && !recipeType.id().equals(resource(processor, "recipe-type"))) - throw error(processor, "Unknown recipe type"); - // All input groups are linked automatically when processing is enabled. - var inputs = java.util.stream.Stream - .concat(groups.values().stream(), fluidGroups.values().stream()) - .filter(g -> g.mode() == IoMode.INPUT).map(Group::id).toList(); - if (processor != null - && processor.attributes().containsKey("filter-inputs") - && !new HashSet<>(Arrays - .asList(required(processor, "filter-inputs").split("\\s+"))) - .equals(new HashSet<>(inputs))) - throw error(processor, "filter-inputs must name the input groups"); var redstone = optional(root, "redstone"); if (redstone != null) requireChoice(redstone, "pause", "processing-only"); @@ -757,17 +895,33 @@ else if (prior != null) throw error(itemDisplayNode, ex.getMessage()); } } - ProcessorDeclaration declaration = null; - zone.moddev.mc.lib.machine.feature.Processor prototype = null; - if (custom) { - try { - declaration = ProcessorDeclaration.load( - required(processor, "class"), - loaders.get(processor.source())); - prototype = declaration.schema(required(processor, "id")); - } catch (IllegalArgumentException ex) { - throw error(processor, ex.getMessage()); + ProcessorDeclaration declaration = primary == null + ? null + : primary.declaration(); + zone.moddev.mc.lib.machine.feature.Processor prototype = declaration == null + ? null + : declaration.schema(primary.id()); + var schemas = new LinkedHashMap>(); + processorConfigs.forEach(config -> { + if (config.declaration() != null) + schemas.put(config.id(), + config.declaration().schema(config.id())); + }); + if (redstone != null + && redstone.attributes().containsKey("comparator-source")) { + var source = required(redstone, "comparator-source"); + var outputIds = new HashSet(); + for (var config : processorConfigs) { + if (config.recipeType() != null) + outputIds.addAll( + zone.moddev.mc.lib.machine.feature.RecipeProcessor + .redstoneOutputIds(config.id())); + else + outputIds.addAll( + config.declaration().redstoneOutputIds(config.id())); } + if (!outputIds.contains(source)) + throw error(redstone, "Unknown comparator source: " + source); } var visualizers = optional(root, "visualizers"); var visualizerStyle = zone.moddev.mc.lib.machine.presentation.VisualizerStyle.DEFAULT; @@ -776,6 +930,17 @@ else if (prior != null) color(visualizers, "range-color", visualizerStyle.rangeColor()), color(visualizers, "work-color", visualizerStyle.workColor())); } + if (energyProvider != null) { + final String provider = energyProvider; + if (processorConfigs.stream() + .noneMatch(config -> config.id().equals(provider) + && config.declaration() != null + && zone.moddev.mc.lib.machine.feature.ProcessorEnergy.class + .isAssignableFrom(config.declaration().type()))) + throw error(power, + "Energy provider must name a processor implementing ProcessorEnergy: " + + provider); + } var upgrades = optional(root, "upgrades"); String gearboxSlot = upgrades == null ? null @@ -795,7 +960,7 @@ else if (prior != null) if (gearboxSlot == null && processor != null) gearboxSlot = componentSocket(root, slots, groups, ids, "gearbox"); - if (capacitorSlot == null && power != null) + if (capacitorSlot == null && power != null && energyCapacitors) capacitorSlot = componentSocket(root, slots, groups, ids, "capacitor"); if (itemId == null && !slots.isEmpty()) @@ -834,9 +999,12 @@ else if (prior != null) group -> group.automation() && group.members().contains(index))) throw error(upgrades, "range-slots must not expose automation"); var slot = slots.get(index); - slots.set(index, - new Slot(slot.id(), slot.role(), 1, slot.itemTag())); + slots.set(index, new Slot(slot.id(), slot.role(), 1, slot.itemTag(), + slot.admission())); } + if (capacitorSlot != null && !energyCapacitors) + throw error(upgrades, + "Selected energy provider does not enable capacitor upgrades"); if (capacitorSlot != null && power == null) throw error(upgrades, "capacitor-slot requires energy storage"); if (capacitorSlot != null && capacitorSlot.equals(gearboxSlot)) @@ -865,8 +1033,8 @@ else if (prior != null) throw error(upgrades, attribute + " must not expose automation"); var slot = slots.get(index); - slots.set(index, - new Slot(slot.id(), slot.role(), 8, slot.itemTag())); + slots.set(index, new Slot(slot.id(), slot.role(), 8, slot.itemTag(), + slot.admission())); } MachineBehavior behavior; try { @@ -881,31 +1049,60 @@ else if (prior != null) ? resource(block, "on-secondary-use") : null, display, itemDisplay, visualizerStyle, gearboxSlot, - capacitorSlot, rangeSlots, legacyUpgradeStorage); + capacitorSlot, rangeSlots, legacyUpgradeStorage, + MachineFacing.parse( + block.attributes().getOrDefault("facing", "horizontal"), + block.attributes().getOrDefault("placement-facing", + "toward-player")), + redstone == null + ? null + : redstone.attributes().get("comparator-source"), + processorConfigs.size() == 1 + && !processor.attributes().containsKey("bindings") + && processorConfigs.getFirst().energyPerTick() == 0 + ? List.of() + : processorConfigs); } catch (IllegalArgumentException ex) { throw error(block, ex.getMessage()); } + var admissions = new ArrayList(); + slots.forEach(slot -> { + if (slot.admission() != null) + admissions.add(slot.admission()); + }); + tanks.forEach(tank -> { + if (tank.admission() != null) + admissions.add(tank.admission()); + }); + for (var admission : admissions) + if (admission.processor() != null && processorConfigs.stream() + .noneMatch(config -> config.id().equals(admission.processor()) + && config.declaration() != null + && zone.moddev.mc.lib.machine.feature.StorageAdmission.class + .isAssignableFrom(config.declaration().type()))) + throw error(root, + "filter-processor must name a processor implementing StorageAdmission: " + + admission.processor()); if (behavior.secondaryAction() != null && (prototype == null || !prototype.actions().containsKey(behavior.secondaryAction()))) throw error(block, "Unknown secondary-use processor action: " + behavior.secondaryAction()); if (display != null) { - if (!custom || (display.item() && !behavior.portable())) + if (schemas.isEmpty() || (display.item() && !behavior.portable())) throw error(displayNode, "Entity displays require a custom processor; item displays require portable machines"); try { - display.validate(Map.of(required(processor, "id"), prototype)); + display.validate(schemas); } catch (IllegalArgumentException ex) { throw error(displayNode, ex.getMessage()); } } if (itemDisplay != null) { - if (prototype == null) + if (schemas.isEmpty()) throw error(itemDisplayNode, "Item displays require a custom processor with a synchronized variable"); try { - itemDisplay - .validate(Map.of(required(processor, "id"), prototype)); + itemDisplay.validate(schemas); } catch (IllegalArgumentException ex) { throw error(itemDisplayNode, ex.getMessage()); } @@ -920,7 +1117,7 @@ else if (prior != null) number(power, "capacity", 1, Long.MAX_VALUE), number(power, "input-rate", 0, Long.MAX_VALUE), number(power, "output-rate", 0, Long.MAX_VALUE), - energyColor, energyName), + energyColor, energyName, energyProvider, energyCapacitors), fluidNode == null ? null : new Fluids(required(fluidNode, "id"), tanks, diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineFacing.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineFacing.java new file mode 100644 index 00000000..3958e29e --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineFacing.java @@ -0,0 +1,97 @@ +package zone.moddev.mc.lib.machine.definition; + +import java.util.EnumSet; +import java.util.Set; + +import net.minecraft.core.Direction; +import net.minecraft.world.phys.Vec3; + +/** Allowed fronts and the independent placement preference. */ +public record MachineFacing(Set directions, boolean towardPlayer) { + public static final MachineFacing DEFAULT = parse("horizontal", + "toward-player"); + + public MachineFacing { + directions = Set.copyOf(directions); + if (directions.isEmpty()) + throw new IllegalArgumentException( + "Facing requires at least one direction"); + } + + public static MachineFacing parse(String faces, String placement) { + var directions = EnumSet.noneOf(Direction.class); + if (faces.equals("horizontal")) + directions.addAll(Set.of(Direction.NORTH, Direction.SOUTH, + Direction.EAST, Direction.WEST)); + else if (faces.equals("all")) + directions = EnumSet.allOf(Direction.class); + else + for (var name : faces.trim().split("\\s+")) { + var direction = Direction.byName(name); + if (direction == null || !directions.add(direction)) + throw new IllegalArgumentException( + "Invalid or duplicate facing: " + name); + } + if (!placement.equals("toward-player") + && !placement.equals("away-from-player")) + throw new IllegalArgumentException( + "Invalid placement-facing: " + placement); + return new MachineFacing(directions, placement.equals("toward-player")); + } + + public boolean horizontal() { + return directions.stream().noneMatch(d -> d.getAxis().isVertical()); + } + + public Direction defaultDirection() { + return directions.contains(Direction.NORTH) + ? Direction.NORTH + : java.util.Arrays.stream(Direction.values()) + .filter(directions::contains).findFirst().orElseThrow(); + } + + /** + * Ordered nearest-look directions, as supplied by the placement context. + */ + public Direction placement(Direction[] nearest) { + for (var direction : nearest) { + var front = towardPlayer ? direction.getOpposite() : direction; + if (directions.contains(front)) + return front; + } + return defaultDirection(); + } + + public Direction transformed(Direction current, Direction proposed) { + return directions.contains(proposed) ? proposed : current; + } + + /** + * Rotates north-authored block coordinates; vertical fronts have north as + * top. + */ + public static Vec3 point(Direction front, double x, double y, double z) { + return switch (front) { + case NORTH -> new Vec3(x, y, z); + case EAST -> new Vec3(1 - z, y, x); + case SOUTH -> new Vec3(1 - x, y, 1 - z); + case WEST -> new Vec3(z, y, 1 - x); + case UP -> new Vec3(1 - x, 1 - z, 1 - y); + case DOWN -> new Vec3(x, z, 1 - y); + }; + } + + /** Model JSON rotations, matching point(). */ + public static int modelX(Direction front) { + return front == Direction.UP ? 270 : front == Direction.DOWN ? 90 : 0; + } + + public static int modelY(Direction front) { + return switch (front) { + case EAST -> 90; + case SOUTH, UP -> 180; + case WEST -> 270; + default -> 0; + }; + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineScreenGenerators.java b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineScreenGenerators.java index c439e773..c2b3da79 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/definition/MachineScreenGenerators.java +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/MachineScreenGenerators.java @@ -54,9 +54,9 @@ public interface Generator { register(ResourceLocation.parse("mmdlib:processors"), (machine, node) -> { options(node, Set.of()); - return machine.processingType().isEmpty() - ? List.of() - : List.of(progress(machine, node)); + return machine.processors().stream() + .filter(config -> config.recipeType() != null) + .map(config -> progress(machine, config, node)).toList(); }); } @@ -104,6 +104,22 @@ && declaresUpgradeLayout(composed)) @Override public Node prepareElement(ResourceLocation id, Node node) { var machine = machines.get(id); + if (machine != null && machine.processors().size() > 1 + && node.tag().equals(ScreenTags.name("inventory-controls")) + && node.children().size() == 1 + && node.children().getFirst().name() + .equals("processor-button") + && node.children().getFirst().attributes() + .equals(Map.of("id", "toggle_0"))) { + var buttons = machine.processors().stream() + .map(config -> n(node, "processor-button", + Map.of("id", "toggle_" + config.id(), + "processor-key", config.id()), + List.of())) + .toList(); + return new Node(node.name(), node.attributes(), buttons, + node.source(), node.line(), node.namespace()); + } if (machine != null && node.tag().equals(ScreenTags.name("machine-upgrades"))) return upgradeSockets(machine, node); @@ -287,12 +303,10 @@ public static void validate(MachineDefinition machine, Screen screen) { Map.of("processors", !machine.hasProcessor() ? Set.of() - : Set.of(machine.processor()))); - Map> declared = machine.behavior() - .processor() == null - ? Map.of() - : Map.of(machine.processor(), - machine.behavior().processor().schema(machine.processor())); + : machine.processors().stream() + .map(ProcessorConfiguration::id) + .collect(java.util.stream.Collectors.toSet()))); + Map> declared = machine.processorSchemas(); var defaults = machine.visualDefaults( machine.hasProcessor() ? declared.get(machine.processor()) : null); for (var element : screen.elements()) { @@ -355,12 +369,21 @@ private static void options(Node node, Set allowed) { "Unknown generator option " + key); } - private static Node progress(MachineDefinition machine, Node node) { - return n(node, "progress", - Map.of("id", "generated_progress", "value", "#getProgress", "max", - "#getTime", "jei-recipes", - machine.recipeType().id().toString()), - List.of()); + private static Node progress(MachineDefinition machine, + ProcessorConfiguration config, Node node) { + return n(node, "progress", Map.of("id", + machine.processors().size() == 1 + ? "generated_progress" + : "generated_progress_" + config.id(), + "value", + machine.processors().size() == 1 + ? "#getProgress" + : "#getProgress(" + machine.processors().indexOf(config) + ")", + "max", + machine.processors().size() == 1 + ? "#getTime" + : "#getTime(" + machine.processors().indexOf(config) + ")", + "jei-recipes", config.recipeType().id().toString()), List.of()); } private static List processing(MachineDefinition machine, Node node) { @@ -374,8 +397,9 @@ private static List processing(MachineDefinition machine, Node node, var main = new ArrayList(); main.add(spacer(node)); main.addAll(groups(machine, node, IoMode.INPUT, 3, claimed)); - if (machine.processingType().isPresent()) - main.add(progress(machine, node)); + for (var config : machine.processors()) + if (config.recipeType() != null) + main.add(progress(machine, config, node)); main.addAll(groups(machine, node, IoMode.OUTPUT, 3, claimed)); main.add(spacer(node)); var rows = new ArrayList(); diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorConfiguration.java b/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorConfiguration.java new file mode 100644 index 00000000..5812ed76 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorConfiguration.java @@ -0,0 +1,36 @@ +package zone.moddev.mc.lib.machine.definition; + +import java.util.List; +import java.util.Map; + +/** + * A stable processor identity and its private view of shared physical + * resources. + */ +public record ProcessorConfiguration(String id, String name, + MachineDefinition.RecipeType recipeType, ProcessorDeclaration declaration, + Map bindings, List filterInputs, + MachineDefinition.RecipeSelection selection, + MachineDefinition.Sounds sounds, MachineDefinition.Events events, + long energyPerTick) { + public ProcessorConfiguration(String id, String name, + MachineDefinition.RecipeType recipeType, + ProcessorDeclaration declaration, Map bindings, + List filterInputs, MachineDefinition.RecipeSelection selection, + MachineDefinition.Sounds sounds, MachineDefinition.Events events) { + this(id, name, recipeType, declaration, bindings, filterInputs, + selection, sounds, events, 0); + } + public ProcessorConfiguration { + if (id == null || id.isBlank() + || (recipeType == null) == (declaration == null)) + throw new IllegalArgumentException( + "A processor needs an ID and exactly one implementation"); + if (energyPerTick < 0) + throw new IllegalArgumentException( + "Negative processor energy cost"); + bindings = java.util.Collections + .unmodifiableMap(new java.util.LinkedHashMap<>(bindings)); + filterInputs = List.copyOf(filterInputs); + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorDeclaration.java b/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorDeclaration.java index 25e54b42..0baabf89 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorDeclaration.java +++ b/src/main/java/zone/moddev/mc/lib/machine/definition/ProcessorDeclaration.java @@ -25,14 +25,25 @@ public synchronized zone.moddev.mc.lib.machine.feature.Processor schema( return schemas.computeIfAbsent(key, id -> new Schema(create(id, null))); } + /** Declared source IDs, without evaluating live redstone levels. */ + public java.util.List redstoneOutputIds(String key) { + return ((Schema) schema(key)).redstoneOutputIds; + } + private static final class Schema implements zone.moddev.mc.lib.machine.feature.Processor { private final StoredProcessor prototype; + private final java.util.List redstoneOutputIds; private final java.util.Map visuals; private final java.util.Map actions; Schema(StoredProcessor prototype) { this.prototype = prototype; + redstoneOutputIds = prototype instanceof zone.moddev.mc.lib.api.redstone.IRedstoneOutput provider + ? provider.redstoneOutputs().stream() + .map(zone.moddev.mc.lib.api.redstone.RedstoneOutput::id) + .toList() + : java.util.List.of(); var builder = new zone.moddev.mc.lib.machine.presentation.VisualVariables.Builder(); prototype.defineVisualVariables(builder); visuals = builder.build().defaults(); @@ -48,6 +59,12 @@ private static final class Schema implements public String key() { return prototype.key(); } + + public net.minecraft.core.Direction placementFacing( + net.minecraft.world.item.context.BlockPlaceContext context, + net.minecraft.core.Direction suggested) { + return prototype.placementFacing(context, suggested); + } public com.mojang.serialization.Codec codec() { return net.minecraft.nbt.CompoundTag.CODEC; } diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/FeatureHost.java b/src/main/java/zone/moddev/mc/lib/machine/feature/FeatureHost.java index 8adfe676..767e2f15 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/feature/FeatureHost.java +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/FeatureHost.java @@ -37,6 +37,7 @@ public final class FeatureHost implements IRedstoneOutput { private boolean syncPending; private int sinceSync = SYNC_INTERVAL; private ProcessorClock processorClock; + private String primaryProcessor; /** Bind a machine's installed gearboxes before binding visual variables. */ public FeatureHost gearboxes(java.util.function.IntSupplier count) { @@ -82,18 +83,34 @@ public FeatureHost add(MachineFeature feature) { return this; } + /** Selects the default processor without changing declaration order. */ + public FeatureHost primaryProcessor(String key) { + if (findProcessor(key).isEmpty()) + throw new IllegalArgumentException( + "Unknown primary processor: " + key); + primaryProcessor = key; + return this; + } + public java.util.Optional> findProcessor(String key) { return features.get(key) instanceof Processor p ? java.util.Optional.of(p) : java.util.Optional.empty(); } + /** All processor kinds in stable declaration order. */ + public List> allProcessors() { + return features.values().stream().filter(Processor.class::isInstance) + .>map(feature -> (Processor) feature).toList(); + } + public java.util.Optional findProcessor(String key, Class type) { return findProcessor(key).filter(type::isInstance).map(type::cast); } public java.util.Optional> findProcessor( java.util.Optional key) { + key = key.or(() -> java.util.Optional.ofNullable(primaryProcessor)); return key.isPresent() ? findProcessor(key.get()) : features.values().stream().filter(Processor.class::isInstance) @@ -168,11 +185,12 @@ public java.util.Optional processor(String key) { } /** - * An omitted key selects the first recipe processor in feature registration - * order. + * An omitted key selects the configured primary processor, or the first + * recipe processor in registration order when no primary is configured. */ public java.util.Optional processor( java.util.Optional key) { + key = key.or(() -> java.util.Optional.ofNullable(primaryProcessor)); return key.isPresent() ? processor(key.orElseThrow()) : features.values().stream() diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/MachinePlacement.java b/src/main/java/zone/moddev/mc/lib/machine/feature/MachinePlacement.java new file mode 100644 index 00000000..1d5136ca --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/MachinePlacement.java @@ -0,0 +1,23 @@ +package zone.moddev.mc.lib.machine.feature; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; + +import org.jetbrains.annotations.Nullable; + +/** Successful server placement, after portable state restoration. */ +public record MachinePlacement(Level level, BlockPos position, BlockState state, + @Nullable Player placer, ItemStack item) { + public MachinePlacement { + position = position.immutable(); + item = item.copy(); + } + + @Override + public ItemStack item() { + return item.copy(); + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/Processor.java b/src/main/java/zone/moddev/mc/lib/machine/feature/Processor.java index 8adadb3a..fff0bb53 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/feature/Processor.java +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/Processor.java @@ -18,6 +18,19 @@ enum ProcessState { } boolean paused(); + + /** + * Pure placement preference, also queried on a prototype without a host. + */ + default net.minecraft.core.Direction placementFacing( + net.minecraft.world.item.context.BlockPlaceContext context, + net.minecraft.core.Direction suggested) { + return suggested; + } + + /** Server callback for a successful item placement, never chunk loading. */ + default void placed(MachinePlacement placement) { + } void setPaused(boolean paused); boolean processing(); ProcessState executionStatus(); diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/ProcessorEnergy.java b/src/main/java/zone/moddev/mc/lib/machine/feature/ProcessorEnergy.java new file mode 100644 index 00000000..76aae055 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/ProcessorEnergy.java @@ -0,0 +1,29 @@ +package zone.moddev.mc.lib.machine.feature; + +import net.minecraft.core.Direction; + +import org.jetbrains.annotations.Nullable; + +import zone.moddev.mc.lib.api.capabilities.EnergyBuffer; +import zone.moddev.mc.lib.api.capabilities.IoMode; + +/** Supplies the machine's single authoritative energy store. */ +public interface ProcessorEnergy { + /** + * Called once per live machine, before resource binding. Do not access host + * resources here. The returned store stays bound for the machine's lifetime + * and is saved by the host. Custom EnergyBuffer implementations must honor + * checkpoint/consume and serialization. + */ + EnergyBuffer createEnergyStorage(long capacity, long inputRate, + long outputRate); + + /** + * Live additional restrictions, intersected with the machine's side + * settings. Null is unsided access. Returning DISABLED also affects already + * cached capability views. + */ + default IoMode energyMode(@Nullable Direction side) { + return IoMode.BOTH; + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/ProcessorMachine.java b/src/main/java/zone/moddev/mc/lib/machine/feature/ProcessorMachine.java index 29ea0283..10fa1266 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/feature/ProcessorMachine.java +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/ProcessorMachine.java @@ -8,6 +8,16 @@ * entity. */ public interface ProcessorMachine { + /** + * Named internal resource groups. Transactions preserve reservations and + * roll back unless committed; internal insertion uses product semantics. + * Available on live hosts after assembly, never on declaration prototypes. + */ + default zone.moddev.mc.lib.machine.inventory.MachineInventory resources() { + throw new UnsupportedOperationException( + "Host has no processing resources"); + } + Level level(); BlockPos position(); void changed(); diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeCycle.java b/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeCycle.java index aad4f0fc..0d34c2c1 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeCycle.java +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeCycle.java @@ -124,27 +124,62 @@ public Result advance(RandomSource random) { return Result.COMPLETED; } + /** + * Adds operating energy to each successful step in the same transaction as + * recipe energy. A blocked last step rolls back its charge and progress. + * Zero preserves legacy behavior. + */ + public Result advance(RandomSource random, String energyGroup, + long operatingCost) { + if (operatingCost < 0) + throw new IllegalArgumentException("Negative operating cost"); + if (operatingCost == 0) + return advance(random); + Objects.requireNonNull(random); + if (plan == null) + return Result.IDLE; + boolean advance = progress < plan.time(); + boolean finishing = !advance || progress + 1 == plan.time(); + try (var tx = inventory.begin()) { + if (advance) { + if (!(inventory.group(energyGroup) + .orElse(null) instanceof EnergyGroup group) + || group.consume(operatingCost, tx) != operatingCost + || !draw(tx)) + return Result.STALLED; + } + if (finishing && !plan.finish(inventory, random, tx)) + return Result.BLOCKED; + tx.commit(); + } + if (finishing) { + plan = null; + progress = 0; + return Result.COMPLETED; + } + progress++; + return Result.RUNNING; + } + private boolean draw() { + try (var tx = inventory.begin()) { + if (!draw(tx)) + return false; + tx.commit(); + return true; + } + } + + private boolean draw(zone.moddev.mc.lib.machine.inventory.MachineTx tx) { for (var need : plan.energy().entrySet()) { long share = EnergySchedule.share(need.getValue(), plan.time(), progress); if (!(inventory.group(need.getKey()) .orElse(null) instanceof EnergyGroup group) - || group.stored() < share) + || group.consume(share, tx) != share) return false; } - try (var tx = inventory.begin()) { - for (var need : plan.energy().entrySet()) { - long share = EnergySchedule.share(need.getValue(), plan.time(), - progress); - if (!(inventory.group(need.getKey()) - .orElse(null) instanceof EnergyGroup group) - || group.consume(share, tx) < share) - return false; - } - tx.commit(); - return true; - } + return true; } /** Release claims while retaining paid progress for an explicit resume. */ diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeProcessor.java b/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeProcessor.java index fd49c0e0..00296067 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeProcessor.java +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/RecipeProcessor.java @@ -252,6 +252,32 @@ public MatchResult recipeAvailability(MachineRecipeEntry entry) { private Status status = Status.IDLE; private java.math.BigInteger completedCycles = java.math.BigInteger.ZERO; private long startedCycles; + private long operatingCost; + /** Additional FE per successful work step, from the energy group. */ + public RecipeProcessor operatingCost(long amount) { + if (amount < 0 || amount > 0 + && !(inventory.group("energy").orElse(null) instanceof EnergyGroup)) + throw new IllegalArgumentException( + "Operating cost requires an energy group and a nonnegative amount"); + operatingCost = amount; + return this; + } + private java.util.function.Consumer onStart = cycle -> { + }; + private java.util.function.Consumer onFinish = cycle -> { + }; + + /** + * Called once for each real transition, including accelerated work steps. + * Resume/load never replays a start; failed/aborted cycles never finish. + */ + public RecipeProcessor cycleCallbacks( + java.util.function.Consumer start, + java.util.function.Consumer finish) { + onStart = java.util.Objects.requireNonNull(start); + onFinish = java.util.Objects.requireNonNull(finish); + return this; + } private final Component displayName; /** @@ -341,6 +367,13 @@ private static String outputPrefix(String key) { } } + /** Stable source IDs available before a runtime recipe processor exists. */ + public static List redstoneOutputIds(String key) { + var prefix = outputPrefix(key); + return List.of(prefix + "/processing", prefix + "/inactive", + prefix + "/progress"); + } + private RedstoneOutput output(String kind, Component name, String icon, int colour, IntSupplier value) { return new RedstoneOutput(outputPrefix + "/" + kind, @@ -583,6 +616,10 @@ public Statistics statistics() { java.math.BigInteger.valueOf(peak))); } } + if (plan != null && operatingCost > 0 && inventory.group("energy") + .orElse(null) instanceof EnergyGroup group) + uses.add(new Statistics.EnergyUse(group.statisticsResource(), + java.math.BigInteger.valueOf(operatingCost))); return new Statistics(displayName, java.util.List.of( Statistics.cycles("cycles", @@ -688,7 +725,7 @@ private void run(FeatureHost host) { } var active = activePlan(); int before = progress(); - var result = runner.advance(level.getRandom()); + var result = runner.advance(level.getRandom(), "energy", operatingCost); status = switch (result) { case IDLE, COMPLETED -> Status.IDLE; case RUNNING -> Status.RUNNING; @@ -698,6 +735,7 @@ private void run(FeatureHost host) { if (result == RecipeCycle.Result.COMPLETED) { completedCycles = completedCycles.add(java.math.BigInteger.ONE); justFinished = active; + onFinish.accept(active); } if (progress() != before || result == RecipeCycle.Result.COMPLETED) { progressChanges.changed(); @@ -754,6 +792,7 @@ private void start(Level level, FeatureHost host) { progressChanges.changed(); startedCycles++; host.markChanged(); + onStart.accept(activePlan()); } } diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/StorageAdmission.java b/src/main/java/zone/moddev/mc/lib/machine/feature/StorageAdmission.java new file mode 100644 index 00000000..ef5c4815 --- /dev/null +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/StorageAdmission.java @@ -0,0 +1,23 @@ +package zone.moddev.mc.lib.machine.feature; + +import net.minecraft.world.item.ItemStack; + +import zone.moddev.mc.lib.machine.ingredient.FluidAmount; + +/** + * Mod-owned external insertion rules, evaluated against current config/recipes. + * Queries must not mutate the host; they also run during simulated transfers. + * The member is its stable XML slot/tank ID. The host may have no level yet. + * Inputs are detached. Existing contents remain extractable when rules change. + */ +public interface StorageAdmission { + default boolean acceptsItem(ProcessorMachine host, String member, + ItemStack stack) { + return false; + } + + default boolean acceptsFluid(ProcessorMachine host, String member, + FluidAmount fluid) { + return false; + } +} diff --git a/src/main/java/zone/moddev/mc/lib/machine/feature/StoredProcessor.java b/src/main/java/zone/moddev/mc/lib/machine/feature/StoredProcessor.java index ce69267c..ea2c0f2c 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/feature/StoredProcessor.java +++ b/src/main/java/zone/moddev/mc/lib/machine/feature/StoredProcessor.java @@ -12,7 +12,8 @@ * Base for processors with observable state shared by ticks and declared * actions. */ -public abstract class StoredProcessor implements Processor { +public abstract class StoredProcessor implements Processor, + zone.moddev.mc.lib.api.stats.StatsProvider { private static final org.slf4j.Logger LOGGER = com.mojang.logging.LogUtils .getLogger(); /** Reserved metadata; variable names cannot contain a colon. */ @@ -31,6 +32,53 @@ public abstract class StoredProcessor implements Processor { private final ProcessorState.Key held = variables.define("held", Codec.BOOL, false); private String key; + private long operatingCost; + /** + * Additional FE per successful work step. Resources are bound before + * ticking. + */ + public final StoredProcessor operatingCost(long amount) { + if (amount < 0) + throw new IllegalArgumentException("Negative operating cost"); + operatingCost = amount; + return this; + } + + @Override + public zone.moddev.mc.lib.api.stats.Statistics statistics() { + if (operatingCost == 0 || machine == null) + return zone.moddev.mc.lib.api.stats.Statistics.EMPTY; + var energy = machine.resources().energy("energy"); + return new zone.moddev.mc.lib.api.stats.Statistics(displayName(), + java.util.List.of(), + java.util.List + .of(new zone.moddev.mc.lib.api.stats.Statistics.EnergyUse( + energy.statisticsResource(), + java.math.BigInteger.valueOf(operatingCost)))); + } + + /** + * Whether this step performed work. Override if completion returns IDLE + * after doing work. + */ + protected boolean performedWork(ProcessState result) { + return result == ProcessState.RUNNING; + } + + private ProcessState processWithCost() { + if (operatingCost == 0) + return process(variables, machine, 1); + var resources = machine.resources(); + try (var tx = resources.begin()) { + if (resources.energy("energy").consume(operatingCost, + tx) != operatingCost) + return ProcessState.STALLED; + var result = process(variables, machine, 1); + if (performedWork(result)) + tx.commit(); + return result; + } + } protected ProcessorMachine machine; public final void initialize(String id, ProcessorMachine context) { @@ -44,6 +92,18 @@ public final void initialize(String id, ProcessorMachine context) { }); } + @Override + public final void placed(MachinePlacement placement) { + variables.update(() -> onPlaced(placement)); + } + + /** + * Successful placement inside a state operation; mutations synchronize + * once. + */ + protected void onPlaced(MachinePlacement placement) { + } + public abstract boolean canStart(ProcessorState state, ProcessorMachine context); /** @@ -195,7 +255,7 @@ public final void tick(FeatureHost host) { if (!active) idle(variables, machine, 1); var next = active || canStart(variables, machine) - ? process(variables, machine, 1) + ? processWithCost() : ProcessState.IDLE; variables.set(status, next.name()); }); diff --git a/src/main/java/zone/moddev/mc/lib/machine/inventory/MachineInventory.java b/src/main/java/zone/moddev/mc/lib/machine/inventory/MachineInventory.java index 6d0f0d72..094003fb 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/inventory/MachineInventory.java +++ b/src/main/java/zone/moddev/mc/lib/machine/inventory/MachineInventory.java @@ -35,6 +35,29 @@ public Optional group(String key) { return Optional.ofNullable(groups.get(key)); } + /** + * Named typed groups, with an explicit error for absent/wrong-kind keys. + */ + public ItemGroup items(String key) { + return require(key, ItemGroup.class); + } + + public FluidGroup fluids(String key) { + return require(key, FluidGroup.class); + } + + public EnergyGroup energy(String key) { + return require(key, EnergyGroup.class); + } + + private T require(String key, Class type) { + var group = groups.get(key); + if (!type.isInstance(group)) + throw new IllegalArgumentException( + "Expected " + type.getSimpleName() + " group: " + key); + return type.cast(group); + } + /** Every group key, in the order added. */ public Set keys() { return groups.keySet(); @@ -45,6 +68,20 @@ public MachineTx begin() { return new SnapshotTx(); } + /** + * Aliases share the same groups and physical transaction/reservation + * identity. + */ + public MachineInventory view(Map bindings) { + if (bindings.isEmpty()) + return this; + var builder = builder(); + bindings.forEach((alias, target) -> builder.group(alias, + group(target).orElseThrow(() -> new IllegalArgumentException( + "Unknown resource group: " + target)))); + return builder.build(); + } + /** Captures the groups' change counters for a failed recipe search. */ public long[] revisions() { return groups.values().stream().mapToLong(SlotGroup::revision) @@ -72,8 +109,7 @@ private Builder() { /** * Adds {@code group} under {@code key}. * - * @throws IllegalArgumentException - * if {@code key} is already used + * @throws IllegalArgumentException if {@code key} is already used */ public Builder group(String key, SlotGroup group) { if (groups.putIfAbsent(key, group) != null) diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java index d767cea3..892bbb50 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/BaseMachine.java @@ -143,6 +143,23 @@ public int getTime() { .map(RecipeProcessor::time).orElse(0); } + /** Generated multi-lane bindings use stable declaration-order indexes. */ + public int getProgress(int processorIndex) { + var processors = features.allProcessors(); + return processorIndex >= 0 && processorIndex < processors.size() + && processors.get(processorIndex) instanceof RecipeProcessor recipe + ? recipe.progress() + : 0; + } + + public int getTime(int processorIndex) { + var processors = features.allProcessors(); + return processorIndex >= 0 && processorIndex < processors.size() + && processors.get(processorIndex) instanceof RecipeProcessor recipe + ? recipe.time() + : 0; + } + public boolean getPaused() { return features.findProcessor(java.util.Optional.empty()) .map(zone.moddev.mc.lib.machine.feature.Processor::paused) diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineBlock.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineBlock.java index b5d157b4..5c3aa58e 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineBlock.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineBlock.java @@ -29,21 +29,62 @@ import zone.moddev.mc.lib.common.runtime.DropsContents; /** Standard placement, interaction and lifecycle hooks for XML machines. */ -public final class DefinedMachineBlock extends Block implements EntityBlock { +public class DefinedMachineBlock extends Block implements EntityBlock { private final Supplier> type; + private final zone.moddev.mc.lib.machine.definition.MachineFacing facing; + private zone.moddev.mc.lib.machine.feature.Processor placementPrototype; + private boolean comparator; + + public static DefinedMachineBlock create(Properties properties, + Supplier> type, + zone.moddev.mc.lib.machine.definition.MachineDefinition definition) { + var facing = definition.behavior().facing(); + var block = facing.horizontal() + ? new DefinedMachineBlock(properties, type, facing) + : new SixWay(properties, type, facing); + if (definition.behavior().processor() != null) + block.placementPrototype = definition.behavior().processor() + .schema(definition.processor()); + block.comparator = definition.behavior().comparatorSource() != null; + return block; + } + + private static final class SixWay extends DefinedMachineBlock { + SixWay(Properties properties, + Supplier> type, + zone.moddev.mc.lib.machine.definition.MachineFacing facing) { + super(properties, type, facing); + } + @Override + protected net.minecraft.world.level.block.state.properties.DirectionProperty facingProperty() { + return BlockStateProperties.FACING; + } + } + + protected net.minecraft.world.level.block.state.properties.DirectionProperty facingProperty() { + return BlockStateProperties.HORIZONTAL_FACING; + } public DefinedMachineBlock(Properties properties, Supplier> type) { + this(properties, type, + zone.moddev.mc.lib.machine.definition.MachineFacing.DEFAULT); + } + + private DefinedMachineBlock(Properties properties, + Supplier> type, + zone.moddev.mc.lib.machine.definition.MachineFacing facing) { super(properties); this.type = type; - registerDefaultState(stateDefinition.any() - .setValue(BlockStateProperties.HORIZONTAL_FACING, Direction.NORTH)); + this.facing = facing; + registerDefaultState(stateDefinition.any().setValue(facingProperty(), + facing.defaultDirection())); } @Override protected void createBlockStateDefinition( StateDefinition.Builder builder) { - builder.add(BlockStateProperties.HORIZONTAL_FACING); + builder.add(facingProperty()); } @Override @@ -56,21 +97,29 @@ protected void tick(BlockState state, @Override public BlockState getStateForPlacement(BlockPlaceContext context) { - return defaultBlockState().setValue( - BlockStateProperties.HORIZONTAL_FACING, - context.getHorizontalDirection().getOpposite()); + var selected = facing.placement(context.getNearestLookingDirections()); + if (placementPrototype != null) { + var proposed = placementPrototype.placementFacing(context, + selected); + if (!facing.directions().contains(proposed)) + throw new IllegalArgumentException( + "Processor selected a forbidden facing: " + proposed); + selected = proposed; + } + return defaultBlockState().setValue(facingProperty(), selected); } @Override public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(BlockStateProperties.HORIZONTAL_FACING, rotation - .rotate(state.getValue(BlockStateProperties.HORIZONTAL_FACING))); + return state.setValue(facingProperty(), + facing.transformed(state.getValue(facingProperty()), + rotation.rotate(state.getValue(facingProperty())))); } @Override public BlockState mirror(BlockState state, Mirror mirror) { - return rotate(state, mirror.getRotation( - state.getValue(BlockStateProperties.HORIZONTAL_FACING))); + return rotate(state, + mirror.getRotation(state.getValue(facingProperty()))); } @Override @@ -170,6 +219,8 @@ protected void onPlace(BlockState state, Level level, BlockPos pos, @Override protected void onRemove(BlockState state, Level level, BlockPos pos, BlockState replacement, boolean moved) { + if (comparator && !state.is(replacement.getBlock())) + level.updateNeighbourForOutputSignal(pos, this); if (!level.restoringBlockSnapshots) DropsContents.onRemove(state, level, pos, replacement); super.onRemove(state, level, pos, replacement, moved); @@ -192,8 +243,21 @@ protected net.minecraft.world.phys.shapes.VoxelShape getShape( if (!(world.getBlockEntity(pos) instanceof DefinedMachineEntity host) || host.definition.behavior().shapes().isEmpty()) return super.getShape(state, world, pos, context); - return host - .shape(state.getValue(BlockStateProperties.HORIZONTAL_FACING)); + return host.shape(state.getValue(facingProperty())); + } + + @Override + protected boolean hasAnalogOutputSignal(BlockState state) { + return comparator; + } + + @Override + protected int getAnalogOutputSignal(BlockState state, Level level, + BlockPos pos) { + return level.getBlockEntity(pos) instanceof DefinedMachineEntity machine + && machine.screenRedstone() != null + ? machine.screenRedstone().comparatorLevel() + : 0; } @Override diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineEntity.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineEntity.java index 56a70a6c..d5bcd149 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineEntity.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineEntity.java @@ -32,36 +32,124 @@ public final class DefinedMachineEntity extends BaseMachine implements zone.moddev.mc.lib.machine.feature.ProcessorMachine, zone.moddev.mc.lib.machine.presentation.VisualizerStyle.Provider { public final MachineDefinition definition; + private final List processorConfigurations; + + public List processorConfigurations() { + return processorConfigurations; + } private Runnable placementComplete; + private boolean placementNotified; + private final java.util.Map admissionRules = new java.util.HashMap<>(); public final ItemInventories items; public final FluidStorage fluids; public final EnergyBuffer energy; + private final zone.moddev.mc.lib.machine.feature.ProcessorEnergy energyProvider; private final List rangeSlots; public final MachineResources resources; public final MachineInventoryLifecycle inventory; + + @Override + public zone.moddev.mc.lib.machine.inventory.MachineInventory resources() { + return resources.recipes(); + } private final RedstoneControl redstone; private final MachineVisualState visuals; private final MachineShapeState shapes; private ResourceLocation legacyGhostRecipe; private final java.util.Map ghosts = new java.util.LinkedHashMap<>(); - private final RecipeProcessor processor; - private final zone.moddev.mc.lib.machine.feature.WorkTargets workTargets; - private java.math.BigInteger cyclesBefore = java.math.BigInteger.ZERO; - private long startsBefore; + private final java.util.Map workTargets = new java.util.LinkedHashMap<>(); + + private MachineRecipeType recipeType( + zone.moddev.mc.lib.machine.definition.ProcessorConfiguration config, + MachineRecipeType primary) { + return primary != null && primary.id().equals(config.recipeType().id()) + ? primary + : MachineContent.recipeType(config.recipeType().id()); + } + + private void linkRecipeAdmission(MachineRecipeType primary) { + for (var config : processorConfigurations) + if (config.recipeType() != null) + resources.recipeInputs(recipeType(config, primary), + config.bindings(), + config.filterInputs().toArray(String[]::new)); + } + + /** Stable capability views evaluate both policies on every call. */ + public net.neoforged.neoforge.energy.IEnergyStorage energyCapability( + @org.jetbrains.annotations.Nullable net.minecraft.core.Direction side) { + return energy == null ? null : energy.view(() -> { + var configured = side == null + ? (energyProvider == null ? IoMode.INPUT : IoMode.BOTH) + : resources.automation().mode(ResourceType.ENERGY, 0, side); + var supplied = energyProvider == null + ? IoMode.BOTH + : energyProvider.energyMode(side); + boolean input = configured.canInsert() && supplied.canInsert(); + boolean output = configured.canExtract() && supplied.canExtract(); + return input + ? (output ? IoMode.BOTH : IoMode.INPUT) + : (output ? IoMode.OUTPUT : IoMode.DISABLED); + }); + } + + private void prepareAdmission( + zone.moddev.mc.lib.machine.definition.AdmissionDeclaration declaration) { + if (declaration.type() != null) + admissionRules.computeIfAbsent(declaration, key -> key.create()); + } + + private zone.moddev.mc.lib.machine.feature.StorageAdmission admission( + zone.moddev.mc.lib.machine.definition.AdmissionDeclaration declaration) { + if (declaration.processor() == null) + return admissionRules.get(declaration); + return features + .findProcessor(declaration.processor(), + zone.moddev.mc.lib.machine.feature.StorageAdmission.class) + .orElseThrow(() -> new IllegalStateException( + "Missing admission processor " + declaration.processor())); + } public DefinedMachineEntity(BlockEntityType type, BlockPos pos, BlockState state, MachineDefinition definition, MachineRecipeType recipes) { super(type, pos, state); this.definition = definition; + processorConfigurations = definition.processors(); // Startup validates registered XML; keep direct Java construction // equally strict. MachineContent.validateResources(definition); var power = definition.power(); - energy = power == null - ? null - : new EnergyBuffer(power.capacity(), power.input(), power.output()) - .onChange(this::setChanged); + var customProcessors = new java.util.HashMap>(); + if (power != null && power.provider() != null) { + var config = processorConfigurations.stream() + .filter(value -> value.id().equals(power.provider())) + .findFirst().orElseThrow(() -> new IllegalArgumentException( + "Unknown energy provider: " + power.provider())); + if (config.declaration() == null) + throw new IllegalArgumentException( + "Energy provider must be a custom processor"); + var provider = config.declaration().create(config.id(), this); + if (!(provider instanceof zone.moddev.mc.lib.machine.feature.ProcessorEnergy source)) + throw new IllegalArgumentException( + "Energy provider must implement ProcessorEnergy"); + customProcessors.put(config.id(), provider); + energyProvider = source; + energy = java.util.Objects + .requireNonNull(source.createEnergyStorage(power.capacity(), + power.input(), power.output()), "Processor energy storage"); + energy.changes().subscribe(this::setChanged); + } else { + energyProvider = null; + energy = power == null + ? null + : new EnergyBuffer(power.capacity(), power.input(), + power.output()).onChange(this::setChanged); + } + if (power != null && !power.capacitors() + && definition.behavior().capacitorSlot() != null) + throw new IllegalArgumentException( + "Selected energy provider does not enable capacitor upgrades"); fluids = new FluidStorage().onChange(this::setChanged); if (definition.fluids() != null) for (var tank : definition.fluids().tanks()) { @@ -74,6 +162,22 @@ public DefinedMachineEntity(BlockEntityType type, BlockPos pos, stack -> filter == null || BuiltInRegistries.FLUID .getKey(stack.getFluid()).equals(filter)); fluids.tankId(index, tank.id()); + if (tank.fluidTag() != null) { + var tag = net.minecraft.tags.TagKey.create( + net.minecraft.core.registries.Registries.FLUID, + tank.fluidTag()); + fluids.restrict(stack -> stack.is(tag), index); + } + if (tank.admission() != null) { + prepareAdmission(tank.admission()); + fluids.restrict( + stack -> admission(tank.admission()).acceptsFluid(this, + tank.id(), + new zone.moddev.mc.lib.machine.ingredient.FluidAmount( + stack.getFluidHolder(), + stack.getComponentsPatch(), stack.getAmount())), + index); + } } items = ItemInventories.partition(definition.inventoryNames()) .onChange(this::setChanged); @@ -81,6 +185,11 @@ public DefinedMachineEntity(BlockEntityType type, BlockPos pos, var slot = definition.slots().get(i); items.slotId(i, slot.id()).role(slot.role(), i).limit(slot.limit(), i); + if (slot.admission() != null) { + prepareAdmission(slot.admission()); + items.restrict(stack -> admission(slot.admission()) + .acceptsItem(this, slot.id(), stack.copy()), i); + } if (slot.itemTag() != null) { var tag = net.minecraft.tags.TagKey.create( net.minecraft.core.registries.Registries.ITEM, @@ -167,9 +276,8 @@ public DefinedMachineEntity(BlockEntityType type, BlockPos pos, var highlights = MachineContent.screenHighlights(definition.id()); for (var group : definition.groups()) { if (!group.automation()) { - resources.recipeOnlyGroup(group.id(), - StorageGroups.items(items, group.members().stream() - .mapToInt(Integer::intValue).toArray())); + resources.recipeOnlyItems(group.id(), items, group.members() + .stream().mapToInt(Integer::intValue).toArray()); continue; } resources @@ -193,9 +301,9 @@ public DefinedMachineEntity(BlockEntityType type, BlockPos pos, if (definition.fluids() != null) for (var group : definition.fluids().groups()) { if (!group.automation()) { - resources.recipeOnlyGroup(group.id(), - StorageGroups.fluids(fluids, group.members().stream() - .mapToInt(Integer::intValue).toArray())); + resources.recipeOnlyFluids(group.id(), fluids, + group.members().stream().mapToInt(Integer::intValue) + .toArray()); continue; } resources.fluids(new ResourceGroup<>(group.id(), @@ -203,12 +311,9 @@ public DefinedMachineEntity(BlockEntityType type, BlockPos pos, ResourceType.FLUIDS, group.mode(), group.members(), highlights.get(group.id()), new SideConfig(group.mode())), fluids); - if (recipes != null && group.mode() == IoMode.INPUT) - resources.recipeInputs(recipes, group.id()); + } - for (var group : definition.groups()) - if (recipes != null && group.mode() == IoMode.INPUT) - resources.recipeInputs(recipes, group.id()); + for (var ghost : definition.ghosts()) { var samples = new zone.moddev.mc.lib.machine.inventory.GhostItemGroup( ghost.count()); @@ -220,46 +325,61 @@ public DefinedMachineEntity(BlockEntityType type, BlockPos pos, ghosts.put(ghost.id(), samples); resources.recipeOnlyGroup(ghost.id(), samples); } + linkRecipeAdmission(recipes); resources.build(); - zone.moddev.mc.lib.machine.feature.Processor visualProcessor = null; - RecipeProcessor recipeProcessor = null; - if (definition.behavior().processor() != null) { - visualProcessor = definition.behavior().processor() - .create(definition.processor(), this); - features.add(visualProcessor); - } else if (definition.hasProcessor()) { - recipeProcessor = new RecipeProcessor(definition.processor(), - recipes, resources.recipes(), - Component.literal(definition.processorName())); - if (definition.recipeSelection() != null) - recipeProcessor - .selectable(definition.recipeSelection().defaultRecipe()); - features.add(recipeProcessor); - visualProcessor = recipeProcessor; + var runtimeProcessors = new java.util.LinkedHashMap>(); + for (var config : processorConfigurations) { + zone.moddev.mc.lib.machine.feature.Processor value; + if (config.declaration() != null) + value = customProcessors.computeIfAbsent(config.id(), + ignored -> config.declaration().create(config.id(), this)); + else { + var typeForProcessor = recipeType(config, recipes); + var lane = new RecipeProcessor(config.id(), typeForProcessor, + resources.recipes().view(config.bindings()), + Component.literal(config.name())); + if (config.selection() != null) + lane.selectable(config.selection().defaultRecipe()); + bindCycleCallbacks(lane, config); + value = lane; + } + if (value instanceof RecipeProcessor lane) + lane.operatingCost(config.energyPerTick()); + else if (value instanceof zone.moddev.mc.lib.machine.feature.StoredProcessor custom) + custom.operatingCost(config.energyPerTick()); + features.add(value); + runtimeProcessors.put(config.id(), value); + if (value instanceof zone.moddev.mc.lib.machine.feature.WorkTargets.Provider provider) { + var targets = new zone.moddev.mc.lib.machine.feature.WorkTargets( + config.id().equals(definition.processor()) + ? "mmdlib:work_targets" + : "mmdlib:work_targets/" + config.id(), + provider::workingBlocks, value::processing); + workTargets.put(config.id(), targets); + features.add(targets); + } } - // Cycle sounds follow recipe processors; custom ones have none. - processor = recipeProcessor; - workTargets = visualProcessor instanceof zone.moddev.mc.lib.machine.feature.WorkTargets.Provider provider - ? new zone.moddev.mc.lib.machine.feature.WorkTargets( - "mmdlib:work_targets", provider::workingBlocks, - visualProcessor::processing) - : null; - if (workTargets != null) - features.add(workTargets); + if (definition.processor() != null) + features.primaryProcessor(definition.processor()); inventory = genericInventory(resources.automation()); if (definition.itemStorageId() != null) inventory.items(definition.itemStorageId(), items); if (definition.fluids() != null) inventory.fluids(definition.fluids().id(), fluids); redstone = definition.redstone() - ? new RedstoneControl(this, List.of(features)) - : null; - var visualSource = visualProcessor; + || definition.behavior().comparatorSource() != null + ? new RedstoneControl(this, List.of(features)) + .comparatorSource(definition.behavior().comparatorSource()) + : null; + if (redstone != null && !definition.redstone()) + redstone.disabledFaces(java.util.EnumSet + .allOf(zone.moddev.mc.lib.api.capabilities.RelativeFace.class)); + var graph = new VisualVariables[1]; java.util.function.Supplier sharedVariables = () -> { if (graph[0] == null) - graph[0] = BuiltinVisualVariables.forMachine(definition, - visualSource, items, fluids, energy); + graph[0] = BuiltinVisualVariables.forProcessors(definition, + runtimeProcessors, items, fluids, energy); return graph[0]; }; features.bindVisualVariables(sharedVariables); @@ -327,17 +447,36 @@ public boolean removed() { void afterPlacement(Runnable action) { // NeoForge confirms captured placements through Block.onPlace only // after the placement event accepts them. - if (level != null && level.captureBlockSnapshots) - placementComplete = action; - else + if (level != null && level.captureBlockSnapshots) { + var previous = placementComplete; + placementComplete = () -> { + if (previous != null) + previous.run(); + action.run(); + }; + } else action.run(); } void completePlacement() { var action = placementComplete; placementComplete = null; - if (action != null) + if (action != null && level != null && !isRemoved() + && level.getBlockEntity(worldPosition) == this) action.run(); } + void notifyPlacement(net.minecraft.world.entity.player.Player placer, + net.minecraft.world.item.ItemStack item) { + if (placementNotified || level == null || level.isClientSide() + || isRemoved()) + return; + placementNotified = true; + var placement = new zone.moddev.mc.lib.machine.feature.MachinePlacement( + level, worldPosition, getBlockState(), placer, item); + features.allProcessors() + .forEach(processor -> processor.placed(placement)); + setChanged(); + } + public void changed() { changed(true); } @@ -379,6 +518,17 @@ public zone.moddev.mc.lib.api.automation.AutomationInventory screenAutomation() @Override public void onLoad() { super.onLoad(); + if (level != null && !level.isClientSide() && !definition.behavior() + .facing().directions().contains(facing())) { + var property = getBlockState().hasProperty( + net.minecraft.world.level.block.state.properties.BlockStateProperties.FACING) + ? net.minecraft.world.level.block.state.properties.BlockStateProperties.FACING + : net.minecraft.world.level.block.state.properties.BlockStateProperties.HORIZONTAL_FACING; + level.setBlock(worldPosition, + getBlockState().setValue(property, + definition.behavior().facing().defaultDirection()), + net.minecraft.world.level.block.Block.UPDATE_CLIENTS); + } if (level != null && !level.isClientSide) features .findProcessor(definition.processor(), @@ -529,52 +679,38 @@ public net.neoforged.neoforge.client.model.data.ModelData getModelData() { * sent. */ public boolean running() { - return processor != null - && processor.status() == RecipeProcessor.Status.RUNNING; - } - - @Override - protected void beforeMachineTick() { - if (processor == null) - return; - cyclesBefore = processor.completedCycles(); - startsBefore = processor.startedCycles(); + return features.processors().stream().anyMatch( + value -> value.status() == RecipeProcessor.Status.RUNNING); } - /** - * Runs the processor's {@code on-start} and {@code on-finish} handlers, and - * plays the {@code finish-sound} for everyone near a completed cycle. - */ - @Override - protected void afterMachineTick() { - if (processor == null - || !(level instanceof net.minecraft.server.level.ServerLevel server)) - return; - if (processor.startedCycles() != startsBefore) - definition.events().start() - .ifPresent(id -> processor.cycle().ifPresent(cycle -> fire(id, + private void bindCycleCallbacks(RecipeProcessor lane, + zone.moddev.mc.lib.machine.definition.ProcessorConfiguration config) { + lane.cycleCallbacks(cycle -> { + if (level instanceof net.minecraft.server.level.ServerLevel server) + config.events().start().ifPresent(id -> fire(id, zone.moddev.mc.lib.api.MaterialEventTypes.MACHINE_CYCLE_START, - server, cycle))); - if (processor.completedCycles().equals(cyclesBefore)) - return; - definition.sounds().finish() - .ifPresent(sound -> level.playSound(null, worldPosition, - SoundDefinition.event(sound), SoundSource.BLOCKS, 1, 1)); - definition.events().finish().ifPresent(id -> processor.justFinished() - .ifPresent(cycle -> fire(id, + server, config.id(), cycle)); + }, cycle -> { + if (!(level instanceof net.minecraft.server.level.ServerLevel server)) + return; + config.sounds().finish() + .ifPresent(sound -> server.playSound(null, worldPosition, + SoundDefinition.event(sound), SoundSource.BLOCKS, 1, 1)); + config.events().finish().ifPresent(id -> fire(id, zone.moddev.mc.lib.api.MaterialEventTypes.MACHINE_CYCLE_FINISH, - server, cycle))); + server, config.id(), cycle)); + }); } private void fire(ResourceLocation id, zone.moddev.mc.lib.api.MaterialEvent event, - net.minecraft.server.level.ServerLevel server, + net.minecraft.server.level.ServerLevel server, String processor, zone.moddev.mc.lib.machine.recipe.CyclePlan cycle) { zone.moddev.mc.lib.api.MaterialExtensions.GLOBAL.events().dispatch(id, event, new zone.moddev.mc.lib.api.MaterialEventContexts.MachineCycle(this, server, worldPosition, definition.id(), cycle.recipe(), - cycle.time())); + cycle.time(), processor)); } /** @@ -582,14 +718,16 @@ private void fire(ResourceLocation id, * client tick. */ public void clientTick() { - if (definition.sounds().running().isPresent()) - zone.moddev.mc.lib.client.MachineSoundsClient.tick(this); - if (workTargets != null - && features.findProcessor(definition.processor()) + zone.moddev.mc.lib.client.MachineSoundsClient.tick(this); + var active = workTargets.entrySet().stream() + .filter(entry -> features.findProcessor(entry.getKey()) .map(zone.moddev.mc.lib.machine.feature.Processor::processing) .orElse(false)) - zone.moddev.mc.lib.client.MachineWorkDisplay.tick(this, - workTargets.targets(), visualizerStyle().workColor()); + .flatMap(entry -> entry.getValue().targets().stream()).distinct() + .toList(); + if (!active.isEmpty()) + zone.moddev.mc.lib.client.MachineWorkDisplay.tick(this, active, + visualizerStyle().workColor()); } public zone.moddev.mc.lib.machine.presentation.VisualizerStyle visualizerStyle() { @@ -601,7 +739,8 @@ public zone.moddev.mc.lib.machine.presentation.VisualizerStyle visualizerStyle() * provider. */ public List workingBlocks() { - return workTargets == null ? List.of() : workTargets.targets(); + return workTargets.values().stream() + .flatMap(targets -> targets.targets().stream()).distinct().toList(); } @Override @@ -653,10 +792,20 @@ protected MachineInventoryLifecycle machineInventory() { public int[] screenRecipeSlots(ResourceLocation category) { if (!definition.processes(category)) return new int[0]; + var targets = new java.util.HashSet(); + for (var config : processorConfigurations) + if (config.recipeType() != null + && config.recipeType().id().equals(category)) { + if (config.bindings().isEmpty()) + definition.groups() + .forEach(group -> targets.add(group.id())); + else + targets.addAll(config.bindings().values()); + } return definition.groups().stream() - .filter(g -> g.mode() == IoMode.INPUT) - .flatMap(g -> g.members().stream()).mapToInt(Integer::intValue) - .toArray(); + .filter(g -> g.mode() == IoMode.INPUT && targets.contains(g.id())) + .flatMap(g -> g.members().stream()).distinct() + .mapToInt(Integer::intValue).toArray(); } @Override diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineItem.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineItem.java index 8799c9a1..0d77aa42 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineItem.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/DefinedMachineItem.java @@ -62,6 +62,11 @@ public InteractionResult place(BlockPlaceContext context) { }); } } + if (result.consumesAction() && !context.getLevel().isClientSide() + && context.getLevel().getBlockEntity( + context.getClickedPos()) instanceof DefinedMachineEntity host) + host.afterPlacement( + () -> host.notifyPlacement(context.getPlayer(), payload)); return result; } diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/GeneratedMachineRecipes.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/GeneratedMachineRecipes.java index 127486a6..3ad4cfc7 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/GeneratedMachineRecipes.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/GeneratedMachineRecipes.java @@ -237,13 +237,21 @@ private static void validateRecipe(RecipeHolder holder) { public static void validateGroups(MachineRecipeType type, MachineRecipe recipe) { for (var machine : MachineContent.definitions().values()) - if (machine.processes(type.id())) - validateGroups(machine, recipe); + for (var processor : machine.processors()) + if (processor.recipeType() != null + && processor.recipeType().id().equals(type.id())) + validateGroups(machine, recipe, processor.bindings()); } static void validateGroups( zone.moddev.mc.lib.machine.definition.MachineDefinition machine, MachineRecipe recipe) { + validateGroups(machine, recipe, java.util.Map.of()); + } + + private static void validateGroups( + zone.moddev.mc.lib.machine.definition.MachineDefinition machine, + MachineRecipe recipe, java.util.Map bindings) { var items = new HashSet(); machine.groups().forEach(g -> items.add(g.id())); var ghostItems = new HashSet(); @@ -251,14 +259,23 @@ static void validateGroups( var fluids = new HashSet(); if (machine.fluids() != null) machine.fluids().groups().forEach(g -> fluids.add(g.id())); - String energy = machine.power() == null ? null : machine.power().id(); + var energy = new HashSet(); + if (machine.power() != null) + energy.add(machine.power().id()); + if (!bindings.isEmpty()) { + remap(items, bindings); + remap(ghostItems, bindings); + remap(fluids, bindings); + remap(energy, bindings); + } recipe.inputs().forEach((key, parts) -> { if (!items.contains(key) && !ghostItems.contains(key) - && !fluids.contains(key) && !key.equals(energy)) + && !fluids.contains(key) && !energy.contains(key)) throw new IllegalArgumentException( machine.id() + ": unknown recipe input group " + key); var ghost = machine.ghosts().stream() - .filter(g -> g.id().equals(key)).findFirst().orElse(null); + .filter(g -> g.id().equals(bindings.getOrDefault(key, key))) + .findFirst().orElse(null); if (ghost != null && parts.stream() .mapToLong(MachineIngredient::amount).sum() > ghost.count()) throw new IllegalArgumentException( @@ -271,7 +288,7 @@ static void validateGroups( : part instanceof MachineIngredient.FluidPart ? fluids.contains(key) : part instanceof MachineIngredient.EnergyPart - && key.equals(energy); + && energy.contains(key); if (!valid) throw new IllegalArgumentException(machine.id() + ": incompatible recipe input group " + key); @@ -291,4 +308,14 @@ static void validateGroups( }); }); } + private static void remap(java.util.Set names, + java.util.Map bindings) { + var targets = java.util.Set.copyOf(names); + names.clear(); + bindings.forEach((alias, target) -> { + if (targets.contains(target)) + names.add(alias); + }); + } + } diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineContent.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineContent.java index 58f669ca..368afeb4 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineContent.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineContent.java @@ -112,14 +112,16 @@ public static Item recoveryItem() { */ private static void checkEvents(MachineDefinition machine) { var events = zone.moddev.mc.lib.api.MaterialExtensions.GLOBAL.events(); - machine.events().start() - .ifPresent(id -> checkEvent(machine, "on-start", id, + for (var config : machine.processors()) { + config.events().start().ifPresent(id -> checkEvent(machine, + "on-start", id, zone.moddev.mc.lib.api.MaterialEventTypes.MACHINE_CYCLE_START, events)); - machine.events().finish() - .ifPresent(id -> checkEvent(machine, "on-finish", id, + config.events().finish().ifPresent(id -> checkEvent(machine, + "on-finish", id, zone.moddev.mc.lib.api.MaterialEventTypes.MACHINE_CYCLE_FINISH, events)); + } } private static void checkEvent(MachineDefinition machine, String attribute, @@ -139,9 +141,8 @@ public static void load(List roots) { definitions = MachineDefinitions.load(roots); var declarations = new TreeMap(); for (var machine : definitions.values()) - machine.processingType() - .filter(MachineDefinition.RecipeType::declare) - .ifPresent(type -> { + machine.processingTypes().stream() + .filter(MachineDefinition.RecipeType::declare).forEach(type -> { var previous = declarations.putIfAbsent(type.id(), type); if (previous != null && !same(previous, type)) throw new IllegalArgumentException( @@ -150,7 +151,7 @@ public static void load(List roots) { declarations .forEach((id, type) -> recipes.put(id, new MachineRecipeType(id))); for (var machine : definitions.values()) - machine.processingType().ifPresent(type -> { + machine.processingTypes().forEach(type -> { if (!recipes.containsKey(type.id())) throw new IllegalArgumentException(machine.id() + ": recipe type must be declared in machine XML: " @@ -204,8 +205,8 @@ private static void registries(RegisterEvent event) { net.minecraft.world.level.material.PushReaction.BLOCK); if (!definition.behavior().shapes().isEmpty()) properties.dynamicShape().noOcclusion(); - var block = new DefinedMachineBlock(properties, - () -> entities.get(id)); + var block = DefinedMachineBlock.create(properties, + () -> entities.get(id), definition); helper.register(id, block); blocks.put(id, block); })); @@ -250,12 +251,7 @@ private static void capabilities(RegisterCapabilitiesEvent event) { : entity.fluids.view(index -> entity.resources.automation() .mode(ResourceType.FLUIDS, index, side))); event.registerBlockEntity(Capabilities.EnergyStorage.BLOCK, type, - (entity, side) -> entity.energy == null - ? null - : entity.energy.view(() -> side == null - ? IoMode.INPUT - : entity.resources.automation() - .mode(ResourceType.ENERGY, 0, side))); + DefinedMachineEntity::energyCapability); } } static void validateResources(MachineDefinition definition) { diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineResourcePack.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineResourcePack.java index db7603dd..db8de4f4 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineResourcePack.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineResourcePack.java @@ -167,12 +167,20 @@ else if (value instanceof Number number) item.addProperty("parent", model); put(result, id, "models/item/", item); var variants = new JsonObject(); - String[] directions = {"north", "east", "south", "west"}; - for (int i = 0; i < 4; i++) { + for (var direction : net.minecraft.core.Direction.values()) { + if (machine.behavior().facing().horizontal() + && direction.getAxis().isVertical()) + continue; var variant = new JsonObject(); variant.addProperty("model", model); - variant.addProperty("y", i * 90); - variants.add("facing=" + directions[i], variant); + variant.addProperty("x", + zone.moddev.mc.lib.machine.definition.MachineFacing + .modelX(direction)); + variant.addProperty("y", + zone.moddev.mc.lib.machine.definition.MachineFacing + .modelY(direction)); + variants.add("facing=" + direction.getSerializedName(), + variant); } var state = new JsonObject(); state.add("variants", variants); @@ -184,8 +192,8 @@ else if (value instanceof Number number) lang.addProperty(id + ".info", machine.name()); machine.groupNames().forEach((group, name) -> lang .addProperty(machine.groupTranslationKey(group), name)); - machine.processingType().filter(recipe -> recipe.declare()) - .ifPresent(recipe -> { + machine.processingTypes().stream() + .filter(recipe -> recipe.declare()).forEach(recipe -> { var recipeId = recipe.id(); languages .computeIfAbsent(recipeId.getNamespace(), diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineResources.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineResources.java index 38a86709..8f4d0d18 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineResources.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineResources.java @@ -3,11 +3,9 @@ import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Set; import java.util.function.Supplier; import net.minecraft.core.Direction; @@ -44,7 +42,13 @@ private record Binding(ResourceGroup group, Object storage) { private final Supplier facing; private final Map bindings = new LinkedHashMap<>(); private final Map> recipeBindings = new LinkedHashMap<>(); - private final Map> inputTypes = new LinkedHashMap<>(); + private record Admission(MachineRecipeType type, + Map aliases, List inputs) { + } + private final List admissions = new ArrayList<>(); + private record FilterTarget(Object storage, List members) { + } + private final Map recipeOnlyTargets = new LinkedHashMap<>(); private final Map recipeOnly = new LinkedHashMap<>(); private MachineInventory recipes; private AutomationInventory automation; @@ -166,13 +170,26 @@ public MachineResources recipeGroup(String key, String... groupIds) { */ public MachineResources recipeInputs(MachineRecipeType type, String... keys) { + return recipeInputs(type, Map.of(), keys); + } + + /** Links a lane's recipe aliases to physical input resources. */ + public MachineResources recipeInputs(MachineRecipeType type, + Map aliases, String... keys) { ensureOpen(); for (String key : keys) { - if (!recipeBindings.containsKey(key)) - throw invalid(key, "unknown recipe input group"); - inputTypes.computeIfAbsent(key, ignored -> new LinkedHashSet<>()) - .add(type); + var target = aliases.getOrDefault(key, key); + if (!aliases.isEmpty() && !aliases.containsKey(key)) + throw invalid(key, "input is not bound in this recipe view"); + var selected = inputTargets(target); + if (selected.stream() + .anyMatch(binding -> !(binding.storage instanceof ItemStore) + && !(binding.storage instanceof FluidStorage))) + throw invalid(key, + "recipe input filtering requires items or fluids"); } + admissions.add(new Admission(Objects.requireNonNull(type), + Map.copyOf(aliases), List.of(keys))); return this; } @@ -188,6 +205,37 @@ public MachineResources recipeOnlyGroup(String key, SlotGroup group) { return this; } + /** Physical items used by recipes without exposing an automation group. */ + public MachineResources recipeOnlyItems(String key, ItemStore storage, + int... members) { + recipeOnlyGroup(key, StorageGroups.items(storage, members)); + recipeOnlyTargets.put(key, new FilterTarget(storage, + java.util.Arrays.stream(members).boxed().toList())); + return this; + } + + /** Physical fluids used by recipes without exposing an automation group. */ + public MachineResources recipeOnlyFluids(String key, FluidStorage storage, + int... members) { + recipeOnlyGroup(key, StorageGroups.fluids(storage, members)); + recipeOnlyTargets.put(key, new FilterTarget(storage, + java.util.Arrays.stream(members).boxed().toList())); + return this; + } + + private List inputTargets(String key) { + if (recipeBindings.containsKey(key)) + return recipeBindings.get(key).stream() + .map(binding -> new FilterTarget(binding.storage, + binding.group.members())) + .toList(); + var physical = recipeOnlyTargets.get(key); + if (physical != null) + return List.of(physical); + throw invalid(key, + "recipe input filtering requires physical items or fluids"); + } + /** * Freezes the definitions and installs reload-aware recipe input filters. */ @@ -210,44 +258,51 @@ public MachineResources build() { recipes = builder.build(); automation = new AutomationInventory(owner, bindings.values().stream().map(Binding::group).toList()); - var filters = new RecipeInputFilters(() -> owner.getLevel(), recipes); - // Collect by physical slot before installing: overlapping recipe - // aliases accept the union. - var itemRules = new IdentityHashMap>>(); - var fluidRules = new IdentityHashMap>>(); - inputTypes.forEach((key, types) -> { - for (var binding : recipeBindings.get(key)) { - for (int member : binding.group.members()) { - var links = types.stream() - .map(type -> new RecipeInputFilters.Link(type, key)) - .toList(); - if (binding.storage instanceof ItemStore items) - itemRules - .computeIfAbsent(items, - ignored -> new LinkedHashMap<>()) - .computeIfAbsent(member, - ignored -> new ArrayList<>()) - .addAll(links); - else if (binding.storage instanceof FluidStorage fluids) - fluidRules - .computeIfAbsent(fluids, - ignored -> new LinkedHashMap<>()) - .computeIfAbsent(member, - ignored -> new ArrayList<>()) - .addAll(links); - else - throw invalid(key, - "recipe input filtering requires items or fluids"); + installRecipeAdmission(); + return this; + } + + private void installRecipeAdmission() { + // Union every lane's rules before restricting a physical slot or tank. + var itemRules = new IdentityHashMap>>>(); + var fluidRules = new IdentityHashMap>>>(); + for (var admission : admissions) { + var filters = new RecipeInputFilters(owner::getLevel, + recipes.view(admission.aliases())); + for (String alias : admission.inputs()) { + var links = List + .of(new RecipeInputFilters.Link(admission.type(), alias)); + for (var binding : inputTargets( + admission.aliases().getOrDefault(alias, alias))) { + for (int member : binding.members()) { + if (binding.storage instanceof ItemStore items) + itemRules + .computeIfAbsent(items, + ignored -> new LinkedHashMap<>()) + .computeIfAbsent(member, + ignored -> new ArrayList<>()) + .add( + stack -> filters.acceptsItem(links, stack)); + else if (binding.storage instanceof FluidStorage fluids) + fluidRules + .computeIfAbsent(fluids, + ignored -> new LinkedHashMap<>()) + .computeIfAbsent(member, + ignored -> new ArrayList<>()) + .add(stack -> filters.acceptsFluid(links, + stack)); + } } } - }); - itemRules - .forEach((storage, rules) -> rules.forEach((slot, links) -> storage - .restrict(stack -> filters.acceptsItem(links, stack), slot))); - fluidRules - .forEach((storage, rules) -> rules.forEach((tank, links) -> storage - .restrict(stack -> filters.acceptsFluid(links, stack), tank))); - return this; + } + itemRules.forEach((storage, + rules) -> rules.forEach((slot, tests) -> storage.restrict( + stack -> tests.stream().anyMatch(test -> test.test(stack)), + slot))); + fluidRules.forEach((storage, + rules) -> rules.forEach((tank, tests) -> storage.restrict( + stack -> tests.stream().anyMatch(test -> test.test(stack)), + tank))); } public MachineInventory recipes() { diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineShapeState.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineShapeState.java index 6e682e95..99233f11 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineShapeState.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineShapeState.java @@ -77,17 +77,17 @@ public VoxelShape shape(Direction facing) { private static Map rotate( MachineBehavior.Shape shape) { var result = new EnumMap(Direction.class); - double x1 = shape.x1(), z1 = shape.z1(), x2 = shape.x2(), - z2 = shape.z2(); - for (var facing : List.of(Direction.NORTH, Direction.EAST, - Direction.SOUTH, Direction.WEST)) { - result.put(facing, Shapes.box(x1 / 16, shape.y1() / 16, z1 / 16, - x2 / 16, shape.y2() / 16, z2 / 16)); - double oldX1 = x1, oldX2 = x2; - x1 = 16 - z2; - x2 = 16 - z1; - z1 = oldX1; - z2 = oldX2; + for (var facing : Direction.values()) { + var first = zone.moddev.mc.lib.machine.definition.MachineFacing + .point(facing, shape.x1() / 16, shape.y1() / 16, + shape.z1() / 16); + var last = zone.moddev.mc.lib.machine.definition.MachineFacing + .point(facing, shape.x2() / 16, shape.y2() / 16, + shape.z2() / 16); + result.put(facing, + Shapes.box(Math.min(first.x, last.x), Math.min(first.y, last.y), + Math.min(first.z, last.z), Math.max(first.x, last.x), + Math.max(first.y, last.y), Math.max(first.z, last.z))); } return Map.copyOf(result); } diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineEntityDisplays.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineEntityDisplays.java index 7373245d..1b2936bd 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineEntityDisplays.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineEntityDisplays.java @@ -16,7 +16,6 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.neoforged.api.distmarker.Dist; import net.neoforged.bus.api.SubscribeEvent; @@ -52,8 +51,8 @@ private record Binding(EntityDisplay display, Optional> policy) { static Binding of(MachineDefinition definition) { var display = definition.behavior().entityDisplay(); - var processor = definition.behavior().processor() - .schema(definition.processor()); + var processor = definition.processorSchemas() + .get(display.variable().processor()); var reference = processor .portableVariable(display.variable().name()).orElse(null); return new Binding(display, @@ -189,8 +188,7 @@ public void render(DefinedMachineEntity machine, float partialTick, var entity = cache.get(machine.getLevel(), snapshot); if (entity == null) return; - var facing = machine.getBlockState() - .getValue(BlockStateProperties.HORIZONTAL_FACING); + var facing = machine.facing(); var offset = display.offset(facing); entity.setPos(machine.getBlockPos().getX() + offset.x, machine.getBlockPos().getY() + offset.y, @@ -198,9 +196,16 @@ public void render(DefinedMachineEntity machine, float partialTick, pose.pushPose(); try { pose.translate(offset.x, offset.y, offset.z); + if (facing.getAxis().isVertical()) { + pose.mulPose(com.mojang.math.Axis.YP.rotationDegrees( + facing == net.minecraft.core.Direction.UP ? 180 : 0)); + pose.mulPose(com.mojang.math.Axis.XP.rotationDegrees( + facing == net.minecraft.core.Direction.UP ? 90 : -90)); + } EntityDisplayRendering.render(entity, pose, buffers, light, partialTick, display.width(), display.height(), - facing.toYRot() + display.yaw()); + (facing.getAxis().isVertical() ? 180 : facing.toYRot()) + + display.yaw()); } finally { pose.popPose(); } diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineItemDisplay.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineItemDisplay.java index a656107c..ea6cd930 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineItemDisplay.java +++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/client/MachineItemDisplay.java @@ -11,7 +11,6 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; import zone.moddev.mc.lib.machine.definition.ItemDisplay; import zone.moddev.mc.lib.machine.neoforge.DefinedMachineEntity; @@ -42,8 +41,7 @@ public void render(DefinedMachineEntity machine, float partialTick, var stack = item(display.variable().read(machine)); if (stack.isEmpty()) return; - var facing = machine.getBlockState() - .getValue(BlockStateProperties.HORIZONTAL_FACING); + var facing = machine.facing(); if (machine.getLevel() != null) light = LevelRenderer.getLightColor(machine.getLevel(), machine.getBlockPos().relative(facing)); @@ -51,7 +49,13 @@ public void render(DefinedMachineEntity machine, float partialTick, try { var offset = display.offset(facing); pose.translate(offset.x, offset.y, offset.z); - pose.mulPose(Axis.YP.rotationDegrees(-facing.toYRot())); + if (facing.getAxis().isVertical()) { + pose.mulPose(Axis.YP.rotationDegrees( + facing == net.minecraft.core.Direction.UP ? 0 : 180)); + pose.mulPose(Axis.XP.rotationDegrees( + facing == net.minecraft.core.Direction.UP ? -90 : 90)); + } else + pose.mulPose(Axis.YP.rotationDegrees(-facing.toYRot())); pose.scale(display.width(), display.height(), .001f); Minecraft.getInstance().getItemRenderer().renderStatic(stack, ItemDisplayContext.GUI, light, overlay, pose, buffers, diff --git a/src/main/java/zone/moddev/mc/lib/machine/presentation/BuiltinVisualVariables.java b/src/main/java/zone/moddev/mc/lib/machine/presentation/BuiltinVisualVariables.java index 8381afe4..cada8bd5 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/presentation/BuiltinVisualVariables.java +++ b/src/main/java/zone/moddev/mc/lib/machine/presentation/BuiltinVisualVariables.java @@ -123,14 +123,23 @@ public static VisualVariableProvider energy(EnergyBuffer energy) { public static VisualVariables forMachine(MachineDefinition definition, zone.moddev.mc.lib.machine.feature.Processor processor, ItemInventories items, FluidStorage fluids, EnergyBuffer energy) { + return forProcessors(definition, + processor == null + ? java.util.Map.of() + : java.util.Map.of(processor.key(), processor), + items, fluids, energy); + } + + public static VisualVariables forProcessors(MachineDefinition definition, + java.util.Map> processors, + ItemInventories items, FluidStorage fluids, EnergyBuffer energy) { var vars = new VisualVariables.Builder(); - if (definition.hasProcessor()) - vars.component("processors." + definition.processor(), - processor != null - ? processor - : definition.behavior().processor() != null - ? definition.behavior().processor() - .schema(definition.processor()) + for (var config : definition.processors()) + vars.component("processors." + config.id(), + processors.containsKey(config.id()) + ? processors.get(config.id()) + : config.declaration() != null + ? config.declaration().schema(config.id()) : processor(null)); for (var group : definition.groups()) { var indexes = definition.inventorySlots(group.id()); diff --git a/src/main/java/zone/moddev/mc/lib/machine/recipe/CyclePlan.java b/src/main/java/zone/moddev/mc/lib/machine/recipe/CyclePlan.java index 24ccada2..13705f9d 100644 --- a/src/main/java/zone/moddev/mc/lib/machine/recipe/CyclePlan.java +++ b/src/main/java/zone/moddev/mc/lib/machine/recipe/CyclePlan.java @@ -40,19 +40,13 @@ * Reserving and restoring work from these fields alone, so a plan may be built * by hand. * - * @param recipe - * the recipe it was made from - * @param time - * ticks the cycle takes - * @param items - * item inputs, by slot - * @param fluids - * fluid inputs, by tank - * @param products - * each product with where it lands; chance products are placed as if - * certain - * @param energy - * the energy each energy group must supply over the cycle + * @param recipe the recipe it was made from + * @param time ticks the cycle takes + * @param items item inputs, by slot + * @param fluids fluid inputs, by tank + * @param products each product with where it lands; chance products are placed + * as if certain + * @param energy the energy each energy group must supply over the cycle */ public record CyclePlan(ResourceLocation recipe, int time, List items, List fluids, List products, Map energy) { @@ -373,6 +367,20 @@ public void release(MachineInventory inventory) { * input is gone or a product no longer fits where it was placed */ public boolean finish(MachineInventory inventory, RandomSource random) { + try (var tx = inventory.begin()) { + if (!finish(inventory, random, tx)) + return false; + tx.commit(); + return true; + } + } + + /** + * Finish within a caller-owned transaction; the caller must roll back on + * failure. + */ + public boolean finish(MachineInventory inventory, RandomSource random, + zone.moddev.mc.lib.machine.inventory.MachineTx tx) { if (plans() == null) return false; var hits = new ArrayList(); @@ -382,42 +390,39 @@ public boolean finish(MachineInventory inventory, RandomSource random) { hits.add(placed); if (!canFinish(inventory, hits)) return false; - try (var tx = inventory.begin()) { - release(inventory, tx); - for (var take : items) { - var group = items(inventory, take.group); - if (group == null) - return false; - var held = group.peek(take.slot); - int count = take.stack.getCount(); - if (!ItemStack.isSameItemSameComponents(held, take.stack) - || held.getCount() < count) - return false; - int consumed = count - take.retained; - if (consumed > 0 - && group.extract(take.slot, consumed, tx) != consumed) - return false; - } - for (var take : fluids) { - var group = fluids(inventory, take.group); - if (group == null) - return false; - var held = group.peek(take.tank); - if (!held.sameFluid(take.fluid) - || held.amount() < take.fluid.amount()) - return false; - int consumed = take.fluid.amount() - take.retained; - if (consumed > 0 - && group.extract(take.tank, consumed, tx) != consumed) - return false; - } - for (var placed : hits) - for (var at : placed.at) - if (!insert(inventory, placed, at, tx)) - return false; - tx.commit(); - return true; + release(inventory, tx); + for (var take : items) { + var group = items(inventory, take.group); + if (group == null) + return false; + var held = group.peek(take.slot); + int count = take.stack.getCount(); + if (!ItemStack.isSameItemSameComponents(held, take.stack) + || held.getCount() < count) + return false; + int consumed = count - take.retained; + if (consumed > 0 + && group.extract(take.slot, consumed, tx) != consumed) + return false; + } + for (var take : fluids) { + var group = fluids(inventory, take.group); + if (group == null) + return false; + var held = group.peek(take.tank); + if (!held.sameFluid(take.fluid) + || held.amount() < take.fluid.amount()) + return false; + int consumed = take.fluid.amount() - take.retained; + if (consumed > 0 + && group.extract(take.tank, consumed, tx) != consumed) + return false; } + for (var placed : hits) + for (var at : placed.at) + if (!insert(inventory, placed, at, tx)) + return false; + return true; } /** diff --git a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/InventoryArchitectureSmoke.java b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/InventoryArchitectureSmoke.java index 3fc1f620..6c5ee1de 100644 --- a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/InventoryArchitectureSmoke.java +++ b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/InventoryArchitectureSmoke.java @@ -579,6 +579,25 @@ static void recipeFilters(ServerLevel level) { var power = new ResourceGroup<>("energy", Component.literal("Energy"), 0x334455, ResourceType.ENERGY, IoMode.INPUT, List.of(0), List.of(), new SideConfig(IoMode.INPUT)); + var invalid = new MachineResources(owner, () -> Direction.NORTH) + .energy(power, energy); + rejected(() -> invalid.recipeInputs(MachineRecipeTypeSmoke.GRINDING, + "energy"), "requires items or fluids"); + var hidden = new ItemStorage(1).role(Role.INPUT, 0); + new MachineResources(owner, () -> Direction.NORTH) + .recipeOnlyItems("hidden", hidden, 0) + .recipeOnlyItems("output", storage, 1) + .recipeOnlyItems("byproduct", storage, 2) + .recipeOnlyFluids("water", fluids, 0).energy(power, energy) + .recipeInputs(MachineRecipeTypeSmoke.GRINDING, + Map.of("input", "hidden", "output", "output", "byproduct", + "byproduct", "water", "water", "energy", "energy"), + "input") + .build(); + require( + hidden.isItemValid(0, new ItemStack(Items.COPPER_ORE)) + && !hidden.isItemValid(0, new ItemStack(Items.DIAMOND)), + "Aliased recipe-only item inputs retain admission without exposing automation"); var resources = new MachineResources(owner, () -> Direction.NORTH) .items(items("input", IoMode.INPUT, 0), storage) .items(items("output", IoMode.OUTPUT, 1), storage) diff --git a/src/test/java/zone/moddev/mc/lib/gui/ScreenFillGeneratorTest.java b/src/test/java/zone/moddev/mc/lib/gui/ScreenFillGeneratorTest.java index 8d0fd6bc..6b60ade7 100644 --- a/src/test/java/zone/moddev/mc/lib/gui/ScreenFillGeneratorTest.java +++ b/src/test/java/zone/moddev/mc/lib/gui/ScreenFillGeneratorTest.java @@ -45,6 +45,32 @@ class ScreenFillGeneratorTest { @TempDir Path directory; + @Test + void multipleProcessorsExpandOnlyTheUnmodifiedDefaultControl() + throws Exception { + var sources = List.of( + new SourceRoot("mmdlib", Path.of("src/main/resources/mmdlib"), + getClass().getClassLoader()), + new SourceRoot("mmdlib_companion", + Path.of("src/companion/resources/mmdlib"), + getClass().getClassLoader())); + var machines = MachineDefinitions.load(sources); + var id = ResourceLocation.parse("mmdlib_companion:parallel_workshop"); + var generator = MachineScreenGenerators.forMachines(machines); + var standard = new Node("inventory-controls", Map.of(), + List.of(new Node("processor-button", Map.of("id", "toggle_0"), + List.of(), "test", 1)), + "test", 1); + assertEquals(3, + generator.prepareElement(id, standard).children().size()); + var authored = new Node("inventory-controls", Map.of(), + List.of(new Node("processor-button", + Map.of("id", "custom_toggle", "text", "Custom"), List.of(), + "test", 1)), + "test", 1); + assertEquals(authored, generator.prepareElement(id, authored)); + } + @Test void machineContextFiltersOnlyUnmodifiedTemplateDefaults() throws Exception { diff --git a/src/test/java/zone/moddev/mc/lib/machine/ItemDisplayTest.java b/src/test/java/zone/moddev/mc/lib/machine/ItemDisplayTest.java index dd5b9934..d7670a46 100644 --- a/src/test/java/zone/moddev/mc/lib/machine/ItemDisplayTest.java +++ b/src/test/java/zone/moddev/mc/lib/machine/ItemDisplayTest.java @@ -89,8 +89,10 @@ void bindsWithoutItemRegistryLookupAndCoexistsWithEntityDisplays() assertEquals(new Vec3(1.002, .7, .75), display.offset(Direction.EAST)); assertEquals(new Vec3(.25, .7, 1.002), display.offset(Direction.SOUTH)); assertEquals(new Vec3(-.002, .7, .25), display.offset(Direction.WEST)); - assertThrows(IllegalArgumentException.class, - () -> display.offset(Direction.UP)); + assertTrue(display.offset(Direction.UP) + .distanceTo(new Vec3(.25, 1.002, .3)) < 1e-12); + assertTrue(display.offset(Direction.DOWN) + .distanceTo(new Vec3(.75, -.002, .3)) < 1e-12); var defaults = load("variable='$processors.test.product'", "") .behavior().itemDisplay(); assertEquals(.5, defaults.x()); diff --git a/src/test/java/zone/moddev/mc/lib/machine/MachineDefinitionsTest.java b/src/test/java/zone/moddev/mc/lib/machine/MachineDefinitionsTest.java index dad90a58..072eaa54 100644 --- a/src/test/java/zone/moddev/mc/lib/machine/MachineDefinitionsTest.java +++ b/src/test/java/zone/moddev/mc/lib/machine/MachineDefinitionsTest.java @@ -48,6 +48,216 @@ private String crusher() throws Exception { .of("src/companion/resources/mmdlib/machine/simple_crusher.xml")); } + public static class Admission + extends + zone.moddev.mc.lib.machine.feature.StoredProcessor + implements zone.moddev.mc.lib.machine.feature.StorageAdmission { + public boolean canStart( + zone.moddev.mc.lib.machine.feature.ProcessorState state, + zone.moddev.mc.lib.machine.feature.ProcessorMachine host) { + return false; + } + public ProcessState process( + zone.moddev.mc.lib.machine.feature.ProcessorState state, + zone.moddev.mc.lib.machine.feature.ProcessorMachine host, + int ticks) { + return ProcessState.IDLE; + } + } + + public static final class ComparatorProcessor extends Admission + implements zone.moddev.mc.lib.api.redstone.IRedstoneOutput { + public List redstoneOutputs() { + return List.of(new zone.moddev.mc.lib.api.redstone.RedstoneOutput( + "custom/output", + net.minecraft.network.chat.Component.literal("Output"), + net.minecraft.network.chat.Component.literal("Output"), + 0xffffff, java.util.Optional.empty(), () -> { + throw new AssertionError( + "Metadata validation must not sample a live level"); + })); + } + } + + @Test + void comparatorValidationUsesCustomSourceMetadataWithoutSamplingLevels() + throws Exception { + String xml = """ + + + + + + + """; + write(xml); + assertEquals("custom/output", + MachineDefinitions.load(sources()) + .get(ResourceLocation.parse("test:crusher")).behavior() + .comparatorSource()); + write(xml.replace("custom/output", "custom/typo")); + assertTrue(assertThrows(IllegalArgumentException.class, + () -> MachineDefinitions.load(sources())).getMessage() + .contains("Unknown comparator source")); + } + + @Test + void comparatorSourcesFailAtTheRedstoneDeclaration() throws Exception { + for (String source : List.of("processor/crusher/processing", + "processor/crusher/inactive", "processor/crusher/progress")) { + write(crusher().replace("", + "")); + assertEquals(source, + MachineDefinitions.load(sources()) + .get(ResourceLocation.parse("test:crusher")).behavior() + .comparatorSource()); + } + write(crusher().replace("", + "")); + var error = assertThrows(IllegalArgumentException.class, + () -> MachineDefinitions.load(sources())); + assertTrue(error.getMessage().contains("crusher.xml")); + long redstoneLine = crusher() + .substring(0, crusher().indexOf("")).lines().count() + 1; + assertTrue( + error.getMessage().contains("crusher.xml:" + redstoneLine + ":"), + error.getMessage()); + assertTrue( + error.getMessage().contains("Unknown comparator source: typo")); + } + + @Test + void processorOperatingCostValidatesPowerAndNonnegativeAmounts() + throws Exception { + String xml = crusher().replace(" MachineDefinitions.load(sources())); + String unpowered = Files + .readString(Path.of( + "src/companion/resources/mmdlib/machine/porting_workshop.xml")) + .replace(" MachineDefinitions.load(sources())); + } + + @Test + void energyProviderIsExplicitAndControlsCapacitorSupport() + throws Exception { + String xml = Files + .readString(Path.of( + "src/companion/resources/mmdlib/machine/parallel_workshop.xml")) + .replace("", + "") + .replace("", + ""); + write(xml); + var definition = MachineDefinitions.load(sources()) + .get(ResourceLocation.parse("test:crusher")); + assertEquals("battery", definition.power().provider()); + assertNull(definition.behavior().capacitorSlot()); + write(xml.replace("provider=\"battery\"", + "provider=\"battery\" capacitors=\"true\"")); + assertNotNull(MachineDefinitions.load(sources()) + .get(ResourceLocation.parse("test:crusher")).behavior() + .capacitorSlot()); + write(xml.replace("provider=\"battery\"", "provider=\"missing\"")); + assertThrows(IllegalArgumentException.class, + () -> MachineDefinitions.load(sources())); + write(xml.replace("provider=\"battery\"", "provider=\"left\"")); + assertThrows(IllegalArgumentException.class, + () -> MachineDefinitions.load(sources())); + write(xml.replace("", + "")); + assertThrows(IllegalArgumentException.class, + () -> MachineDefinitions.load(sources())); + } + + @Test + void multipleProcessorsBindResourcesAndValidateEveryLane() + throws Exception { + String xml = Files + .readString(Path.of( + "src/companion/resources/mmdlib/machine/parallel_workshop.xml")) + .replace("zone.moddev.mc.companion.ChargePump", + Admission.class.getName()); + write(xml); + var definition = MachineDefinitions.load(sources()) + .get(ResourceLocation.parse("test:crusher")); + assertEquals(List.of("charge", "left", "right"), + definition.processors().stream().map( + zone.moddev.mc.lib.machine.definition.ProcessorConfiguration::id) + .toList()); + assertEquals("left", definition.processor()); + assertEquals("right_input", + definition.processors().get(2).bindings().get("input")); + assertEquals(List.of("input"), + definition.processors().get(2).filterInputs()); + write(xml.replace("input=right_input", "input=missing")); + assertThrows(IllegalArgumentException.class, + () -> MachineDefinitions.load(sources())); + write(xml.replace("id=\"right\"", "id=\"left\"")); + assertThrows(IllegalArgumentException.class, + () -> MachineDefinitions.load(sources())); + } + + @Test + void admissionDeclarationsResolveAndRejectMissingProcessors() + throws Exception { + String xml = Files + .readString(Path.of( + "src/companion/resources/mmdlib/machine/admission_demo.xml")) + .replace("zone.moddev.mc.companion.AdmissionDemo", + Admission.class.getName()); + write(xml); + var definition = MachineDefinitions.load(sources()) + .get(ResourceLocation.parse("test:crusher")); + assertEquals("rules", + definition.slots().getFirst().admission().processor()); + assertEquals(Admission.class, + definition.slots().get(1).admission().type()); + assertEquals(ResourceLocation.parse("minecraft:water"), + definition.fluids().tanks().getFirst().fluidTag()); + write(xml.replace("filter-processor=\"rules\"", + "filter-processor=\"missing\"")); + assertThrows(IllegalArgumentException.class, + () -> MachineDefinitions.load(sources())); + write(xml.replace("filter-processor=\"rules\"", + "filter-processor=\"rules\" filter-class=\"" + + Admission.class.getName() + "\"")); + assertThrows(IllegalArgumentException.class, + () -> MachineDefinitions.load(sources())); + } + + @Test + void facingFixturesLoadAndValidateInheritedPolicies() throws Exception { + for (var name : List.of("all", "away", "up", "down", "vertical", + "asymmetric")) { + write(Files.readString( + Path.of("src/companion/resources/mmdlib/machine/facing_" + name + + ".xml"))); + var definition = MachineDefinitions.load(sources()) + .get(ResourceLocation.parse("test:crusher")); + assertFalse(definition.behavior().facing().directions().isEmpty()); + assertEquals(!name.equals("away"), + definition.behavior().facing().towardPlayer()); + } + write(crusher().replace("", + "")); + var facing = MachineDefinitions.load(sources()) + .get(ResourceLocation.parse("test:crusher")).behavior().facing(); + assertEquals(Set.of(net.minecraft.core.Direction.UP, + net.minecraft.core.Direction.NORTH), facing.directions()); + assertFalse(facing.towardPlayer()); + } + @Test void rangeSocketsSupportRangeOnlyMachinesAndRejectOverlaps() throws Exception { @@ -1058,7 +1268,7 @@ void singletonOverridesCanChangeTheirIds() throws Exception { assertNotNull(plan.recipeType().generator()); assertEquals(100000, plan.power().capacity()); write(crusher().replace("", - "")); + "")); assertTrue(assertThrows(IllegalArgumentException.class, () -> MachineDefinitions.load(sources())).getMessage() .contains("Duplicate definition processor")); diff --git a/src/test/java/zone/moddev/mc/lib/machine/MachineFacingTest.java b/src/test/java/zone/moddev/mc/lib/machine/MachineFacingTest.java new file mode 100644 index 00000000..2f77afa3 --- /dev/null +++ b/src/test/java/zone/moddev/mc/lib/machine/MachineFacingTest.java @@ -0,0 +1,79 @@ +package zone.moddev.mc.lib.machine; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.EnumSet; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.phys.Vec3; + +import org.junit.jupiter.api.Test; + +import zone.moddev.mc.lib.machine.definition.MachineFacing; +import zone.moddev.mc.lib.machine.feature.WorkingArea; + +class MachineFacingTest { + @Test + void allSubsetsConstrainPlacementAndTransforms() { + var directions = Direction.values(); + for (int mask = 1; mask < 64; mask++) { + var allowed = EnumSet.noneOf(Direction.class); + for (int i = 0; i < 6; i++) + if ((mask & (1 << i)) != 0) + allowed.add(directions[i]); + for (boolean toward : new boolean[]{false, true}) { + var policy = new MachineFacing(allowed, toward); + assertTrue(allowed.contains(policy.defaultDirection())); + for (var first : directions) { + var order = new java.util.ArrayList(); + order.add(first); + for (var other : directions) + if (other != first) + order.add(other); + var selected = policy + .placement(order.toArray(Direction[]::new)); + assertTrue(allowed.contains(selected)); + var preferred = toward ? first.getOpposite() : first; + if (allowed.contains(preferred)) + assertEquals(preferred, selected); + for (var next : directions) + assertTrue(allowed + .contains(policy.transformed(selected, next))); + } + } + } + } + + @Test + void transformsAgreeWithFrontAndVerticalTop() { + for (var front : Direction.values()) { + var center = MachineFacing.point(front, .5, .5, .5); + var face = MachineFacing.point(front, .5, .5, 0).subtract(center); + assertEquals(Vec3.atLowerCornerOf(front.getNormal()).scale(.5), + face); + if (front.getAxis().isVertical()) + assertEquals(new Vec3(0, 0, -.5), + MachineFacing.point(front, .5, 1, .5).subtract(center)); + var area = new WorkingArea(-1, -2, 1, 2, 1, 3); + var bounds = area.bounds(BlockPos.ZERO, front); + var positions = new java.util.HashSet(); + for (var position : area.blocks(BlockPos.ZERO, front)) { + assertTrue(bounds.contains(Vec3.atCenterOf(position))); + positions.add(position); + } + assertEquals(area.size(), positions.size()); + } + } + + @Test + void rejectsInvalidDeclarations() { + for (var faces : new String[]{"", "up up", "horizontal up", "diagonal"}) + assertThrows(IllegalArgumentException.class, + () -> MachineFacing.parse(faces, "toward-player")); + assertThrows(IllegalArgumentException.class, + () -> MachineFacing.parse("all", "sideways")); + } +} diff --git a/src/test/java/zone/moddev/mc/lib/machine/feature/ProcessorLookupTest.java b/src/test/java/zone/moddev/mc/lib/machine/feature/ProcessorLookupTest.java index e564f04e..ee700e10 100644 --- a/src/test/java/zone/moddev/mc/lib/machine/feature/ProcessorLookupTest.java +++ b/src/test/java/zone/moddev/mc/lib/machine/feature/ProcessorLookupTest.java @@ -8,6 +8,28 @@ import zone.moddev.mc.lib.gui.runtime.ScreenHost; class ProcessorLookupTest { + @Test + void primarySelectionKeepsExplicitAndIndexedOrderIndependent() { + var first = new ProcessorStateTest.Fixture(); + first.initialize("first", null); + var second = new ProcessorStateTest.Fixture(); + second.initialize("second", null); + var features = new FeatureHost(() -> { + }).add(first).add(second); + assertSame(first, + features.findProcessor(java.util.Optional.empty()).orElseThrow()); + features.primaryProcessor("second"); + assertSame(second, + features.findProcessor(java.util.Optional.empty()).orElseThrow()); + assertSame(first, features.findProcessor(java.util.Optional.of("first")) + .orElseThrow()); + assertSame(first, features.allProcessors().getFirst()); + assertTrue(features.processor(java.util.Optional.empty()).isEmpty()); + org.junit.jupiter.api.Assertions.assertThrows( + IllegalArgumentException.class, + () -> features.primaryProcessor("missing")); + } + @Test void lookupAcceptsGenericHostsAndRejectsMissingOrMismatchedProcessors() { var processor = new ProcessorStateTest.Fixture();