/** * Make forge not spew "dangerous alternative prefix" messages in this block. */ public static void shutupForge(Runnable op) { Logger log = (Logger) FMLLog.log; try { Object privateConfig = ReflectionHelper.findField(Logger.class, "privateConfig").get(log); Field intLevelF = ReflectionHelper.findField(privateConfig.getClass(), "intLevel"); int intLevel = (int) intLevelF.get(privateConfig); intLevelF.set(privateConfig, 299); // disable WARN logging try { op.run(); } finally { intLevelF.set(privateConfig, intLevel); } } catch (IllegalAccessException e) { e.printStackTrace(); } }
private void makeOurList() { if (serverListInternetField == null) { if (serverListInternetField == null) { serverListInternetField = ReflectionHelper.findField(ServerSelectionList.class, "field_148198_l", "serverListInternet"); serverListInternetField.setAccessible(true); } } try { ourList = (List<ServerListEntryPublic>) serverListInternetField.get(this); } catch (IllegalAccessException e) { CreeperHost.logger.warn("Reflection to get server list failed.", e); } }
private void setServerList(ServerListPublic serverList) { ourSavedServerList = serverList; if (savedServerListField == null) { savedServerListField = ReflectionHelper.findField(GuiMultiplayer.class, "field_146804_i", "savedServerList"); savedServerListField.setAccessible(true); } try { savedServerListField.set(this, serverList); } catch (IllegalAccessException e) { CreeperHost.logger.error("Unable to set server list", e); } }
private void setLanServerDetector(LanServerDetector.ThreadLanServerFind detector) { ourLanServerDetector = detector; if (lanServerDetectorField == null) { lanServerDetectorField = ReflectionHelper.findField(GuiMultiplayer.class, "field_146800_B", "lanServerDetector"); lanServerDetectorField.setAccessible(true); } try { lanServerDetectorField.set(this, detector); } catch (IllegalAccessException e) { CreeperHost.logger.error("Unable to set server list", e); } }
private void setLanServerList(LanServerDetector.LanServerList detector) { ourLanServerList = detector; if (lanServerListField == null) { lanServerListField = ReflectionHelper.findField(GuiMultiplayer.class, "field_146799_A", "lanServerList"); lanServerListField.setAccessible(true); } try { lanServerListField.set(this, detector); } catch (IllegalAccessException e) { CreeperHost.logger.error("Unable to set server list", e); } }
private void setServerListSelector(ServerSelectionListPublic list) { ourServerListSelector = list; if (serverListSelectorField == null) { serverListSelectorField = ReflectionHelper.findField(GuiMultiplayer.class, "field_146803_h", "serverListSelector"); serverListSelectorField.setAccessible(true); } try { serverListSelectorField.set(this, list); } catch (IllegalAccessException e) { CreeperHost.logger.error("Unable to set server list", e); } }
private static String getTabLabel(CreativeTabs tab) { if (tabLabelField == null) { tabLabelField = ReflectionHelper.findField(CreativeTabs.class, "tabLabel", "field_78034_o", "o"); tabLabelField.setAccessible(true); } try { return (String) tabLabelField.get(tab); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; }
@SubscribeEvent public static void onRenderPlayer(RenderPlayerEvent.Post event) { EntityPlayer player = event.getEntityPlayer(); String uuid = player.getUUID(player.getGameProfile()).toString(); if(player instanceof AbstractClientPlayer && UUIDS.contains(uuid) && !done.contains(player)) { AbstractClientPlayer clplayer = (AbstractClientPlayer) player; if(clplayer.hasPlayerInfo()) { NetworkPlayerInfo info = ReflectionHelper.getPrivateValue(AbstractClientPlayer.class, clplayer, ObfuscatedNames.PLAYER_INFO); Map<MinecraftProfileTexture.Type, ResourceLocation> textures = ReflectionHelper.getPrivateValue(NetworkPlayerInfo.class, info, ObfuscatedNames.PLAYER_TEXTURES); ResourceLocation loc = new ResourceLocation("proxyslib", "textures/whoknows/special_cape.png"); textures.put(MinecraftProfileTexture.Type.CAPE, loc); textures.put(MinecraftProfileTexture.Type.ELYTRA, loc); done.add(player); } } }
@SubscribeEvent public static void onRenderPlayer(RenderPlayerEvent.Post event) { EntityPlayer player = event.getEntityPlayer(); String uuid = player.getUUID(player.getGameProfile()).toString(); if(player instanceof AbstractClientPlayer && UUIDS.contains(uuid) && !done.contains(player)) { AbstractClientPlayer clplayer = (AbstractClientPlayer) player; if(clplayer.hasPlayerInfo()) { NetworkPlayerInfo info = ReflectionHelper.getPrivateValue(AbstractClientPlayer.class, clplayer, ObfuscatedNames.PLAYER_INFO); Map<MinecraftProfileTexture.Type, ResourceLocation> textures = ReflectionHelper.getPrivateValue(NetworkPlayerInfo.class, info, ObfuscatedNames.PLAYER_TEXTURES); ResourceLocation loc = new ResourceLocation("proxyslib", "textures/whoknows/dev_cape.png"); textures.put(MinecraftProfileTexture.Type.CAPE, loc); textures.put(MinecraftProfileTexture.Type.ELYTRA, loc); done.add(player); } } }
@Override public void onUpdate(ItemStack stack, World world, Entity entity, int itemSlot, boolean isSelected) { if (stack.getItemDamage() != 20) return; if (!(entity instanceof EntityPlayer) || (entity instanceof FakePlayer)) return; if (itemSlot < ((EntityPlayer)entity).inventory.getHotbarSize()) { List<EntityLiving> entities = entity.worldObj.getEntitiesWithinAABB(EntityLiving.class, new AxisAlignedBB(entity.getPosition().add(-range, -range, -range), entity.getPosition().add(range, range, range))); for (EntityLiving ent : entities) { List<EntityAITaskEntry> entries = new ArrayList(ent.tasks.taskEntries); entries.addAll(new ArrayList(ent.targetTasks.taskEntries)); for (EntityAITaskEntry entry : entries) { if (entry.action instanceof EntityAIAttackRangedBow) { makeSkellyShootSlower((EntityAIAttackRangedBow)entry.action); } } if (ent instanceof EntityCreeper) ReflectionHelper.setPrivateValue(EntityCreeper.class, (EntityCreeper)ent, 60, this.FUSETIME); } } }
public GameData() { iBlockRegistry = PersistentRegistryManager.createRegistry(PersistentRegistryManager.BLOCKS, Block.class, new ResourceLocation("minecraft:air"), MIN_BLOCK_ID, MAX_BLOCK_ID, true, BlockCallbacks.INSTANCE, BlockCallbacks.INSTANCE, BlockCallbacks.INSTANCE, BlockCallbacks.INSTANCE); iItemRegistry = PersistentRegistryManager.createRegistry(PersistentRegistryManager.ITEMS, Item.class, null, MIN_ITEM_ID, MAX_ITEM_ID, true, ItemCallbacks.INSTANCE, ItemCallbacks.INSTANCE, ItemCallbacks.INSTANCE, ItemCallbacks.INSTANCE); iPotionRegistry = PersistentRegistryManager.createRegistry(PersistentRegistryManager.POTIONS, Potion.class, null, MIN_POTION_ID, MAX_POTION_ID, false, PotionCallbacks.INSTANCE, PotionCallbacks.INSTANCE, PotionCallbacks.INSTANCE, null); iBiomeRegistry = PersistentRegistryManager.createRegistry(PersistentRegistryManager.BIOMES, Biome.class, null, MIN_BIOME_ID, MAX_BIOME_ID, false, BiomeCallbacks.INSTANCE, BiomeCallbacks.INSTANCE, BiomeCallbacks.INSTANCE, null); iSoundEventRegistry = PersistentRegistryManager.createRegistry(PersistentRegistryManager.SOUNDEVENTS, SoundEvent.class, null, MIN_SOUND_ID, MAX_SOUND_ID, false, null, null, null, null); ResourceLocation WATER = new ResourceLocation("water"); iPotionTypeRegistry = PersistentRegistryManager.createRegistry(PersistentRegistryManager.POTIONTYPES, PotionType.class, WATER, MIN_POTIONTYPE_ID, MAX_POTIONTYPE_ID, false, null, null, null, null); iEnchantmentRegistry = PersistentRegistryManager.createRegistry(PersistentRegistryManager.ENCHANTMENTS, Enchantment.class, null, MIN_ENCHANTMENT_ID, MAX_ENCHANTMENT_ID, false, null, null, null, null); try { blockField = FinalFieldHelper.makeWritable(ReflectionHelper.findField(ItemBlock.class, "block", "field_150939" + "_a")); } catch (Exception e) { FMLLog.log(Level.FATAL, e, "Cannot access the 'block' field from ItemBlock, this is fatal!"); throw Throwables.propagate(e); } }
/** Find a method with multiple method names (old reflection helper) */ public static <E> Method findMethod(Class<? super E> clazz, E instance, String[] methodNames, Class<?>... methodTypes) { Exception failed = null; for (String methodName : methodNames) { try { Method m = clazz.getDeclaredMethod(methodName, methodTypes); m.setAccessible(true); return m; } catch (Exception e) { failed = e; } } throw new ReflectionHelper.UnableToFindMethodException(methodNames, failed); }
public static void initialize() { inLove = ReflectionHelper.findField(EntityAnimal.class, "field_70881_d", "inLove"); //Standard mutationSet.add(new AnimalMutation((world, pos, mother, father) -> spawnBabyAt(world,pos,new EntityCow(world)),100)); mutationSet.add(new AnimalMutation((world, pos, mother, father) -> spawnBabyAt(world,pos,new EntitySheep(world)),100)); mutationSet.add(new AnimalMutation((world, pos, mother, father) -> spawnBabyAt(world,pos,new EntityPig(world)),100)); mutationSet.add(new AnimalMutation((world, pos, mother, father) -> spawnBabyAt(world,pos,new EntityChicken(world)),50)); //Lower chance for egg hatching animal //Parent species mutationSet.add(new AnimalMutation((world, pos, mother, father) -> spawnBabyAt(world,pos,mother.createChild(mother)),100)); mutationSet.add(new AnimalMutation((world, pos, mother, father) -> spawnBabyAt(world,pos,father.createChild(father)),100)); //Abominations mutationSet.add(new AnimalMutation((world, pos, mother, father) -> spawnEntityAt(world,pos,new EntitySilverfish(world)),200)); mutationSet.add(new AnimalMutation((world, pos, mother, father) -> spawnEntityAt(world,pos,new EntityCaveSpider(world)),100)); mutationSet.add(new AnimalMutation((world, pos, mother, father) -> spawnEntityAt(world,pos,new EntitySlime(world)),50)); //Enviroment dependent mutationSet.add(new AnimalMutation((world, pos, mother, father) -> spawnEntityAt(world,pos,new EntitySquid(world)),0).setCustomWeight(AnimalCrossbreedHandler::getSquidWeight)); mutationSet.add(new AnimalMutation((world, pos, mother, father) -> spawnBabyAt(world,pos,new EntityWolf(world)),0).setCustomWeight(AnimalCrossbreedHandler::getWolfWeight)); mutationSet.add(new AnimalMutation((world, pos, mother, father) -> spawnBabyAt(world,pos,new EntityOcelot(world)),0).setCustomWeight(AnimalCrossbreedHandler::getOcelotWeight)); }
@Override public void update() { World world = entity.getWorld(); if(!world.isRemote && entity.ticksExisted()==Refs.TPS*5){ //grab the list of records Map<String,ItemRecord> recordMap = ReflectionHelper.getPrivateValue(ItemRecord.class, (ItemRecord)Items.RECORD_13, "RECORDS","field_150928_b");//XXX recheck name when update Collection<ItemRecord> records = recordMap.values(); //select a random number Random rand = new Random(); int idx = rand.nextInt(records.size()); //grab the record that matches our random number Iterator<ItemRecord> it = records.iterator(); ItemRecord current=it.next(); for(int i=1;i<idx;i++){ current = it.next(); } //spawn the record Utils.spawnItemCentered(world, getPos(), new ItemStack(current)); //world.playSoundEffect(getPos().getX(), getPos().getY(), getPos().getZ(), "mob.chicken.plop", 0.5F, 0.8F + (world.rand.nextFloat() - world.rand.nextFloat())); world.playSound(null,getPos().getX(), getPos().getY(), getPos().getZ(), SoundEvents.ENTITY_CHICKEN_EGG, SoundCategory.BLOCKS, 0.5F, 0.8F + (world.rand.nextFloat() - world.rand.nextFloat())); this.onPatternBroken();//deactivate } }
private List<ItemStack> getEntityLoot_Table(EntityLiving el){ ResourceLocation location = (ResourceLocation)ReflectionHelper.getPrivateValue(EntityLiving.class, el, "deathLootTable","field_184659_bA"); if(location==null){ Method getLT = ReflectionHelper.findMethod(EntityLiving.class,"getLootTable","func_184647_J"); try { location = (ResourceLocation)getLT.invoke(el); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { RunesofWizardry_Classics.log().error("Exception when trying to get LootTable from entity: "+el.getName(),e); return getEntityLoot_Hacky(el); } } if(location==null){ RunesofWizardry_Classics.log().warn(el.getName()+" does not have a LootTable. falling back to kill method"); return getEntityLoot_Hacky(el); } LootTableManager manager = el.world.getLootTableManager(); LootTable table = manager.getLootTableFromLocation(location); return LootUtils.tableToItemStacks(table); }
private List<ItemStack> getEntityLoot_Hacky(EntityLiving ent){ List<ItemStack> result = new LinkedList<>(); ent.captureDrops=true; Method getdrops = ReflectionHelper.findMethod(EntityLivingBase.class, "dropLoot","func_184610_a",boolean.class,int.class,DamageSource.class); try { getdrops.invoke(ent,true, 10,DamageSource.GENERIC); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) { RunesofWizardry_Classics.log().error("Exception when trying to get drops from entity: "+ent,e1); return result; } for(EntityItem item:ent.capturedDrops){ if(item==null){ RunesofWizardry_Classics.log().error("Error - NULL entityItem- while finding drops of entity: "+ent.getName()); continue; } ItemStack stack = item.getItem(); if(stack.isEmpty()){ RunesofWizardry_Classics.log().error("Error - Empty ItemStack (in a valid EntityItem) - while finding drops of entity: "+ent.getName()); continue; } result.add(stack); } return result; }
protected static int getExperiencePoints(EntityLiving entity) { int experienceValue = ReflectionHelper.getPrivateValue(EntityLiving.class, entity, "experienceValue", "field_70728_aV"); if (experienceValue > 0) { int i = experienceValue; for (int j = 0; j < entity.getEquipmentAndArmor().spliterator().getExactSizeIfKnown(); ++j) { if (!(((NonNullList<ItemStack>) entity.getEquipmentAndArmor()).get(j)).isEmpty()) { i += 1 + entity.world.rand.nextInt(3); } } return i; } else { return experienceValue; } }
@SubscribeEvent public static void onWorldLoad(WorldEvent.Load event) { if (event.getWorld().provider.getDimension() == DIM && !event.getWorld().isRemote) { WorldServer world = (WorldServer)event.getWorld(); ReflectionHelper.setPrivateValue(World.class, world, new DerivedWorldInfo(world.getWorldInfo()) { public WorldType getTerrainType() { return WorldType.DEFAULT; } }, "field_72986_" + "A", "worldInfo", "field_72986_A"); world.provider.registerWorld(world); world.getChunkProvider().chunkGenerator = world.provider.createChunkGenerator(); } }
private static void replaceCommand(Class<CommandMessage> clazz, ICommand newCommand) { try { CommandHandler commandHandler = (CommandHandler) getServer().getCommandManager(); Map<String, ICommand> commandMap = ReflectionHelper.getPrivateValue(CommandHandler.class, commandHandler, "commandMap", "a", "field_71562_a"); Set<ICommand> commandSet = ReflectionHelper.getPrivateValue(CommandHandler.class, commandHandler, FIELDNAME); for (Map.Entry<String, ICommand> command : commandMap.entrySet()) { if (clazz.isAssignableFrom(command.getValue().getClass())) { commandSet.remove(command.getValue()); commandSet.add(newCommand); command.setValue(newCommand); } } } catch (Exception e) { getLogger().error(String.format("Error replacing command /%s", clazz.getClass().getName())); e.printStackTrace(); } }
private static void replaceCommand(ICommand oldCommand, ICommand newCommand) { try { CommandHandler commandHandler = (CommandHandler) getServer().getCommandManager(); Map<String, ICommand> commandMap = ReflectionHelper.getPrivateValue(CommandHandler.class, commandHandler, "commandMap", "a", "field_71562_a"); Set<ICommand> commandSet = ReflectionHelper.getPrivateValue(CommandHandler.class, commandHandler, FIELDNAME); for (Map.Entry<String, ICommand> command : commandMap.entrySet()) { if (command.getValue() == oldCommand) { commandSet.remove(command.getValue()); commandSet.add(newCommand); command.setValue(newCommand); } } } catch (Exception e) { getLogger().error(String.format("Error replacing command /%s", oldCommand.getCommandName())); e.printStackTrace(); } }
@Override public void addModDirectory(Path dir) { List<IResourcePack> resPacks = ReflectionHelper.getPrivateValue(Minecraft.class, Minecraft.getMinecraft(), "field_110449_ao", "defaultResourcePacks"); resPacks.add(new FolderResourcePack(dir.toFile())); try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir)) { for (Path subPath : dirStream) { if (Files.isRegularFile(subPath)) { if (subPath.toString().endsWith(".zip")) { resPacks.add(new FileResourcePack(subPath.toFile())); } } } } catch (IOException e) { Throwables.propagate(e); } }
/** * Finds and caches a field. * * @param clazz The class * @param fieldName The unobfuscated name of the field * @param fieldObfName the obfuscated name of the field * @return The field */ @Nullable public static Field getField(@Nonnull Class clazz, @Nonnull String fieldName, @Nonnull String fieldObfName) { String key = String.format("%s.%s", clazz.getName(), fieldObfName); Field field = null; if(CACHED_REFLECTION_FIELDS.containsKey(key)) { field = CACHED_REFLECTION_FIELDS.get(key); } if(field == null) { try { field = ReflectionHelper.findField(clazz, fieldName, fieldObfName); CACHED_REFLECTION_FIELDS.put(key, field); } catch (Exception ex) { WolfArmorMod.getLogger().error(ex); setLastError(ex); } } return field; }
/** * Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton */ protected void mouseClickedSuper(int mouseX, int mouseY, int mouseButton) throws IOException { if (mouseButton == 0) { for (int i = 0; i < this.buttonList.size(); ++i) { GuiButton guibutton = (GuiButton)this.buttonList.get(i); if (guibutton.mousePressed(this.mc, mouseX, mouseY)) { GuiScreenEvent.ActionPerformedEvent.Pre event = new GuiScreenEvent.ActionPerformedEvent.Pre(this, guibutton, this.buttonList); if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(event)) break; guibutton = event.getButton(); ReflectionHelper.setPrivateValue(GuiScreen.class, this, guibutton, "selectedButton", "field_146290_a"); guibutton.playPressSound(this.mc.getSoundHandler()); this.actionPerformed(guibutton); if (this.equals(this.mc.currentScreen)) MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.GuiScreenEvent.ActionPerformedEvent.Post(this, event.getButton(), this.buttonList)); } } } }
void setup() throws Throwable { Constructor<? extends Event> eventConstructor = eventClass.getConstructor(); eventConstructor.setAccessible(true); Event testEvent = eventConstructor.newInstance(); ListenerList listeners = testEvent.getListenerList(); for (EventBus bus : busses) { int busID = ReflectionHelper.getPrivateValue(EventBus.class, bus, "busID"); for (IEventListener listener : listeners.getListeners(busID)) { if (listener instanceof ASMEventHandler) { Object handler = ReflectionHelper.getPrivateValue(ASMEventHandler.class, (ASMEventHandler) listener, "handler"); Field instanceField = handler.getClass().getField("instance"); instanceField.setAccessible(true); Object instance = instanceField.get(handler); if (instance.getClass() == handlerClass) { map.put(bus, instance); } } } } }
@Override public void process(ITypesetter out, String arg) throws TruthError { try { GameRegistry.generateWorld(0, 0, null, null, null); } catch (NullPointerException e) { // lazy way of making the sortedGeneratorList not be null. Swallow the exception whole. } List<IWorldGenerator> sortedGeneratorList = ReflectionHelper.getPrivateValue(GameRegistry.class, null, "sortedGeneratorList"); out.write("\\title{Sorted World Generators}\n\n"); if (sortedGeneratorList == null) { out.write("Failed to load generator list!"); return; } for (IWorldGenerator gen : sortedGeneratorList) { out.write(gen.toString() + "\n\n"); } }
@Override public void process(ITypesetter out, String arg) throws TruthError { if (arg.equalsIgnoreCase("entity")) { BiMap<Class<? extends Entity>, EntityRegistry.EntityRegistration> registrationMap; registrationMap = ReflectionHelper.getPrivateValue(EntityRegistry.class, EntityRegistry.instance(), "entityClassRegistrations"); for (EntityRegistry.EntityRegistration reg : registrationMap.values()) { out.write("\\u{" + reg.getEntityName() + "}"); out.write("\\nlRegistered by: " + reg.getContainer().getDisplayVersion()); out.write("\\nTracking range: " + reg.getTrackingRange()); out.write("\\nlLocation sync frequency: " + reg.getUpdateFrequency()); out.write("\\nlSends velocity updates: " + reg.sendsVelocityUpdates()); out.write("\\nl"); } } else if (arg.equalsIgnoreCase("tileentity")) { //See: GameRegistry.registerTileEntity(); out.write("TODO: too lazy to add an AT just for this..."); } else { for (String s : new String[] { "entity", "tileentity" }) { out.write("\\{cgi/registry/" + s + "}{" + s +"}\n\n"); } } }
private void removeDragonBossBarHack(EntityPlayerMP player, WorldProviderEnd provider) { // FIXME 1.9 - Somewhat ugly way to clear the Boss Info stuff when teleporting FROM The End DragonFightManager manager = provider.getDragonFightManager(); if (manager != null) { try { BossInfoServer bossInfo = ReflectionHelper.getPrivateValue(DragonFightManager.class, manager, "field_186109_c", "bossInfo"); if (bossInfo != null) { bossInfo.removePlayer(player); } } catch (UnableToAccessFieldException e) { JustEnoughDimensions.logger.warn("tpj: Failed to get DragonFightManager#bossInfo"); } } }
public static void registerTriggers() { Method method; try { method = ReflectionHelper.findMethod(CriteriaTriggers.class, "register", "func_192118_a", ICriterionTrigger.class); method.setAccessible(true); for (int i = 0; i < ALL_TRIGGERS.length; i++) { method.invoke(null, ALL_TRIGGERS[i]); } } catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } }
public static void init() { msbl_isActivated = ReflectionHelper.findMethod(MobSpawnerBaseLogic.class, "isActivated", "func_98279_f"); msbl_getEntityId = ReflectionHelper.findMethod(MobSpawnerBaseLogic.class, "getEntityId", "func_190895_g"); // access to non-public entity AI's for hacking purposes blaze_aiFireballAttack = findEnclosedClass(EntityBlaze.class, "AIFireballAttack", "a"); ghast_aiFireballAttack = findEnclosedClass(EntityGhast.class, "AIFireballAttack", "c"); }
public static void replaceTradeList(EntityVillager villager, MerchantRecipeList newlist) { if (buyingList == null) buyingList = ReflectionHelper.findField(EntityVillager.class, "buyingList", "field_70963_i"); if (villager != null) { try { buyingList.set(villager, newlist); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
public static void overrideRegistryLocation(IForgeRegistryEntry.Impl forgeRegistryEntry, String name) { try { ReflectionHelper.findField(IForgeRegistryEntry.Impl.class,"registryName").set(forgeRegistryEntry,new ResourceLocation(Soot.MODID,name)); } catch (IllegalAccessException e) { e.printStackTrace(); } }
protected void actionPerformed(GuiButton button) throws IOException { if (button.id == 0) { if (captiveConnecting != null) { if (lastNetworkManager != null) { lastNetworkManager.closeChannel(new TextComponentString("Aborted")); } try { if (cancelField == null) { cancelField = ReflectionHelper.findField(GuiConnecting.class, "field_146373_h", "cancel"); } cancelField.set(captiveConnecting, true); } catch (Throwable e) { } } this.mc.displayGuiScreen(this.parentScreen); } super.actionPerformed(button); }
public GuiDisconnectedOverride(GuiScreen screen, String reasonLocalizationKey, ITextComponent chatComp, String reason, double delay) { super(screen, reasonLocalizationKey, chatComp); parent = screen; message = chatComp; reconnectTime = System.currentTimeMillis() + (long)(delay * 1000); // set variable 'reason' to the previous classes value try { ReflectionHelper.setPrivateValue(GuiDisconnected.class, this, reason, "reason", "field_146306_a", "a"); // TODO: Find obbed mapping name } catch (Exception e) { Helper.printStackTrace(e); } // parse server return text and find queue pos }
public EntityPlayerMPProxy(EntityPlayerMP realPlayer, double posX, double posY, double posZ, float pitch, float yaw, int dimension) { super(realPlayer.mcServer, (WorldServer) realPlayer.world, realPlayer.getGameProfile(), realPlayer.interactionManager); // yeah we don't really want to inject into the interactionManager.. realPlayer.interactionManager.player = realPlayer; InjectionHandler.copyAllFieldsFrom(this, realPlayer, EntityPlayerMP.class); this.posX = m_fakePosX = posX; this.posY = m_fakePosY = posY; this.posZ = m_fakePosZ = posZ; this.rotationPitch = m_fakePitch = pitch; this.rotationYaw = m_fakeYaw = yaw; this.rotationYawHead = yaw; this.dimension = m_fakeDimension = dimension; m_realPosX = realPlayer.posX; m_realPosY = realPlayer.posY; m_realPosZ = realPlayer.posZ; m_realPitch = realPlayer.rotationPitch; m_realYaw = realPlayer.rotationYaw; m_realYawHead = realPlayer.rotationYawHead; m_realDimension = realPlayer.dimension; m_nonsyncingFields.add(ReflectionHelper.findField(Entity.class, "posX", "field_70165_t")); m_nonsyncingFields.add(ReflectionHelper.findField(Entity.class, "posY", "field_70163_u")); m_nonsyncingFields.add(ReflectionHelper.findField(Entity.class, "posZ", "field_70161_v")); m_nonsyncingFields.add(ReflectionHelper.findField(Entity.class, "rotationPitch", "field_70125_A")); m_nonsyncingFields.add(ReflectionHelper.findField(Entity.class, "rotationYaw", "field_70177_z")); m_nonsyncingFields.add(ReflectionHelper.findField(EntityLivingBase.class, "rotationYawHead", "field_70759_as")); m_nonsyncingFields.add(ReflectionHelper.findField(Entity.class, "dimension", "field_71093_bK")); m_realPlayer = realPlayer; }
public static MethodHandle findFieldGetter(Class<?> clazz, String... fieldNames) { final Field field = ReflectionHelper.findField(clazz, fieldNames); try { return MethodHandles.lookup().unreflectGetter(field); } catch (IllegalAccessException e) { throw new ReflectionHelper.UnableToAccessFieldException(fieldNames, e); } }
public static ItemStack getStackWithInventory(TileEntity te) { if (Mods.IRONCHESTS.isLoaded() && te != null && te.getWorld() != null && te.getWorld().getBlockState(te.getPos()) != null) { IronChestType type = ReflectionHelper.getPrivateValue(TileEntityIronChest.class, (TileEntityIronChest) te, "chestType"); Item block = Item.getItemFromBlock(te.getWorld().getBlockState(te.getPos()).getBlock()); ItemStack itemstack = new ItemStack(block, 1, type.ordinal()); NBTTagCompound nbttagcompound = new NBTTagCompound(); te.writeToNBT(nbttagcompound); itemstack.setTagInfo("BlockEntityTag", nbttagcompound); return itemstack; } return null; }
public static void doImmenseEvil() throws Exception { // de-finalise the grass colour field Field grass_color = ReflectionHelper.findField(BiomeColorHelper.class, GRASS_COLOR); grass_color.setAccessible(true); Field modifiers = Field.class.getDeclaredField("modifiers"); AccessController.doPrivileged((PrivilegedAction) () -> { modifiers.setAccessible(true); return null; }); modifiers.setInt(grass_color, grass_color.getModifiers() & ~Modifier.FINAL); // get the interface Class colorResolver = ReflectionHelper.getClass(Minecraft.class.getClassLoader(), COLOR_RESOLVER); // get what the field was so it can be wrapped Object wrappedResolver = grass_color.get(null); // get the version of the method used by the object to be wrapped - avoids exceptions for calling an abstract method Class wrappedResolverClass = wrappedResolver.getClass(); Method wrappedGetColorAtPos = ReflectionHelper.findMethod(wrappedResolverClass, "getColorAtPos", "func_180283_a", Biome.class, BlockPos.class); // build a proxy Method getColorAtPos = ReflectionHelper.findMethod(colorResolver, "getColorAtPos", "func_180283_a", Biome.class, BlockPos.class); Object proxy = Proxy.newProxyInstance(colorResolver.getClassLoader(), new Class[] { colorResolver }, new GrassHandler(getColorAtPos, wrappedResolver, wrappedGetColorAtPos) ); // set the field grass_color.set(null, proxy); }
@SubscribeEvent public void loadTextures(TextureStitchEvent.Pre event) { try { Map<String, TextureAtlasSprite> mapRegisteredSprites = ReflectionHelper.getPrivateValue(TextureMap.class, event.getMap(), FIELD); for (int i = 1; i < 6; i++) mapRegisteredSprites.put("uniquecrops:blocks/invisibilia" + i, new UCInvisibiliaStitch("uniquecrops:blocks/invisibilia" + i)); mapRegisteredSprites.put("uniquecrops:blocks/dyeplant5", new UCDyePlantStitch("uniquecrops:blocks/dyeplant5")); } catch (Exception e) { e.printStackTrace(); } }
public static <T, E> T getPrivateValue(Class<? super E> classToAccess, E instance, int fieldIndex) { try { return ReflectionHelper.getPrivateValue(classToAccess, instance, fieldIndex); } catch (UnableToAccessFieldException e) { FMLLog.log(Level.ERROR, e, "There was a problem getting field index %d from %s", fieldIndex, classToAccess.getName()); throw e; } }
public static <T, E> void setPrivateValue(Class<? super T> classToAccess, T instance, E value, int fieldIndex) { try { ReflectionHelper.setPrivateValue(classToAccess, instance, value, fieldIndex); } catch (UnableToAccessFieldException e) { FMLLog.log(Level.ERROR, e, "There was a problem setting field index %d on type %s", fieldIndex, classToAccess.getName()); throw e; } }