Jump to content

[1.14.4]Making a tile entity


DarkAssassin

Recommended Posts

i still have troubles creating a functional tile entity

 

the Error log i´m getting is this:

 

A TileEntity type me.spawntweak.lists.MobSpawnerTileEntity has thrown an exception trying to write state. It will not persist, Report this to the mod author java.lang.RuntimeException: class me.spawntweak.lists.MobSpawnerTileEntity is missing a mapping

 

[02:29:55] [Server thread/ERROR] [minecraft/Chunk]: A TileEntity type fabian.spawntweak.lists.MobSpawnerTileEntity has thrown an exception trying to write state. It will not persist, Report this to the mod author java.lang.RuntimeException: class me.spawntweak.lists.MobSpawnerTileEntity is missing a mapping! This is a bug!         at net.minecraft.tileentity.TileEntity.writeInternal(TileEntity.java:72) ~[?:?] {re:classloading}         at net.minecraft.tileentity.TileEntity.write(TileEntity.java:66) ~[?:?] {re:classloading}         at me.spawntweak.lists.MobSpawnerTileEntity.write(MobSpawnerTileEntity.java:72) ~[?:?] {re:classloading}         at net.minecraft.world.chunk.Chunk.func_223134_j(Chunk.java:444) ~[?:?] {re:classloading}         at net.minecraft.world.chunk.storage.ChunkSerializer.write(ChunkSerializer.java:303) ~[?:?] {re:classloading}         at net.minecraft.world.server.ChunkManager.func_219229_a(ChunkManager.java:677) ~[?:?] {re:classloading}         at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174) [?:1.8.0_241] {}         at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) [?:1.8.0_241] {}         at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) [?:1.8.0_241] {}         at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382) [?:1.8.0_241] {}         at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482) [?:1.8.0_241] {}         at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472) [?:1.8.0_241] {}         at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151) [?:1.8.0_241] {}         at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174) [?:1.8.0_241] {}         at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) [?:1.8.0_241] {}         at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418) [?:1.8.0_241] {}         at net.minecraft.world.server.ChunkManager.save(ChunkManager.java:336) [?:?] {re:classloading}         at net.minecraft.world.server.ServerChunkProvider.save(ServerChunkProvider.java:309) [?:?] {re:classloading,pl:accesstransformer:B}         at net.minecraft.world.server.ServerWorld.save(ServerWorld.java:770) [?:?] {re:classloading}         at net.minecraft.server.MinecraftServer.save(MinecraftServer.java:528) [?:?] {re:classloading,pl:accesstransformer:B}         at net.minecraft.server.MinecraftServer.stopServer(MinecraftServer.java:571) [?:?] {re:classloading,pl:accesstransformer:B}         at net.minecraft.server.integrated.IntegratedServer.stopServer(IntegratedServer.java:235) [?:?] {re:classloading,pl:runtimedistcleaner:A}         at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:685) [?:?] {re:classloading,pl:accesstransformer:B}         at java.lang.Thread.run(Thread.java:748) [?:1.8.0_241] {}

main:

@Mod("spawntweak")
public class SpawnTweak{

    
    public static SpawnTweak instance;
    public static final String modid = "spawntweak";
    private static final Logger logger = LogManager.getLogger(modid);
    
    public SpawnTweak() {
        instance=this;
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::clientRegistries);
        MinecraftForge.EVENT_BUS.register(this);
        
        
        }
    
private void setup(final FMLCommonSetupEvent event) {
        
        logger.info("setup registered");
        
    }
    private void clientRegistries(final FMLClientSetupEvent event) {
        
        logger.info("client registered");
        
    }
    
    @Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD)
    public static class RegistryEvents{
        
        

        @SubscribeEvent
        public static void registerItems(final RegistryEvent.Register<Item> event) {
            event.getRegistry().registerAll(
                    ItemList.spawner= new BlockItem(BlockList.spawner, new Item.Properties().group(ItemGroup.TRANSPORTATION)).setRegistryName(BlockList.spawner.getRegistryName()));}

        @SubscribeEvent
        public static void registerBlocks(final RegistryEvent.Register<Block> event) {
            event.getRegistry().registerAll(
            
            BlockList.spawner = new MobSpawner(MobSpawner.Properties.create(Material.IRON).hardnessAndResistance(3.0f, 3.0f).sound(SoundType.METAL)).setRegistryName("minecraft:spawner"));
            logger.info("Blocks registered");
        }

        
        @SubscribeEvent
        public static void registerTileEntety(RegistryEvent.Register<TileEntityType<?>> event) {

            
         TileEntityType<?> type = TileEntityType.Builder.create(MobSpawnerTileEntity::new, BlockList.spawner).build(null);
          type.setRegistryName("minecraft:mob_spawner");
          event.getRegistry().register(type);
        }
   
    }    
        
    }    

Block

public class MobSpawner extends Block{
    
    
    public MobSpawner(Properties properties) {
        super(Properties.create(Material.IRON).hardnessAndResistance(3.0f, 3.0f).sound(SoundType.METAL));
      
    }
   
    @Override
    public TileEntity createTileEntity(BlockState state, IBlockReader world) {
        return new MobSpawnerTileEntity();
    }
    public BlockRenderLayer getRenderLayer()
    {
        return BlockRenderLayer.TRANSLUCENT;
    }
    
    @Override
    public boolean hasTileEntity(BlockState state) {
        return true;
    }

}

Tile Entity

public class MobSpawnerTileEntity extends TileEntity implements ITickableTileEntity {
   private final AbstractSpawner spawnerLogic = new AbstractSpawner() {
      public void broadcastEvent(int id) {
         MobSpawnerTileEntity.this.world.addBlockEvent(MobSpawnerTileEntity.this.pos, Blocks.SPAWNER, id, 0);
      }

      public World getWorld() {
         return MobSpawnerTileEntity.this.world;
      }

      public BlockPos getSpawnerPosition() {
         return MobSpawnerTileEntity.this.pos;
      }

      public void setNextSpawnData(WeightedSpawnerEntity nextSpawnData) {
         super.setNextSpawnData(nextSpawnData);
         if (this.getWorld() != null) {
            BlockState blockstate = this.getWorld().getBlockState(this.getSpawnerPosition());
            this.getWorld().notifyBlockUpdate(MobSpawnerTileEntity.this.pos, blockstate, blockstate, 4);
         }

      }
   };
   
   public void tick(BlockState state, World worldIn, BlockPos pos, Random random) {
          if (!worldIn.isRemote) {
             if (worldIn.isBlockPowered(pos)) {
                AbstractSpawner.isActivated  = true;
           }
             else 
        {
            AbstractSpawner.isActivated =false;     
                 
                 
                 
        }  
       }

    
    
     }
   
   public MobSpawnerTileEntity() {
      super(TileEntityType.MOB_SPAWNER);
   }

   public void read(CompoundNBT compound) {
      super.read(compound);
      this.spawnerLogic.read(compound);
   }

   public CompoundNBT write(CompoundNBT compound) {
      super.write(compound);
      this.spawnerLogic.write(compound);
      return compound;
   }

   public void tick() {
      this.spawnerLogic.tick();
   }

  
   @Nullable
   public SUpdateTileEntityPacket getUpdatePacket() {
      return new SUpdateTileEntityPacket(this.pos, 1, this.getUpdateTag());
   }

  
   public CompoundNBT getUpdateTag() {
      CompoundNBT compoundnbt = this.write(new CompoundNBT());
      compoundnbt.remove("SpawnPotentials");
      return compoundnbt;
   }

 
   public boolean receiveClientEvent(int id, int type) {
      return this.spawnerLogic.setDelayToMin(id) ? true : super.receiveClientEvent(id, type);
   }

 
   public boolean onlyOpsCanSetNbt() {
      return true;
   }

   public AbstractSpawner getSpawnerBaseLogic() {
      return this.spawnerLogic;
   }
}

Abstract Spawner

public abstract class AbstractSpawner {
   private static final Logger LOGGER = LogManager.getLogger();
   public static boolean isActivated;
   private int spawnDelay = 20;
   private final List<WeightedSpawnerEntity> potentialSpawns = Lists.newArrayList();
   private WeightedSpawnerEntity spawnData = new WeightedSpawnerEntity();
   private double mobRotation;
   private double prevMobRotation;
   private int minSpawnDelay = 200;
   private int maxSpawnDelay = 800;
   private int spawnCount = 4;
   private Entity cachedEntity;
   private int maxNearbyEntities = 6;
   private int activatingRangeFromPlayer = 16;
   private int spawnRange = 4;

   @SuppressWarnings("resource")
@Nullable
   private ResourceLocation getEntityId() {
      String s = this.spawnData.getNbt().getString("id");

      try {
         return StringUtils.isNullOrEmpty(s) ? null : new ResourceLocation(s);
      } catch (ResourceLocationException var4) {
         BlockPos blockpos = this.getSpawnerPosition();
         LOGGER.warn("Invalid entity id '{}' at spawner {}:[{},{},{}]", s, this.getWorld().dimension.getType(), blockpos.getX(), blockpos.getY(), blockpos.getZ());
         return null;
      }
   }

   @SuppressWarnings("deprecation")
public void setEntityType(EntityType<?> type) {
      this.spawnData.getNbt().putString("id", Registry.ENTITY_TYPE.getKey(type).toString());
   }

   /**
    * Returns true if there's a player close enough to this mob spawner to activate it.
    */
   public boolean isActivated() {
      BlockPos blockpos = this.getSpawnerPosition();
      return this.getWorld().isPlayerWithin((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D, (double)this.activatingRangeFromPlayer);
   }

   public void tick() {
      
      if (!this.isActivated()||!isActivated) {
         this.prevMobRotation = this.mobRotation;
      } else {
         World world = this.getWorld();
         BlockPos blockpos = this.getSpawnerPosition();
         if (world.isRemote) {
            double d3 = (double)((float)blockpos.getX() + world.rand.nextFloat());
            double d4 = (double)((float)blockpos.getY() + world.rand.nextFloat());
            double d5 = (double)((float)blockpos.getZ() + world.rand.nextFloat());
            world.addParticle(ParticleTypes.SMOKE, d3, d4, d5, 0.0D, 0.0D, 0.0D);
            world.addParticle(ParticleTypes.FLAME, d3, d4, d5, 0.0D, 0.0D, 0.0D);
            if (this.spawnDelay > 0) {
               --this.spawnDelay;
            }

            this.prevMobRotation = this.mobRotation;
            this.mobRotation = (this.mobRotation + (double)(1000.0F / ((float)this.spawnDelay + 200.0F))) % 360.0D;
         } else {
            if (this.spawnDelay == -1) {
               this.resetTimer();
            }

            if (this.spawnDelay > 0) {
               --this.spawnDelay;
               return;
            }

            boolean flag = false;

            for(int i = 0; i < this.spawnCount; ++i) {
               CompoundNBT compoundnbt = this.spawnData.getNbt();
               Optional<EntityType<?>> optional = EntityType.readEntityType(compoundnbt);
               if (!optional.isPresent()) {
                  this.resetTimer();
                  return;
               }

               ListNBT listnbt = compoundnbt.getList("Pos", 6);
               int j = listnbt.size();
               double d0 = j >= 1 ? listnbt.getDouble(0) : (double)blockpos.getX() + (world.rand.nextDouble() - world.rand.nextDouble()) * (double)this.spawnRange + 0.5D;
               double d1 = j >= 2 ? listnbt.getDouble(1) : (double)(blockpos.getY() + world.rand.nextInt(3) - 1);
               double d2 = j >= 3 ? listnbt.getDouble(2) : (double)blockpos.getZ() + (world.rand.nextDouble() - world.rand.nextDouble()) * (double)this.spawnRange + 0.5D;
               if (world.areCollisionShapesEmpty(optional.get().func_220328_a(d0, d1, d2)) && EntitySpawnPlacementRegistry.func_223515_a(optional.get(), world.getWorld(), SpawnReason.SPAWNER, new BlockPos(d0, d1, d2), world.getRandom())) {
                  Entity entity = EntityType.func_220335_a(compoundnbt, world, (p_221408_6_) -> {
                     p_221408_6_.setLocationAndAngles(d0, d1, d2, p_221408_6_.rotationYaw, p_221408_6_.rotationPitch);
                     return p_221408_6_;
                  });
                  if (entity == null) {
                     this.resetTimer();
                     return;
                  }

                  int k = world.getEntitiesWithinAABB(entity.getClass(), (new AxisAlignedBB((double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ(), (double)(blockpos.getX() + 1), (double)(blockpos.getY() + 1), (double)(blockpos.getZ() + 1))).grow((double)this.spawnRange)).size();
                  if (k >= this.maxNearbyEntities) {
                     this.resetTimer();
                     return;
                  }

                  entity.setLocationAndAngles(entity.posX, entity.posY, entity.posZ, world.rand.nextFloat() * 360.0F, 0.0F);
                  if (entity instanceof MobEntity) {
                     MobEntity mobentity = (MobEntity)entity;
                     if (!EventFactory.canEntitySpawnSpawner(mobentity, world, (float)entity.posX, (float)entity.posY, (float)entity.posZ, this)) {
                        continue;
                     }

                     if (this.spawnData.getNbt().size() == 1 && this.spawnData.getNbt().contains("id", 8)) {
                        ((MobEntity)entity).onInitialSpawn(world, world.getDifficultyForLocation(new BlockPos(entity)), SpawnReason.SPAWNER, (ILivingEntityData)null, (CompoundNBT)null);
                     }
                  }

                  this.func_221409_a(entity);
                  world.playEvent(2004, blockpos, 0);
                  if (entity instanceof MobEntity) {
                     ((MobEntity)entity).spawnExplosionParticle();
                  }

                  flag = true;
               }
            }

            if (flag) {
               this.resetTimer();
            }
         }

      }
   }

   private void func_221409_a(Entity p_221409_1_) {
      if (this.getWorld().addEntity(p_221409_1_)) {
         for(Entity entity : p_221409_1_.getPassengers()) {
            this.func_221409_a(entity);
         }

      }
   }

   @SuppressWarnings("resource")
private void resetTimer() {
      if (this.maxSpawnDelay <= this.minSpawnDelay) {
         this.spawnDelay = this.minSpawnDelay;
      } else {
         int i = this.maxSpawnDelay - this.minSpawnDelay;
         this.spawnDelay = this.minSpawnDelay + this.getWorld().rand.nextInt(i);
      }

      if (!this.potentialSpawns.isEmpty()) {
         this.setNextSpawnData(WeightedRandom.getRandomItem(this.getWorld().rand, this.potentialSpawns));
      }

      this.broadcastEvent(1);
   }

   @SuppressWarnings("resource")
public void read(CompoundNBT nbt) {
      this.spawnDelay = nbt.getShort("Delay");
      this.potentialSpawns.clear();
      if (nbt.contains("SpawnPotentials", 9)) {
         ListNBT listnbt = nbt.getList("SpawnPotentials", 10);

         for(int i = 0; i < listnbt.size(); ++i) {
            this.potentialSpawns.add(new WeightedSpawnerEntity(listnbt.getCompound(i)));
         }
      }

      if (nbt.contains("SpawnData", 10)) {
         this.setNextSpawnData(new WeightedSpawnerEntity(1, nbt.getCompound("SpawnData")));
      } else if (!this.potentialSpawns.isEmpty()) {
         this.setNextSpawnData(WeightedRandom.getRandomItem(this.getWorld().rand, this.potentialSpawns));
      }

      if (nbt.contains("MinSpawnDelay", 99)) {
         this.minSpawnDelay = nbt.getShort("MinSpawnDelay");
         this.maxSpawnDelay = nbt.getShort("MaxSpawnDelay");
         this.spawnCount = nbt.getShort("SpawnCount");
      }

      if (nbt.contains("MaxNearbyEntities", 99)) {
         this.maxNearbyEntities = nbt.getShort("MaxNearbyEntities");
         this.activatingRangeFromPlayer = nbt.getShort("RequiredPlayerRange");
      }

      if (nbt.contains("SpawnRange", 99)) {
         this.spawnRange = nbt.getShort("SpawnRange");
      }

      if (this.getWorld() != null) {
         this.cachedEntity = null;
      }

   }

   public CompoundNBT write(CompoundNBT compound) {
      ResourceLocation resourcelocation = this.getEntityId();
      if (resourcelocation == null) {
         return compound;
      } else {
         compound.putShort("Delay", (short)this.spawnDelay);
         compound.putShort("MinSpawnDelay", (short)this.minSpawnDelay);
         compound.putShort("MaxSpawnDelay", (short)this.maxSpawnDelay);
         compound.putShort("SpawnCount", (short)this.spawnCount);
         compound.putShort("MaxNearbyEntities", (short)this.maxNearbyEntities);
         compound.putShort("RequiredPlayerRange", (short)this.activatingRangeFromPlayer);
         compound.putShort("SpawnRange", (short)this.spawnRange);
         compound.put("SpawnData", this.spawnData.getNbt().copy());
         ListNBT listnbt = new ListNBT();
         if (this.potentialSpawns.isEmpty()) {
            listnbt.add(this.spawnData.toCompoundTag());
         } else {
            for(WeightedSpawnerEntity weightedspawnerentity : this.potentialSpawns) {
               listnbt.add(weightedspawnerentity.toCompoundTag());
            }
         }

         compound.put("SpawnPotentials", listnbt);
         return compound;
      }
   }

   @OnlyIn(Dist.CLIENT)
   public Entity getCachedEntity() {
      if (this.cachedEntity == null) {
         this.cachedEntity = EntityType.func_220335_a(this.spawnData.getNbt(), this.getWorld(), Function.identity());
         if (this.spawnData.getNbt().size() == 1 && this.spawnData.getNbt().contains("id", 8) && this.cachedEntity instanceof MobEntity) {
            ((MobEntity)this.cachedEntity).onInitialSpawn(this.getWorld(), this.getWorld().getDifficultyForLocation(new BlockPos(this.cachedEntity)), SpawnReason.SPAWNER, (ILivingEntityData)null, (CompoundNBT)null);
         }
      }

      return this.cachedEntity;
   }

   /**
    * Sets the delay to minDelay if parameter given is 1, else return false.
    */
   public boolean setDelayToMin(int delay) {
      if (delay == 1 && this.getWorld().isRemote) {
         this.spawnDelay = this.minSpawnDelay;
         return true;
      } else {
         return false;
      }
   }

   public void setNextSpawnData(WeightedSpawnerEntity nextSpawnData) {
      this.spawnData = nextSpawnData;
   }

   public abstract void broadcastEvent(int id);

   public abstract World getWorld();

   public abstract BlockPos getSpawnerPosition();

   @OnlyIn(Dist.CLIENT)
   public double getMobRotation() {
      return this.mobRotation;
   }

   @OnlyIn(Dist.CLIENT)
   public double getPrevMobRotation() {
      return this.prevMobRotation;
   }

   @Nullable
   public Entity getSpawnerEntity() {
      return null;
   }
}

    

Link to comment
Share on other sites

1 hour ago, CHEESEBOT314 said:

When creating the new TileEntityType store it in a public static final field and use that instead of the old one.

Or better still, use ObjectHolder or DeferredRegistry. There are plenty of topics on both if you search this site.

Link to comment
Share on other sites

2 hours ago, CHEESEBOT314 said:

The reason this error is happening is that you are using the old TileEntityType in your TileEntity constructor instead of the newly registered one. When creating the new TileEntityType store it in a public static final field and use that instead of the old one.

i have now done this

 

    
         TileEntityType<?> type = TileEntityType.Builder.create(MobSpawnerTileEntity::new, BlockList.spawner).build(null);
          type.setRegistryName("minecraft:mob_spawner");
          event.getRegistry().register(type);
          TEList.mob_spawner = type;

 

and in the tile entity class done this

 

TileEntityType.MOB_SPAWNER ==> TEList.mob_spawner

and now the game neither crashes nor spews out error messages and now the entity is registered, but the tile entity doesn´t work as excpected. instead of behaving like the vanilla spawner (i used the vanilla code for spawners and added

public void tick(BlockState state, World worldIn, BlockPos pos, Random random) {
          if (!worldIn.isRemote) {
             if (worldIn.isBlockPowered(pos)) {
                AbstractSpawner.isActivated  = true;
           }
             else 
        {
            AbstractSpawner.isActivated =false;     
                 
                 
                 
        }  
       }

    
    
     }) but it behaves lika a normal block even when i comment the changes out. also no errors are shown

Link to comment
Share on other sites

4 minutes ago, DarkAssassin said:

public void tick(BlockState state, World worldIn, BlockPos pos, Random random) {
          if (!worldIn.isRemote) {
             if (worldIn.isBlockPowered(pos)) {
                AbstractSpawner.isActivated  = true;
           }
             else 
        {
            AbstractSpawner.isActivated =false;     
                 
                 
                 
        }  
       }

    
    
     }

You probably need to call super#tick at some point.

Link to comment
Share on other sites

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



×
×
  • Create New...

Important Information

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