Jump to content

Recommended Posts

Posted (edited)

I've created my own spawner block, called LimitedSpawnerBlock (extending SpawnerBlock), which returns a LimitedMobSpawnerTileEntity (extending MobSpawnerTileEntity) upon calling the overriden LimitedSpawnerBlock#createTileEntity, which owns a LimitedAbstractSpawner (extending AbstractSpawner)--- set up just like the Vanilla code...

My goal is for the spawner block to break after so many spawns (like how RLCraft spawners have health). The LimitedMobSpawnerTileEntity stores health, which decrements on spawn, and calls for the LimitedSpawnerBlock to be deleted from the world when health reaches zero.

I've registered the LimitedSpawnerBlock as "minecraft:spawner" and the TileEntityType<LimitedMobSpawnerTileEntity> as "minecraft:mob_spawner". 

I've read the docs on tile entities and yet get this error, crashing my game when I place a spawner, and not loading chunks that should have a spawner:

Spoiler
[15:15:58] [Render thread/WARN] [minecraft/ClientPlayNetHandler]: Received passengers for unknown entity
[15:16:08] [Server thread/ERROR] [minecraft/Chunk]: A TileEntity type com.izofar.izomod.tileentity.LimitedMobSpawnerTileEntity has thrown an exception trying to write state. It will not persist, Report this to the mod author
java.lang.RuntimeException: class com.izofar.izomod.tileentity.LimitedMobSpawnerTileEntity is missing a mapping! This is a bug!
        at net.minecraft.tileentity.TileEntity.saveMetadata(TileEntity.java:64) ~[forge:?] {re:classloading}
        at net.minecraft.tileentity.TileEntity.save(TileEntity.java:58) ~[forge:?] {re:classloading}
        at net.minecraft.tileentity.MobSpawnerTileEntity.save(MobSpawnerTileEntity.java:47) ~[forge:?] {re:classloading}
        at com.izofar.izomod.tileentity.LimitedMobSpawnerTileEntity.save(LimitedMobSpawnerTileEntity.java:52) ~[?:?] {re:classloading}
        at net.minecraft.world.chunk.Chunk.getBlockEntityNbtForSaving(Chunk.java:427) ~[forge:?] {re:classloading}
        at net.minecraft.world.chunk.storage.ChunkSerializer.write(ChunkSerializer.java:287) ~[forge:?] {re:classloading}
        at net.minecraft.world.server.ChunkManager.save(ChunkManager.java:682) ~[forge:?] {re:classloading}
        at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174) ~[?:1.8.0_291] {}
        at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[?:1.8.0_291] {}
        at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[?:1.8.0_291] {}
        at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1384) ~[?:1.8.0_291] {}
        at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482) ~[?:1.8.0_291] {}
        at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472) ~[?:1.8.0_291] {}
        at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151) ~[?:1.8.0_291] {}
        at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174) ~[?:1.8.0_291] {}
        at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[?:1.8.0_291] {}
        at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418) ~[?:1.8.0_291] {}
        at net.minecraft.world.server.ChunkManager.saveAllChunks(ChunkManager.java:337) ~[forge:?] {re:classloading}
        at net.minecraft.world.server.ServerChunkProvider.save(ServerChunkProvider.java:307) ~[forge:?] {re:classloading,pl:accesstransformer:B}
        at net.minecraft.world.server.ServerWorld.save(ServerWorld.java:698) ~[forge:?] {re:classloading}
        at net.minecraft.server.MinecraftServer.saveAllChunks(MinecraftServer.java:532) ~[forge:?] {re:classloading,pl:accesstransformer:B}
        at net.minecraft.server.MinecraftServer.stopServer(MinecraftServer.java:568) ~[forge:?] {re:classloading,pl:accesstransformer:B}
        at net.minecraft.server.integrated.IntegratedServer.stopServer(IntegratedServer.java:167) ~[forge:?] {re:classloading,pl:runtimedistcleaner:A}
        at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:679) ~[forge:?] {re:classloading,pl:accesstransformer:B}
        at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:232) ~[forge:?] {re:classloading,pl:accesstransformer:B}
        at java.lang.Thread.run(Thread.java:748) [?:1.8.0_291] {}

This is my LimitedMobSpawnerTileEntity class:

Spoiler
public class LimitedMobSpawnerTileEntity extends MobSpawnerTileEntity {

	private AbstractSpawner spawner;
	
	public LimitedMobSpawnerTileEntity() {
		super();
		this.spawner = new LimitedAbstractSpawner(this) {
			public void broadcastEvent(int p_98267_1_) {
				LimitedMobSpawnerTileEntity.this.level.blockEvent(LimitedMobSpawnerTileEntity.this.worldPosition, ModBlocks.LIMITED_SPAWNER, p_98267_1_, 0);		
			}

			public World getLevel() {
				return LimitedMobSpawnerTileEntity.this.level;
			}

			public BlockPos getPos() {
				return LimitedMobSpawnerTileEntity.this.worldPosition;
			}
			
			public void setNextSpawnData(WeightedSpawnerEntity p_184993_1_) {
		        super.setNextSpawnData(p_184993_1_);
		        if (this.getLevel() != null) {
		           BlockState blockstate = this.getLevel().getBlockState(this.getPos());
		           this.getLevel().sendBlockUpdated(LimitedMobSpawnerTileEntity.this.worldPosition, blockstate, blockstate, 4);
		        }
		     }
		};
	}
	
	public void destroy(World world) {
		world.removeBlockEntity(this.getBlockPos());
	}
	
	@Override
	public CompoundNBT save(CompoundNBT nbt) {
		return super.save(nbt);
	}

	@Override
	public void load(BlockState state, CompoundNBT nbt) {
		super.load(state, nbt);
	}
}

I'm not sure what is wrong with the mapping?

Edited by izofar
Posted (edited)

Update: I resolved the mapping issue by registering with .setRegistryName("mob_spawner") instead of  .setRegistryName("minecraft", "mob_spawner"). I still get the following errors, and the spawner blocks that spawn are empty:

[15:26:03] [Render thread/WARN] [minecraft/ClientPlayNetHandler]: Received passengers for unknown entity
[15:26:03] [Server thread/WARN] [minecraft/TileEntity]: Block entity invalid: minecraft:mob_spawner @ BlockPos{x=651, y=69, z=-10735}

I've tracked down that the TileEntity messages comes from isValid(), which checks if it is in the Set of valid blocks, determined by:

public TileEntityType(Supplier<? extends T> p_i51497_1_, Set<Block> p_i51497_2_, Type<?> p_i51497_3_) {
      this.factory = p_i51497_1_;
      this.validBlocks = p_i51497_2_;
      this.dataType = p_i51497_3_;
   }

But, shouldn't this be handled by the TileEntityType registry?

Edited by izofar
Posted (edited)
14 hours ago, Luis_ST said:

show where you register your TE

I plan to move to deferred registries when I port to 1.17, but I am currently working with the registry events approach. My declaration is:

public static TileEntityType<LimitedMobSpawnerTileEntity> LIMITED_MOB_SPAWNER = (TileEntityType<LimitedMobSpawnerTileEntity>)TileEntityType.Builder.of(LimitedMobSpawnerTileEntity::new, ModBlocks.LIMITED_SPAWNER).build(null).setRegistryName("mob_spawner");

In which I register it here:

@SubscribeEvent
    public static void onTileEntitiesRegistry(final RegistryEvent.Register<TileEntityType<?>> tileEntityRegistryEvent) {
        tileEntityRegistryEvent.getRegistry().registerAll(
        		
        		ModTileEntityTypes.LIMITED_MOB_SPAWNER
        		
        );
    }

EDIT:

Using the above code, I just get a bunch of empty spawners. When I change the TE registration to "minecraft:mob_spawner" then I get the mapping error again. I think this is closer to what I want, but I may be missing a step. Looking at the mapping error I get, I traced it to my TileEntity#save override, in which the error comes from the check:

private CompoundNBT saveMetadata(CompoundNBT p_189516_1_) {
      ResourceLocation resourcelocation = TileEntityType.getKey(this.getType());
      if (resourcelocation == null) {
         throw new RuntimeException(this.getClass() + " is missing a mapping! This is a bug!");
      } else {
         ...
         return p_189516_1_;
      }
   }

The TileEntityType.getKey method uses depreciated methods, so I'm not sure how to bug fix that, but I believe it is just looking for the name to which I registered the TE.  

EDIT:

I figured out that because my LimitedSpawnerTileEntity was extending SpawnerTileEntity, that the constructor was passing TileEntityType.MOB_SPAWNER to TileEntity through super, even thought I should have passed ModTileEntityType.LIMITED_MOB_SPAWNER. Once I did that, and removed the SpawnerTileEntity extension and extended TileEntity directly, the mapping was resolved. I still have an issue with modifying the existing spawner behavior, because now when dungeons feature checks if the spawner is an instance of SpawnerTileEntity, it returns false. I know that Java inheritence doesn't allow for a way to access the super of the super (intending to pass the modded TE type instead), how else should I best do this?

Edited by izofar
Posted
12 minutes ago, diesieben07 said:

That means you need to create your registry objects in the registry events and you need to use @ObjectHolder to inject them into fields. Your current code is not correct.

Currently, I have a init package with my ModBlocks, ModItems, ModEntityTypes, etc. abstract classes that initialize the registry objects as class fields. Does it suffice to use @ObjectHolder("modid") above the class name in each class? My runClient has worked so far without these annotations... are these necessary for build, then? All of my registry objects are currently public static. Should I use final on all objects?

Also, regarding the original topic, I updated my last post with the inheritance issue I am running into.

Posted (edited)
18 minutes ago, izofar said:

Should I use final on all objects?

when a Field can be final it should be

Edit: forgot to say i would recommend you to use DeferredRegister

Edited by Luis_ST
Posted

Thank you both... as for overriding spawners, if I want each spawner to have its own health, how can I make my modded spawner TE a subclass of the vanilla spawner TE, but maintain the mappings by passing the modded TE type through to the TileEntity super-superclass?

Posted
7 minutes ago, izofar said:

how can I make my modded spawner TE a subclass of the vanilla spawner TE, but maintain the mappings by passing the modded TE type through to the TileEntity super-superclass?

Basically you can't.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted
5 minutes ago, Draco18s said:

Basically you can't.

Since all I'm basically doing with the subclass is storing a "health" field, is storing this as an NBT in the spawner TE that already exists feasible (using special spawn events and getting the spawner TE that way)?

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
×
×
  • Create New...

Important Information

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