Skip to content

Commit 46a3520

Browse files
authored
Merge pull request #99 from MinecraftModDevelopmentMods/add-bottles
Bottles as generic fluid containers
2 parents 2dab4eb + de5acbb commit 46a3520

12 files changed

Lines changed: 475 additions & 1 deletion

File tree

‎docs/fluid-bottles.md‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Fluid bottles
2+
3+
Vanilla glass bottles only pick up water. MMDLib lets them hold any fluid in the
4+
`#mmdlib:bottleable` fluid tag, without a mixin. A filled bottle is a single item,
5+
`mmdlib:fluid_bottle`, that holds **333 mB**, a third of a bucket, of one fluid.
6+
7+
## Making a fluid bottleable
8+
9+
Add its **source** fluid to the tag with a datapack or your mod's data:
10+
11+
```json
12+
// data/mmdlib/tags/fluid/bottleable.json
13+
{ "replace": false, "values": ["example:molten_tin"] }
14+
```
15+
16+
MMDLib ships the tag empty, so packs and mods decide what can be bottled.
17+
Vanilla's own fluids (water, lava) are always left to vanilla, even if tagged:
18+
a water bottle is still vanilla's water potion.
19+
20+
## What works
21+
22+
* **Right-click a source block** with a glass bottle to fill it. The source block
23+
stays, as it does for water. Protected blocks (`Level.mayInteract`) are skipped.
24+
* **Tanks and pipes** fill and empty bottles through the fluid item capability
25+
(`Capabilities.FluidHandler.ITEM`), for example with `FluidUtil`. Filling takes
26+
exactly 333 mB. Emptying a bottle leaves a glass bottle.
27+
* **Name**: "Bottle of" plus the fluid's name, such as "Bottle of Molten Copper".
28+
* **Look**: vanilla's potion bottle, with the fluid's still texture showing
29+
through the potion's liquid area. It is tinted with whatever color the fluid
30+
type registers on the client (`IClientFluidTypeExtensions#getTintColor`);
31+
fluids without a tint show their texture as drawn. Glowing fluids glow.
32+
33+
## Other mods' glass bottle capabilities
34+
35+
If another mod already gives glass bottles a fluid capability, MMDLib doesn't
36+
register its own: it logs that at startup and leaves filling glass bottles from
37+
tanks to that mod. Right-clicking bottleable fluids, and filled MMDLib bottles,
38+
work either way. MMDLib registers at the lowest priority, so mods registering at
39+
the usual priority are seen first.
40+
41+
## Code
42+
43+
`zone.moddev.mc.lib.common.fluid.FluidBottles` holds the tag (`BOTTLEABLE`), the
44+
capacity, the item (`BOTTLE`) and its fluid component (`CONTENT`).
45+
`FluidBottleItem.filled(fluid)` makes a full bottle, and
46+
`FluidBottleItem.contents(stack)` reads one. `FluidBottles.bottleable(fluid)` is
47+
the single rule for what can be bottled.
48+
49+
`FluidBottleSmoke` (game tests) checks filling from the world, water left to
50+
vanilla, untagged fluids refused, and filling and emptying through tanks.

‎src/main/java/zone/moddev/mc/lib/MMDLib.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ public MMDLib(IEventBus modBus, ModContainer container) {
117117
NeoForge.EVENT_BUS.addListener(
118118
zone.moddev.mc.lib.machine.neoforge.MachinePartsLoader::register);
119119
modBus.addListener(zone.moddev.mc.lib.util.Registries::register);
120+
zone.moddev.mc.lib.common.fluid.FluidBottles.register(modBus);
120121

121122
if (ModList.get().isLoaded("crafttweaker")) CraftTweakerInit.register(modBus);
122123

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package zone.moddev.mc.lib.client;
2+
3+
import net.neoforged.api.distmarker.Dist;
4+
import net.neoforged.bus.api.SubscribeEvent;
5+
import net.neoforged.fml.common.EventBusSubscriber;
6+
import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent;
7+
import net.neoforged.neoforge.client.model.DynamicFluidContainerModel;
8+
9+
import zone.moddev.mc.lib.common.fluid.FluidBottles;
10+
11+
/**
12+
* Colors the fluid in a {@code mmdlib:fluid_bottle} with whatever tint its fluid type registers on
13+
* the client ({@code IClientFluidTypeExtensions#getTintColor}); fluids that register none show
14+
* their texture as drawn.
15+
*/
16+
@EventBusSubscriber(modid = "mmdlib", bus = EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
17+
public final class FluidBottleClient {
18+
private FluidBottleClient() {}
19+
20+
@SubscribeEvent
21+
public static void colors(RegisterColorHandlersEvent.Item event) {
22+
event.register(new DynamicFluidContainerModel.Colors(), FluidBottles.BOTTLE.get());
23+
}
24+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package zone.moddev.mc.lib.common.fluid;
2+
3+
import net.minecraft.world.item.ItemStack;
4+
5+
import net.neoforged.neoforge.fluids.FluidStack;
6+
import net.neoforged.neoforge.fluids.capability.IFluidHandlerItem;
7+
8+
/**
9+
* The fluid capability of an empty glass bottle: it takes exactly {@link FluidBottles#CAPACITY} of
10+
* a bottleable fluid at once and becomes a {@link FluidBottleItem}, the way NeoForge's bucket
11+
* wrapper turns an empty bucket into a filled one. Anything else is refused, so other fluid
12+
* handling of glass bottles is left alone.
13+
*/
14+
final class EmptyBottleFluidHandler implements IFluidHandlerItem {
15+
private ItemStack container;
16+
17+
EmptyBottleFluidHandler(ItemStack container) {
18+
this.container = container;
19+
}
20+
21+
@Override
22+
public ItemStack getContainer() {
23+
return container;
24+
}
25+
26+
@Override
27+
public int getTanks() {
28+
return 1;
29+
}
30+
31+
@Override
32+
public FluidStack getFluidInTank(int tank) {
33+
return FluidStack.EMPTY;
34+
}
35+
36+
@Override
37+
public int getTankCapacity(int tank) {
38+
return FluidBottles.CAPACITY;
39+
}
40+
41+
@Override
42+
public boolean isFluidValid(int tank, FluidStack stack) {
43+
return FluidBottles.bottleable(stack.getFluid());
44+
}
45+
46+
@Override
47+
public int fill(FluidStack resource, FluidAction action) {
48+
// A single bottle, filled whole: a stack of bottles is filled one at a time by FluidUtil.
49+
if (container.getCount() != 1
50+
|| resource.getAmount() < FluidBottles.CAPACITY
51+
|| !FluidBottles.bottleable(resource.getFluid())) return 0;
52+
if (action.execute()) container = FluidBottleItem.filled(resource.getFluid());
53+
return FluidBottles.CAPACITY;
54+
}
55+
56+
@Override
57+
public FluidStack drain(FluidStack resource, FluidAction action) {
58+
return FluidStack.EMPTY;
59+
}
60+
61+
@Override
62+
public FluidStack drain(int maxDrain, FluidAction action) {
63+
return FluidStack.EMPTY;
64+
}
65+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package zone.moddev.mc.lib.common.fluid;
2+
3+
import net.minecraft.network.chat.Component;
4+
import net.minecraft.world.item.Item;
5+
import net.minecraft.world.item.ItemStack;
6+
import net.minecraft.world.item.Items;
7+
import net.minecraft.world.level.material.Fluid;
8+
9+
import net.neoforged.neoforge.fluids.FluidStack;
10+
import net.neoforged.neoforge.fluids.SimpleFluidContent;
11+
12+
/**
13+
* {@code mmdlib:fluid_bottle}: a glass bottle holding {@link FluidBottles#CAPACITY} of one fluid,
14+
* kept in the {@link FluidBottles#CONTENT} component. Named after its fluid ("Bottle of Molten
15+
* Copper"); emptying it, through its fluid capability, leaves a glass bottle.
16+
*/
17+
public final class FluidBottleItem extends Item {
18+
/** One-high stacks, like potions: bottles of different fluids cannot share a stack anyway. */
19+
public FluidBottleItem(Properties properties) {
20+
super(properties.stacksTo(1).craftRemainder(Items.GLASS_BOTTLE));
21+
}
22+
23+
/** The fluid in {@code stack}; empty for an unfilled bottle. */
24+
public static FluidStack contents(ItemStack stack) {
25+
return stack.getOrDefault(FluidBottles.CONTENT.get(), SimpleFluidContent.EMPTY).copy();
26+
}
27+
28+
/** A bottle full of {@code fluid}. */
29+
public static ItemStack filled(Fluid fluid) {
30+
var stack = new ItemStack(FluidBottles.BOTTLE.get());
31+
stack.set(
32+
FluidBottles.CONTENT.get(),
33+
SimpleFluidContent.copyOf(new FluidStack(fluid, FluidBottles.CAPACITY)));
34+
return stack;
35+
}
36+
37+
@Override
38+
public Component getName(ItemStack stack) {
39+
var fluid = contents(stack);
40+
return fluid.isEmpty()
41+
? super.getName(stack)
42+
: Component.translatable(getDescriptionId(stack) + ".filled", fluid.getHoverName());
43+
}
44+
}
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
package zone.moddev.mc.lib.common.fluid;
2+
3+
import java.util.function.Supplier;
4+
5+
import org.slf4j.Logger;
6+
7+
import com.mojang.logging.LogUtils;
8+
9+
import net.minecraft.core.component.DataComponentType;
10+
import net.minecraft.core.registries.BuiltInRegistries;
11+
import net.minecraft.core.registries.Registries;
12+
import net.minecraft.resources.ResourceLocation;
13+
import net.minecraft.sounds.SoundEvents;
14+
import net.minecraft.sounds.SoundSource;
15+
import net.minecraft.stats.Stats;
16+
import net.minecraft.tags.TagKey;
17+
import net.minecraft.world.InteractionResult;
18+
import net.minecraft.world.item.ItemUtils;
19+
import net.minecraft.world.item.Items;
20+
import net.minecraft.world.level.material.Fluid;
21+
import net.minecraft.world.phys.BlockHitResult;
22+
import net.minecraft.world.phys.HitResult;
23+
24+
import net.neoforged.bus.api.EventPriority;
25+
import net.neoforged.bus.api.IEventBus;
26+
import net.neoforged.neoforge.capabilities.Capabilities;
27+
import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent;
28+
import net.neoforged.neoforge.common.NeoForge;
29+
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
30+
import net.neoforged.neoforge.fluids.SimpleFluidContent;
31+
import net.neoforged.neoforge.fluids.capability.templates.FluidHandlerItemStack;
32+
import net.neoforged.neoforge.registries.DeferredHolder;
33+
import net.neoforged.neoforge.registries.DeferredRegister;
34+
35+
import zone.moddev.mc.lib.MMDLib;
36+
37+
/**
38+
* Lets vanilla glass bottles hold any fluid in {@link #BOTTLEABLE}, without a mixin:
39+
*
40+
* <ul>
41+
* <li>Right-clicking a source block of such a fluid with a glass bottle gives a {@link
42+
* FluidBottleItem} and leaves the source in place, as water bottles do.
43+
* <li>Glass bottles and filled bottles get a fluid capability, so tanks and pipes fill and empty
44+
* them. If another mod already gives glass bottles one, MMDLib logs that and leaves glass
45+
* bottles to it.
46+
* </ul>
47+
*
48+
* Vanilla's own fluids (water, lava) are always left to vanilla, tagged or not.
49+
*/
50+
public final class FluidBottles {
51+
private static final Logger LOGGER = LogUtils.getLogger();
52+
53+
/** Source fluids glass bottles can hold. MMDLib ships it empty: packs and mods fill it. */
54+
public static final TagKey<Fluid> BOTTLEABLE =
55+
TagKey.create(Registries.FLUID, ResourceLocation.fromNamespaceAndPath(MMDLib.MODID, "bottleable"));
56+
57+
/** Millibuckets in a bottle: a third of a bucket, the common convention. */
58+
public static final int CAPACITY = 333;
59+
60+
private static final DeferredRegister.DataComponents COMPONENTS =
61+
DeferredRegister.createDataComponents(Registries.DATA_COMPONENT_TYPE, MMDLib.MODID);
62+
63+
/** The fluid a {@link FluidBottleItem} holds. */
64+
public static final Supplier<DataComponentType<SimpleFluidContent>> CONTENT =
65+
COMPONENTS.registerComponentType(
66+
"bottle_fluid",
67+
builder ->
68+
builder
69+
.persistent(SimpleFluidContent.CODEC)
70+
.networkSynchronized(SimpleFluidContent.STREAM_CODEC));
71+
72+
/** {@code mmdlib:fluid_bottle}. */
73+
public static final DeferredHolder<net.minecraft.world.item.Item, FluidBottleItem> BOTTLE =
74+
MMDLib.ITEMS.register(
75+
"fluid_bottle", () -> new FluidBottleItem(new net.minecraft.world.item.Item.Properties()));
76+
77+
private FluidBottles() {}
78+
79+
/** Registers the component, the capabilities and the bottle-filling hook. */
80+
public static void register(IEventBus modBus) {
81+
COMPONENTS.register(modBus);
82+
// Lowest priority, so mods registering at the usual priority are seen first.
83+
modBus.addListener(EventPriority.LOWEST, FluidBottles::capabilities);
84+
NeoForge.EVENT_BUS.addListener(FluidBottles::fillFromWorld);
85+
}
86+
87+
/** Whether glass bottles can hold {@code fluid}: tagged, and not one of vanilla's. */
88+
public static boolean bottleable(Fluid fluid) {
89+
return !BuiltInRegistries.FLUID.getKey(fluid).getNamespace().equals("minecraft")
90+
&& fluid.defaultFluidState().is(BOTTLEABLE);
91+
}
92+
93+
private static void capabilities(RegisterCapabilitiesEvent event) {
94+
event.registerItem(
95+
Capabilities.FluidHandler.ITEM,
96+
(stack, context) ->
97+
new FluidHandlerItemStack.SwapEmpty(
98+
CONTENT, stack, new net.minecraft.world.item.ItemStack(Items.GLASS_BOTTLE), CAPACITY) {
99+
@Override
100+
public boolean canFillFluidType(net.neoforged.neoforge.fluids.FluidStack fluid) {
101+
return bottleable(fluid.getFluid());
102+
}
103+
},
104+
BOTTLE.get());
105+
if (event.isItemRegistered(Capabilities.FluidHandler.ITEM, Items.GLASS_BOTTLE)) {
106+
LOGGER.info(
107+
"Another mod already gives glass bottles a fluid capability; MMDLib leaves filling them"
108+
+ " from tanks to it. Right-clicking bottleable fluids still works.");
109+
return;
110+
}
111+
event.registerItem(
112+
Capabilities.FluidHandler.ITEM,
113+
(stack, context) -> new EmptyBottleFluidHandler(stack),
114+
Items.GLASS_BOTTLE);
115+
}
116+
117+
/**
118+
* A glass bottle used on a bottleable source fills, both sides, before vanilla's bottle handling
119+
* (which only knows water). Anything else goes on to vanilla.
120+
*/
121+
private static void fillFromWorld(PlayerInteractEvent.RightClickItem event) {
122+
var held = event.getItemStack();
123+
if (!held.is(Items.GLASS_BOTTLE)) return;
124+
var player = event.getEntity();
125+
var level = event.getLevel();
126+
var hit = player.pick(player.blockInteractionRange(), 0, true);
127+
if (hit.getType() != HitResult.Type.BLOCK || !(hit instanceof BlockHitResult block)) return;
128+
var pos = block.getBlockPos();
129+
var fluid = level.getFluidState(pos);
130+
if (!fluid.isSource() || !bottleable(fluid.getType()) || !level.mayInteract(player, pos)) return;
131+
level.playSound(
132+
player,
133+
player.getX(),
134+
player.getY(),
135+
player.getZ(),
136+
SoundEvents.BOTTLE_FILL,
137+
SoundSource.NEUTRAL,
138+
1.0F,
139+
1.0F);
140+
player.awardStat(Stats.ITEM_USED.get(Items.GLASS_BOTTLE));
141+
player.setItemInHand(
142+
event.getHand(),
143+
ItemUtils.createFilledResult(held, player, FluidBottleItem.filled(fluid.getType())));
144+
event.setCanceled(true);
145+
event.setCancellationResult(InteractionResult.sidedSuccess(level.isClientSide()));
146+
}
147+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
/**
2+
* Glass bottles that hold any fluid in the {@code #mmdlib:bottleable} tag; see {@link
3+
* zone.moddev.mc.lib.common.fluid.FluidBottles}.
4+
*/
5+
package zone.moddev.mc.lib.common.fluid;

‎src/main/resources/assets/mmdlib/lang/en_us.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -377,5 +377,7 @@
377377
"screen.mmdlib.stats.cycles": "Cycles",
378378
"screen.mmdlib.stats.cycle_tip": "Click to cycle tick / second / minute. Right-click to cycle backwards.",
379379
"screen.mmdlib.stats.empty": "No statistics available.",
380-
"screen.mmdlib.stats.tip": "Measured RF: latest 20 ticks. Cycles: up to 60 game seconds. Max cycles uses the active recipe duration; max use is peak recipe demand. Max transfer rates use one transfer per tick."
380+
"screen.mmdlib.stats.tip": "Measured RF: latest 20 ticks. Cycles: up to 60 game seconds. Max cycles uses the active recipe duration; max use is peak recipe demand. Max transfer rates use one transfer per tick.",
381+
"item.mmdlib.fluid_bottle": "Fluid Bottle",
382+
"item.mmdlib.fluid_bottle.filled": "Bottle of %s"
381383
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"parent": "neoforge:item/default",
3+
"loader": "neoforge:fluid_container",
4+
"fluid": "minecraft:empty",
5+
"cover_is_mask": false,
6+
"textures": {
7+
"fluid": "minecraft:item/potion_overlay",
8+
"cover": "minecraft:item/potion",
9+
"particle": "minecraft:item/potion"
10+
}
11+
}

0 commit comments

Comments
 (0)