Jump to content

Recommended Posts

Posted

Not sure which of the titles options is actually my problem, but here the problem is:

 

I have a general blockslab class with two variants:

 

The slabs place and appear correctly in the game world as blocks/slabs.

 

However, as inventory and entity items they are untextured (but correctly named).

 

There's an additional error where the game says it cant find the approprite blockstates for an item baring the name the itemBlock is registered with. (i'm assuming this is where the issue is occuring). This currently removed by using the string "mossy_slab" to register the itemblock. note this has no impact on the ingame issue.

 

My blockstate and model files are copy pastes and so contain no information about inventory or ground states. These seems a potentional solution.

 

The blockSlab class (i'm fairly confident this is in order):

 

 

 

public class mossySlab extends BlockSlab

{

    public static final PropertyEnum<mossySlab.EnumType> VARIANT = PropertyEnum.<mossySlab.EnumType>create("variant", mossySlab.EnumType.class);

 

 

public mossySlab() {

 

super(Material.ROCK);

this.setHardness(2.0F);

this.setResistance(10F);

//this.fullblock = fullblock;

this.setSoundType(SoundType.STONE);

        IBlockState iblockstate = this.blockState.getBaseState();

 

        if (!this.isDouble())

      {

        this.setCreativeTab(w2theJungle.JungleModTab);

this.setLightOpacity(0);

            iblockstate = iblockstate.withProperty(HALF, BlockSlab.EnumBlockHalf.BOTTOM);

        }

 

this.setDefaultState(iblockstate.withProperty(VARIANT, mossySlab.EnumType.MOSSY_SLAB));

}

 

@SideOnly(Side.CLIENT)

@Override

public ItemStack getPickBlock(IBlockState state, RayTraceResult trace, World wrld, BlockPos pos, EntityPlayer player)

{

        return new ItemStack(JungleBlocks.mossyslabSingle, 1, ((mossySlab.EnumType)state.getValue(VARIANT)).getMetadata());

 

}

 

    public int quantityDropped(Random p_149745_1_)

    {

        return this.isDouble() ? 2 : 1;

    }

   

    public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state)

    {

        return new ItemStack(Blocks.STONE_SLAB, 1, ((mossySlab.EnumType)state.getValue(VARIANT)).getMetadata());

    }

   

@Override

public Item getItemDropped(IBlockState state, Random random, int b) {

 

        return Item.getItemFromBlock(JungleBlocks.mossyslabSingle);

}

   

    public IBlockState getStateFromMeta(int meta)

    {

        IBlockState iblockstate = this.getDefaultState().withProperty(VARIANT, mossySlab.EnumType.byMetadata(meta & 7));

 

        if (!this.isDouble())

        {

            iblockstate = iblockstate.withProperty(HALF, (meta & 8) == 0 ? BlockSlab.EnumBlockHalf.BOTTOM : BlockSlab.EnumBlockHalf.TOP);

        }

 

        return iblockstate;

    }

   

    public int getMetaFromState(IBlockState state)

    {

        int i = 0;

        i = i | ((mossySlab.EnumType)state.getValue(VARIANT)).getMetadata();

 

        if (!this.isDouble() && state.getValue(HALF) == BlockSlab.EnumBlockHalf.TOP)

        {

            i |= 8;

        }

 

        return i;

    }

 

@Override

public String getUnlocalizedName(int meta) {

        return super.getUnlocalizedName() + "." + mossySlab.EnumType.byMetadata(meta).getUnlocalizedName();

}

   

@Override

public Comparable<?> getTypeForItem(ItemStack stack) {

        return mossySlab.EnumType.byMetadata(stack.getMetadata() & 7);

}

 

@Override

public IProperty<?> getVariantProperty() {

        return VARIANT;

}

 

    @SideOnly(Side.CLIENT)

    public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list)

    {

        if (itemIn != Item.getItemFromBlock(JungleBlocks.mossyslabDouble))

        {

            for (mossySlab.EnumType blockstoneslab$enumtype : mossySlab.EnumType.values())

            {

            list.add(new ItemStack(itemIn, 1, blockstoneslab$enumtype.getMetadata()));

            }

        }

    }

 

    public int damageDropped(IBlockState state)

    {

        return ((mossySlab.EnumType)state.getValue(VARIANT)).getMetadata();

    }

 

    protected final BlockStateContainer createBlockState() {

        if (this.isDouble()) {

            return new BlockStateContainer(this, new IProperty[] {VARIANT});

        } else {

            return new BlockStateContainer(

                this,

                new IProperty[] {HALF, VARIANT});

        }

    }

   

    public MapColor getMapColor(IBlockState state)

    {

        return ((mossySlab.EnumType)state.getValue(VARIANT)).getMapColor();

    }

   

@Override

public boolean isDouble() {

return false;

}

 

    public static class Double extends mossySlab

    {

        public boolean isDouble()

        {

            return true;

        }

    }

 

    public static class Half extends mossySlab

    {

        public boolean isDouble()

        {

            return false;

        }

    }

 

 

    public static enum EnumType implements IStringSerializable

    {

        MOSSY_SLAB(0, "mossy", MapColor.STONE),

        MOSSY_SMOOTH_SLAB(1, "mossy_smooth", MapColor.STONE);

 

 

        private static final mossySlab.EnumType[] META_LOOKUP = new mossySlab.EnumType[values().length];

        private final int meta;

        private final String name;

        private final MapColor mapColor;

 

        private EnumType(int p_i46391_3_, String p_i46391_4_, MapColor p_i46391_5_)

        {

            this.meta = p_i46391_3_;

            this.name = p_i46391_4_;

            this.mapColor = p_i46391_5_;

        }

 

        public int getMetadata()

        {

            return this.meta;

        }

 

        public MapColor getMapColor()

        {

            return this.mapColor;

        }

 

        public String toString()

        {

            return this.name;

        }

 

        public static mossySlab.EnumType byMetadata(int meta)

        {

            if (meta < 0 || meta >= META_LOOKUP.length)

            {

                meta = 0;

            }

 

            return META_LOOKUP[meta];

        }

 

        public String getName()

        {

            return this.name;

        }

 

        public String getUnlocalizedName()

        {

            return this.name;

        }

 

        static

        {

            for (mossySlab.EnumType blockstoneslabnew$enumtype : values())

            {

                META_LOOKUP[blockstoneslabnew$enumtype.getMetadata()] = blockstoneslabnew$enumtype;

            }

        }

    }

}

 

 

 

The definition and registration:

 

 

 

 

                mossyslabSingle = (BlockSlab) (new mossySlab.Half()).setUnlocalizedName("stoneMossySlab");

mossyslabDouble = (BlockSlab) (new mossySlab.Double()).setUnlocalizedName("stoneMossySlab");

 

 

                ItemSlab item = (ItemSlab) (new ItemSlab(JungleBlocks.mossyslabSingle, JungleBlocks.mossyslabSingle, JungleBlocks.mossyslabDouble)).setUnlocalizedName("mossySlab");

registerBlockSlab(mossyslabSingle, item, "mossy_slab"); 

        registerBlockSlab(mossyslabDouble, null, "mossy_double_slab");

 

public static void registerBlockSlab(Block block, ItemSlab item, String string)

{

block.setRegistryName(string);

GameRegistry.register(block);

if(item != null)

{

GameRegistry.register(item, block.getRegistryName());

}

       

}

 

ModelLoader.setCustomStateMapper(mossyslabSingle, (new StateMap.Builder()).withName(mossySlab.VARIANT).withSuffix("_slab").build());

                ModelLoader.setCustomStateMapper(mossyslabDouble, (new StateMap.Builder()).withName(mossySlab.VARIANT).withSuffix("_double_slab").build());

 

 

 

 

The render:

 

 

 

                registerSlabRender("mossy_slab", mossySlab.EnumType.MOSSY_SLAB.getMetadata(), JungleBlocks.mossyslabSingle);

registerSlabRender("mossy_smooth_slab", mossySlab.EnumType.MOSSY_SMOOTH_SLAB.getMetadata(), JungleBlocks.mossyslabSingle);

 

public static void registerSlabRender(String string, int i, Block block)

{

Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(block), i, new ModelResourceLocation(string, "inventory"));

}

 

 

 

edit: to remove commented out experiments/notes/old code

Posted

Where and when do you call your rendering-registration? Main, proxy, preInit, init, postInit?

 

Also, do not use Minecraft.getMinecraft().getRenderItem().getItemModelMesher(), use ModelLoader.setCustomModelResourceLocation instead, and be sure to call that in preInit.

Example would be, (by passing block)

ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(block), 0, new ModelResourceLocation(block.getRegistryName(), "inventory"));

Also previously known as eAndPi.

"Pi, is there a station coming up where we can board your train of thought?" -Kronnn

Published Mods: Underworld

Handy links: Vic_'s Forge events Own WIP Tutorials.

Posted

ta. problem solved. the original call was in the init event: the itemmeshers would crash the game if put in preinit. moot now, since i switched t the model loaders which have to be put in preinit. one thing to note, the string below had to have the modid added to completely cure the problem.

 

  public static void registerSlabRender(String string, int i, Block block)

  {

        //ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(block), i, new ModelResourceLocation("thejungle:" + string, "inventory"));

 

  }

Posted

ta. problem solved. the original call was in the init event: the itemmeshers would crash the game if put in preinit. moot now, since i switched t the model loaders which have to be put in preinit. one thing to note, the string below had to have the modid added to completely cure the problem.

 

  public static void registerSlabRender(String string, int i, Block block)

  {

        //ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(block), i, new ModelResourceLocation("thejungle:" + string, "inventory"));

 

  }

 

To quote the Block#setRegistryName documentation:

/**

    * Sets a unique name for this Item. This should be used for uniquely identify the instance of the Item.

    * This is the valid replacement for the atrocious 'getUnlocalizedName().substring(6)' stuff that everyone does.

    * Unlocalized names have NOTHING to do with unique identifiers. As demonstrated by vanilla blocks and items.

    *

    * The supplied name will be prefixed with the currently active mod's modId.

    * If the supplied name already has a prefix that is different, it will be used and a warning will be logged.

    *

    * If a name already exists, or this Item is already registered in a registry, then an IllegalStateException is thrown.

    *

    * Returns 'this' to allow for chaining.

    *

    * @param name Unique registry name

    * @return This instance

    */

Same thing applies to, random strings. You are meant to use RegistryName here, but you imitate it using a string that does what RegistryName does.

It's unlikely, but if ANY mod, literally any ever has a method that checks blocks, and uses Block#getRegistryName, on this block, guess what'll happen. Bam, nullpointerexception.

Sorry if I sound harsh, but this is what you are meant to use! It's actually dangerous to do what you are doing now.

Also previously known as eAndPi.

"Pi, is there a station coming up where we can board your train of thought?" -Kronnn

Published Mods: Underworld

Handy links: Vic_'s Forge events Own WIP Tutorials.

Posted

EDIT: having dwelt on the below, i have to ask if you're sure about the registryname in this instance. the slab variants dont have registry names. in anycase at this point the game just wants the name of the blockstate file. calling the registry name is highly convenient, but not essential. the blockstate file doesnt have to have the registry name, the two simply have to match.

 

EDIT: there are two seperate render calls one for each slab variant. its the passed in block that doesnt change.

 

the code was largely created by scouring the vanilla stuff, which uses a string. i say this merely by way of explaining it. i had looked at it after making the changes you suggested above and thought that it seemed identical to the registry name. but theres a snag here. changing the string to block.getregistryname, while not throwing up errors, gives both slabs the same texture in inventory and as an entity item. this is particularly odd as the passed in string does not change, the line in the post above is called only once.

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
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
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.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
    • Do you use features of inventory profiles next (ipnext) or is there a change without it?
    • Remove rubidium - you are already using embeddium, which is a fork of rubidium
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.