Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[SOLVED] [1.17.1] How to/Fluids not working


Majd123mc
 Share

Recommended Posts

Solved:
 

Quote

As advised by Luis_ST, I subclassed LiquidBlock to fix all the missing references to LiquidBlock.supplier.

I *finally* found a reference for what my OilFluid class should look like, and it turns out I just had to change this:

super(new ForgeFlowingFluid.Properties(
				Source::new,
				Flowing::new,
				FluidAttributes.builder(
								new ResourceLocation(MiniTech.MODID, "block/oil_still"),
								new ResourceLocation(MiniTech.MODID, "block/oil_flow")
						).overlay(new ResourceLocation(MiniTech.MODID, "block/oil_overlay"))
						.translationKey("block." + MiniTech.MODID + ".oil")
						.color(0xffffff)));

to this:

super(new ForgeFlowingFluid.Properties(
				ModFluids.OIL,
				ModFluids.FLOWING_OIL,
				FluidAttributes.builder(
								new ResourceLocation(MiniTech.MODID, "block/oil_still"),
								new ResourceLocation(MiniTech.MODID, "block/oil_flow")
						).overlay(new ResourceLocation(MiniTech.MODID, "block/oil_overlay"))
						.translationKey("block." + MiniTech.MODID + ".oil")
						.color(0xffffff))
				.block(ModBlocks.OIL)
				.bucket(ModItems.OIL_BUCKET));

 



Hello all.

I am trying to implement oil into my mod (I know I know, unoriginal). But I just can't seem to get it to work.

(System/Minecraft information: Java 17, forge: 1.17.1-37.0.95, mappings: official)

I am using DeferredRegisters.

In the current configuration, the bucket doesn't do anything most of the time, the block doesn't appear and doesn't flow.

I am extending "ForgeFlowingFluid".

It seems in LiquidBlock there are two constructors, one deprecated taking in a Fluid, the other takes in a supplier/RegistryObject<Fluid>.

Because I am using DeferredRegisters, I have to use the second one, because blocks are registered before fluids.

But it seems that in the code, most of it relies on the LiquidBlock.fluid field, which never gets set in the second constructor. I tried hacking in a solution with a "Fixed" version of LiquidBlock:

public class FixedLiquidBlock extends LiquidBlock {
	private static final List<FixedLiquidBlock> liquidBlocksNeedingFixing = new ArrayList<>();

	// Check if the supplier is a registry object. If it is, and the value is not null, set the value of the fluid field, else mark it so that it gets set later.
	public FixedLiquidBlock(Supplier<? extends FlowingFluid> supplier, Properties properties) {
		super(supplier, properties);
		try {
			if (supplier instanceof RegistryObject registryObject && registryObject.get() != null) {
				try {
					Class<?> class_ = LiquidBlock.class;

					Field fluidField = ObfuscationReflectionHelper.findField(class_, "fluid");
					fluidField.setAccessible(true);
					fluidField.set(this, supplier.get());
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		} catch (NullPointerException ignored) {}

		liquidBlocksNeedingFixing.add(this);
	}

	@Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD)
	private static class FixedLiquidBlockEvents {
		@SubscribeEvent(priority = EventPriority.LOWEST) // Force the event to be called last
		// After registration of fluids is finished, set the fluids field.
		public static void onFluidsRegister(RegistryEvent<Fluid> fluidRegistryEvent) {
			for (FixedLiquidBlock fixedLiquidBlock : liquidBlocksNeedingFixing) {
				try {
					Class<?> class_ = LiquidBlock.class;

					Field fluidField = ObfuscationReflectionHelper.findField(class_, "fluid");
					fluidField.setAccessible(true);
					fluidField.set(fixedLiquidBlock, fixedLiquidBlock.getFluid());
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}
	}
}

But clearly what I'm doing is stupid because it still doesn't work. I even tried without my hacky solution, and it still didn't work!

Am I doing something wrong? Should I be extending something else? What else should I do?
 

Code for fluid, OilFluid.java:
 

public abstract class OilFluid extends ForgeFlowingFluid {

	protected OilFluid() {
		super(new ForgeFlowingFluid.Properties(
				Source::new,
				Flowing::new,
				FluidAttributes.builder(
								new ResourceLocation(MiniTech.MODID, "block/oil_still"),
								new ResourceLocation(MiniTech.MODID, "block/oil_flow")
						).overlay(new ResourceLocation(MiniTech.MODID, "block/oil_overlay"))
						.translationKey("block." + MiniTech.MODID + ".oil")
						.color(0xffffff)));
	}



	public static class Flowing extends OilFluid {
		public Flowing()
		{
			registerDefaultState(getStateDefinition().any().setValue(LEVEL, 7));
		}

		@Override
		protected void createFluidStateDefinition(StateDefinition.Builder<Fluid, FluidState> p_76476_) {
			super.createFluidStateDefinition(p_76476_);
			p_76476_.add(LEVEL);
		}

		@Override
		public int getAmount(FluidState p_76480_) {
			return p_76480_.getValue(LEVEL);
		}

		@Override
		public boolean isSource(FluidState p_76478_) {
			return false;
		}
	}

	public static class Source extends OilFluid {

		@Override
		public int getAmount(FluidState p_76485_) {
			return 8;
		}

		@Override
		public boolean isSource(FluidState p_76483_) {
			return true;
		}
	}
}

Code for ModBlocks.java:
 

public class ModBlocks {
    private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MiniTech.MODID);

    public static final RegistryObject<RefineryFurnaceBlock> REFINERY_FURNACE = BLOCKS.register("refinery_furnace", () -> new RefineryFurnaceBlock(BlockBehaviour.Properties.of(Material.STONE).requiresCorrectToolForDrops().strength(3.5F).lightLevel(litBlockEmission(13))));
    // Fluids
    public static final RegistryObject<LiquidBlock> OIL = BLOCKS.register("oil", () -> new FixedLiquidBlock(ModFluids.OIL, BlockBehaviour.Properties.of(Material.WATER).noCollission().strength(100.0F).noDrops()));

    public static void register(IEventBus eventBus) {
        BLOCKS.register(eventBus);
    }

    private static ToIntFunction<BlockState> litBlockEmission(int lightLevel) {
        return (blockState) -> {
            return blockState.getValue(BlockStateProperties.LIT) ? lightLevel : 0;
        };
    }
}

 

Edited by Majd123mc
Solved
Link to comment
Share on other sites

3 hours ago, Majd123mc said:

Am I doing something wrong? Should I be extending something else? What else should I do?

you should not use refelection to set the Field, overwrite all methods that use the vanilla 'fluid' Field,
and copy the code of vanilla and replace the vanilla Field with LiquidBlock#getFluid

The methods you need to overwrite:

  • LiquidBlock#isPathfindable
  • LiquidBlock#skipRendering
  • LiquidBlock#onPlace
  • LiquidBlock#updateShape
  • LiquidBlock#neighborChanged
  • LiquidBlock#shouldSpreadLiquid (AT required)
  • LiquidBlock#pickupBlock
  • LiquidBlock#getPickupSound
Edited by Luis_ST
  • Thanks 1
Link to comment
Share on other sites

The bucket item should be pretty straight forward and is handled in a general purpose registry file. I basically just copied the vanilla water bucket registry, and changed to what I needed. The fluid block and registry however gave me some headache. You prolly want to adapt to changes in 1.17+, but most of the code should be working out of the box.

Fluid block:

 
	public class BlockCrudeOil extends FlowingFluidBlock {
	    public BlockCrudeOil(Object object, Properties props) {
        super(() -> (FlowingFluid) RegisterFluid.OIL_FLUID.get(), props
                        .doesNotBlockMovement()
                        .hardnessAndResistance(100f)
                        .noDrops()
                    );
    }
    
    @Override
    public boolean canHarvestBlock(BlockState state, IBlockReader world, BlockPos pos, PlayerEntity player)
    {
        return false;
    }
    
    @Override
    public int getFlammability(BlockState state, IBlockReader world, BlockPos pos, Direction face)
    {
        return 300;
    }
    
    @Override
    public boolean isFlammable(BlockState state, IBlockReader world, BlockPos pos, Direction face)
    {
        return true;
    }
    
    public int getFireSpreadSpeed(BlockState state, IBlockReader world, BlockPos pos, Direction face)
    {
        return 100;
    }
    
    public boolean canDisplace(FluidState fluidState, IBlockReader blockReader, BlockPos pos, Fluid fluid, Direction direction) 
    {
        return true;
    }    
    
}

Fluid registry:

 
	public class RegisterFluid{
    
    public static final ResourceLocation OIL_STILL_RL = new ResourceLocation("fluid/oil_still");
    public static final ResourceLocation OIL_FLOWING_RL = new ResourceLocation("fluid/oil_flow");
    public static final ResourceLocation OIL_OVERLAY_RL = new ResourceLocation("fluid/oil_overlay");
    
    public static final Material MATOIL = (new Material.Builder(MaterialColor.TNT)).doesNotBlockMovement().notSolid().replaceable().liquid().build();
	    public static final DeferredRegister<Fluid> FLUIDS
            = DeferredRegister.create(ForgeRegistries.FLUIDS, MatLibMain.MODID);   
	    public static final RegistryObject<FlowingFluid> OIL_FLUID
            = FLUIDS.register("oil_fluid", () -> new ForgeFlowingFluid.Source(RegisterFluid.OIL_PROPERTIES));
	    public static final RegistryObject<FlowingFluid> OIL_FLOWING
            = FLUIDS.register("oil_flowing", () -> new ForgeFlowingFluid.Flowing(RegisterFluid.OIL_PROPERTIES));
	    public static final ForgeFlowingFluid.Properties OIL_PROPERTIES = new ForgeFlowingFluid.Properties(
            () -> OIL_FLUID.get(), () -> OIL_FLOWING.get(), FluidAttributes.builder(OIL_STILL_RL, OIL_FLOWING_RL)
            .density(800).temperature(300).viscosity(10000).sound(SoundEvents.ITEM_HONEY_BOTTLE_DRINK).overlay(OIL_OVERLAY_RL)
            .color(0xff000000)).slopeFindDistance(2).levelDecreasePerBlock(2).tickRate(45).explosionResistance(100f)
            .block(() -> RegisterFluid.OIL_BLOCK.get()).bucket(() -> RegisterMain.BUCKETOIL.get());
    
    public static class Source extends ForgeFlowingFluid.Source {
        public Source() {
            super(OIL_PROPERTIES);
        }
	        public int getTickDelay(IWorldReader world) {
            return 20;
        }  
	    }    
    
    public static final RegistryObject<FlowingFluidBlock> OIL_BLOCK = RegisterMain.BLOCKS.register("crudeoil",
            () -> new BlockCrudeOil(null, AbstractBlock.Properties.create(RegisterFluid.MATOIL)));//null was = () -> new FlowingFluidBlock(() -> MatLibFluidOil.OIL_FLUID.get(),     
	    public static void register(IEventBus eventBus) {
        FLUIDS.register(eventBus);
    } 
    
} 
	

 

Edited by Cratthorax
  • Thanks 1
Link to comment
Share on other sites

Thanks for the help everybody! I tried this and although the block did register, the fluid just appears as a flat plane you can only see if you break the block under it.

I tried debugging it as much as I could but alas I couldn't solve it

Here is the code for my "fixed" liquidblock as suggested by Luis_ST:

package com.hotmail.majdroaydi.minitech.blocks;

import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.tags.FluidTags;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.LiquidBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FlowingFluid;
import net.minecraft.world.level.pathfinder.PathComputationType;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;

import java.util.Optional;
import java.util.function.Supplier;

public class ForgeLiquidBlock extends LiquidBlock {
	public ForgeLiquidBlock(Supplier<? extends FlowingFluid> supplier, Properties properties) {
		super(supplier, properties);
	}

	@Override
	public VoxelShape getCollisionShape(BlockState p_54760_, BlockGetter p_54761_, BlockPos p_54762_, CollisionContext p_54763_) {
		return p_54763_.isAbove(STABLE_SHAPE, p_54762_, true) && p_54760_.getValue(LEVEL) == 0 && p_54763_.canStandOnFluid(p_54761_.getFluidState(p_54762_.above()), getFluid()) ? STABLE_SHAPE : Shapes.empty();
	}

	@Override
	public boolean isPathfindable(BlockState p_54704_, BlockGetter p_54705_, BlockPos p_54706_, PathComputationType p_54707_) {
		return !getFluid().is(FluidTags.LAVA);
	}

	@Override
	public boolean skipRendering(BlockState p_54716_, BlockState p_54717_, Direction p_54718_) {
		return p_54717_.getFluidState().getType().isSame(getFluid());
	}

	@Override
	public void onPlace(BlockState p_54754_, Level p_54755_, BlockPos p_54756_, BlockState p_54757_, boolean p_54758_) {
		if (this.shouldSpreadLiquid(p_54755_, p_54756_, p_54754_)) {
			p_54755_.getLiquidTicks().scheduleTick(p_54756_, p_54754_.getFluidState().getType(), getFluid().getTickDelay(p_54755_));
		}

	}

	@Override
	public BlockState updateShape(BlockState p_54723_, Direction p_54724_, BlockState p_54725_, LevelAccessor p_54726_, BlockPos p_54727_, BlockPos p_54728_) {
		if (p_54723_.getFluidState().isSource() || p_54725_.getFluidState().isSource()) {
			p_54726_.getLiquidTicks().scheduleTick(p_54727_, p_54723_.getFluidState().getType(), getFluid().getTickDelay(p_54726_));
		}

		//return super.updateShape(p_54723_, p_54724_, p_54725_, p_54726_, p_54727_, p_54728_);
		return p_54723_; // Calling super.updateShape will just call LiquidBlock's updateShape, not what we are looking for! Thankfully, Block.updateShape, simply enough, just returns the first parameter.
	}

	@Override
	public void neighborChanged(BlockState p_54709_, Level p_54710_, BlockPos p_54711_, Block p_54712_, BlockPos p_54713_, boolean p_54714_) {
		if (this.shouldSpreadLiquid(p_54710_, p_54711_, p_54709_)) {
			p_54710_.getLiquidTicks().scheduleTick(p_54711_, p_54709_.getFluidState().getType(), getFluid().getTickDelay(p_54710_));
		}

	}

	private boolean shouldSpreadLiquid(Level p_54697_, BlockPos p_54698_, BlockState p_54699_) {
		if (getFluid().is(FluidTags.LAVA)) {
			boolean flag = p_54697_.getBlockState(p_54698_.below()).is(Blocks.SOUL_SOIL);

			for(Direction direction : POSSIBLE_FLOW_DIRECTIONS) {
				BlockPos blockpos = p_54698_.relative(direction.getOpposite());
				if (p_54697_.getFluidState(blockpos).is(FluidTags.WATER)) {
					Block block = p_54697_.getFluidState(p_54698_).isSource() ? Blocks.OBSIDIAN : Blocks.COBBLESTONE;
					p_54697_.setBlockAndUpdate(p_54698_, net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(p_54697_, p_54698_, p_54698_, block.defaultBlockState()));
					this.fizz(p_54697_, p_54698_);
					return false;
				}

				if (flag && p_54697_.getBlockState(blockpos).is(Blocks.BLUE_ICE)) {
					p_54697_.setBlockAndUpdate(p_54698_, net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(p_54697_, p_54698_, p_54698_, Blocks.BASALT.defaultBlockState()));
					this.fizz(p_54697_, p_54698_);
					return false;
				}
			}
		}

		return true;
	}

	private void fizz(LevelAccessor p_54701_, BlockPos p_54702_) {
		p_54701_.levelEvent(1501, p_54702_, 0);
	}

	@Override
	public ItemStack pickupBlock(LevelAccessor p_153772_, BlockPos p_153773_, BlockState p_153774_) {
		if (p_153774_.getValue(LEVEL) == 0) {
			p_153772_.setBlock(p_153773_, Blocks.AIR.defaultBlockState(), 11);
			return new ItemStack(getFluid().getBucket());
		} else {
			return ItemStack.EMPTY;
		}
	}

	@Override
	public Optional<SoundEvent> getPickupSound() {
		return getFluid().getPickupSound();
	}
}

The code for my OilFluid can be found above.

Link to comment
Share on other sites

Thank you everybody, I have figured out the cause. I was accidentally passing in the constructor for the Fluids instead of the RegistryObject.

I changed:

super(new ForgeFlowingFluid.Properties(
				OilFluid.Source::new,
				OilFluid.Flowing::new,

to:

super(new ForgeFlowingFluid.Properties(
				ModFluids.OIL,
				ModFluids.FLOWING_OIL,

And now the fluid actually works! But it doesn't spread though, I think I'd be able to figured it out from now. Thanks a lot Luis_ST and Cratthorax!

Link to comment
Share on other sites

Yeah, the whole registry process can be quite confusing and daunting for how MC is working nowadays, but once you get the grasp of it, it actually saves a whole lot of effort, and quantity of code. I'd spend 3 days+ to actually figure I had to apply the getter(.get())[<-- is this even named getter?], to any of the .class references, because stupid Eclipse refused to de-obfuscate the source of problems. It was just making stupid a** auto fix suggestions, that didn't help at all. Google found the answer quite often though.

And don't even get me started when I was trying to implement the Oil to world generation. I was literally tearing my hair out for days.

But don't give up. We're not the only ones dealing with the reinvention of MC code wheel. I mean I get it. There's always room for improvements. But a wheel is just a wheel, right?

Edited by Cratthorax
  • Thanks 1
Link to comment
Share on other sites

  • Majd123mc changed the title to [CLOSED] [1.17.1] How to/Fluids not working
  • Majd123mc changed the title to [SOLVED] [1.17.1] How to/Fluids not working

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share



×
×
  • Create New...

Important Information

By using this site, you agree to our Privacy Policy.