Remove old paulscode libraries.

Re-work EnumHelper and ObjectHolder systems to bypass JITer of final fields.
Other cleanups.
This commit is contained in:
LexManos committed 2018-09-06 04:39:01 -07:00
1 parent 2798080f60
commit 12869710de
55 files changed
+495 -5859

No files matched your search

@@ -1,78 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.client;
import net.minecraft.client.audio.MusicTicker;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.Util.EnumOS;
import net.minecraft.world.GameType;
import net.minecraft.client.settings.GameSettings.Options;
import net.minecraftforge.common.util.EnumHelper;
import javax.annotation.Nullable;
public class EnumHelperClient extends EnumHelper
{
private static Class<?>[][] clientTypes =
{
{GameType.class, int.class, String.class, String.class},
{Options.class, String.class, boolean.class, boolean.class},
{EnumOS.class},
{MusicTicker.MusicType.class, SoundEvent.class, int.class, int.class}
};
@Nullable
public static GameType addGameType(String name, int id, String displayName, String shortName)
{
return addEnum(GameType.class, name, id, displayName, shortName);
}
@Nullable
public static Options addOptions(String name, String langName, boolean isSlider, boolean isToggle)
{
return addEnum(Options.class, name, langName, isSlider, isToggle);
}
@Nullable
public static Options addOptions(String name, String langName, boolean isSlider, boolean isToggle, float valMin, float valMax, float valStep)
{
return addEnum(Options.class, name,
new Class<?>[]{String.class, boolean.class, boolean.class, float.class, float.class, float.class},
langName, isSlider, isToggle, valMin, valMax, valStep);
}
@Nullable
public static EnumOS addOS2(String name)
{
return addEnum(EnumOS.class, name);
}
@Nullable
public static MusicTicker.MusicType addMusicType(String name, SoundEvent sound, int minDelay, int maxDelay)
{
return addEnum(MusicTicker.MusicType.class, name, sound, minDelay, maxDelay);
}
@Nullable
private static <T extends Enum<? >> T addEnum(Class<T> enumType, String enumName, Object... paramValues)
{
return addEnum(clientTypes, enumType, enumName, paramValues);
}
}
@@ -31,6 +31,7 @@ import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
import javax.annotation.Nonnull;
import javax.vecmath.Matrix3f;
@@ -40,6 +41,7 @@ import javax.vecmath.Vector4f;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.GameSettings;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.ISound;
import net.minecraft.client.audio.SoundHandler;
@@ -48,15 +50,12 @@ import net.minecraft.client.gui.BossInfoClient;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.renderer.BlockRendererDispatcher;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.BlockFaceUV;
import net.minecraft.client.renderer.block.model.IBakedModel;
@@ -72,16 +71,13 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.renderer.vertex.VertexFormatElement;
import net.minecraft.client.renderer.vertex.VertexFormatElement.EnumUsage;
import net.minecraft.client.resources.FoliageColorReloadListener;
import net.minecraft.client.resources.GrassColorReloadListener;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.resources.IResourceManagerReloadListener;
import net.minecraft.client.resources.LanguageManager;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.client.util.SearchTreeManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
@@ -101,7 +97,6 @@ import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.registry.IRegistry;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.client.event.ColorHandlerEvent;
@@ -111,7 +106,6 @@ import net.minecraftforge.client.event.FOVUpdateEvent;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.client.event.InputUpdateEvent;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.client.event.MouseEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderHandEvent;
import net.minecraftforge.client.event.RenderSpecificHandEvent;
@@ -132,25 +126,17 @@ import net.minecraftforge.common.model.IModelPart;
import net.minecraftforge.common.model.ITransformation;
import net.minecraftforge.common.model.TRSRTransformation;
import net.minecraftforge.fml.VersionChecker;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.FMLLog;
import org.apache.commons.lang3.tuple.Pair;
import org.lwjgl.BufferUtils;
import java.util.Optional;
import com.google.common.collect.Maps;
public class ForgeHooksClient
{
//private static final ResourceLocation ITEM_GLINT = new ResourceLocation("textures/misc/enchanted_item_glint.png");
static TextureManager engine()
{
return FMLClientHandler.instance().getClient().renderEngine;
}
public static String getArmorTexture(Entity entity, ItemStack armor, String _default, EntityEquipmentSlot slot, String type)
{
String result = armor.getItem().getArmorTexture(armor, entity, slot, type);
@@ -406,18 +392,18 @@ public class ForgeHooksClient
m.setIdentity();
m.setTranslation(TRSRTransformation.toVecmath(transform.translation));
t.setIdentity();
t.rotY(transform.rotation.y);
t.rotY(transform.rotation.func_195900_b());
m.mul(t);
t.setIdentity();
t.rotX(transform.rotation.x);
t.rotX(transform.rotation.func_195899_a());
m.mul(t);
t.setIdentity();
t.rotZ(transform.rotation.z);
t.rotZ(transform.rotation.func_195902_c());
m.mul(t);
t.setIdentity();
t.m00 = transform.scale.x;
t.m11 = transform.scale.y;
t.m22 = transform.scale.z;
t.m00 = transform.scale.func_195899_a();
t.m11 = transform.scale.func_195900_b();
t.m22 = transform.scale.func_195902_c();
m.mul(t);
return m;
}
@@ -30,7 +30,7 @@ import net.minecraft.util.ResourceLocation;
import net.minecraft.world.biome.*;
import static net.minecraftforge.common.BiomeDictionary.Type.*;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistries;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
@@ -32,6 +32,11 @@ import java.util.UUID;
import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
@@ -50,9 +55,6 @@ import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fml.server.ServerLifecycleHooks;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.ModContainer;
import com.google.common.cache.Cache;
@@ -87,11 +89,11 @@ import com.google.common.collect.Sets;
* The chunkloading is configurable at runtime. The file "config/forgeChunkLoading.cfg" contains both default configuration for chunkloading, and a sample individual mod
* specific override section.
*
* @author cpw
*
*/
public class ForgeChunkManager
{
public static Marker CHUNK_MANAGER = MarkerManager.getMarker("CHUNKMANAGER");
private static Logger LOGGER = LogManager.getLogger();
private static int defaultMaxCount;
private static int defaultMaxChunks;
private static boolean overridesEnabled;
@@ -143,7 +145,7 @@ public class ForgeChunkManager
final ImmutableSetMultimap<ChunkPos, Ticket> persistentChunksFor = getPersistentChunksFor(world);
final ImmutableSet.Builder<Chunk> builder = ImmutableSet.builder();
world.profiler.startSection("forcedChunkLoading");
builder.addAll(persistentChunksFor.keys().stream().filter(Objects::nonNull).map(input -> world.getChunkFromChunkCoords(input.x, input.z)).iterator());
builder.addAll(persistentChunksFor.keys().stream().filter(Objects::nonNull).map(input -> world.getChunk(input.x, input.z)).iterator());
world.profiler.endStartSection("regularChunkLoading");
builder.addAll(chunkIterator);
world.profiler.endSection();
@@ -265,7 +267,7 @@ public class ForgeChunkManager
}
else
{
FMLLog.log.error("Attempt to create a player ticket without a valid player");
LOGGER.error(CHUNK_MANAGER, "Attempt to create a player ticket without a valid player");
throw new RuntimeException();
}
}
@@ -279,7 +281,7 @@ public class ForgeChunkManager
{
if (depth > getMaxChunkDepthFor(modId) || (depth <= 0 && getMaxChunkDepthFor(modId) > 0))
{
FMLLog.log.warn("The mod {} tried to modify the chunk ticket depth to: {}, its allowed maximum is: {}", modId, depth, getMaxChunkDepthFor(modId));
LOGGER.warn(CHUNK_MANAGER, "The mod {} tried to modify the chunk ticket depth to: {}, its allowed maximum is: {}", modId, depth, getMaxChunkDepthFor(modId));
}
else
{
@@ -453,7 +455,7 @@ public class ForgeChunkManager
try
{
NBTTagCompound forcedChunkData = CompressedStreamTools.read(chunkLoaderData);
return forcedChunkData.getTagList("TicketList", Constants.NBT.TAG_COMPOUND).tagCount() > 0;
return forcedChunkData.getTagList("TicketList", Constants.NBT.TAG_COMPOUND).size() > 0;
}
catch (IOException e)
{
@@ -493,11 +495,11 @@ public class ForgeChunkManager
}
catch (IOException e)
{
FMLLog.log.warn("Unable to read forced chunk data at {} - it will be ignored", chunkLoaderData.getAbsolutePath(), e);
LOGGER.warn(CHUNK_MANAGER, "Unable to read forced chunk data at {} - it will be ignored", chunkLoaderData.getAbsolutePath(), e);
return;
}
NBTTagList ticketList = forcedChunkData.getTagList("TicketList", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < ticketList.tagCount(); i++)
for (int i = 0; i < ticketList.size(); i++)
{
NBTTagCompound ticketHolder = ticketList.getCompoundTagAt(i);
String modId = ticketHolder.getString("Owner");
@@ -505,18 +507,18 @@ public class ForgeChunkManager
if (!isPlayer && !Loader.isModLoaded(modId))
{
FMLLog.log.warn("Found chunkloading data for mod {} which is currently not available or active - it will be removed from the world save", modId);
LOGGER.warn(CHUNK_MANAGER, "Found chunkloading data for mod {} which is currently not available or active - it will be removed from the world save", modId);
continue;
}
if (!isPlayer && !callbacks.containsKey(modId))
{
FMLLog.log.warn("The mod {} has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId);
LOGGER.warn(CHUNK_MANAGER, "The mod {} has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId);
continue;
}
NBTTagList tickets = ticketHolder.getTagList("Tickets", Constants.NBT.TAG_COMPOUND);
for (int j = 0; j < tickets.tagCount(); j++)
for (int j = 0; j < tickets.size(); j++)
{
NBTTagCompound ticket = tickets.getCompoundTagAt(j);
modId = ticket.hasKey("ModId") ? ticket.getString("ModId") : modId;
@@ -558,14 +560,14 @@ public class ForgeChunkManager
// force the world to load the entity's chunk
// the load will come back through the loadEntity method and attach the entity
// to the ticket
world.getChunkFromChunkCoords(tick.entityChunkX, tick.entityChunkZ);
world.getChunk(tick.entityChunkX, tick.entityChunkZ);
}
}
for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values()))
{
if (tick.ticketType == Type.ENTITY && tick.entity == null)
{
FMLLog.log.warn("Failed to load persistent chunkloading entity {} from store.", pendingEntities.inverse().get(tick));
LOGGER.warn(CHUNK_MANAGER, "Failed to load persistent chunkloading entity {} from store.", pendingEntities.inverse().get(tick));
loadedTickets.remove(tick.modId, tick);
}
}
@@ -587,7 +589,7 @@ public class ForgeChunkManager
}
if (tickets.size() > maxTicketLength)
{
FMLLog.log.warn("The mod {} has too many open chunkloading tickets {}. Excess will be dropped", modId, tickets.size());
LOGGER.warn(CHUNK_MANAGER, "The mod {} has too many open chunkloading tickets {}. Excess will be dropped", modId, tickets.size());
tickets.subList(maxTicketLength, tickets.size()).clear();
}
ForgeChunkManager.tickets.get(world).putAll(modId, tickets);
@@ -645,7 +647,7 @@ public class ForgeChunkManager
ModContainer container = getContainer(mod);
if (container == null)
{
FMLLog.log.warn("Unable to register a callback for an unknown mod {} ({} : {})", mod, mod.getClass().getName(), Integer.toHexString(System.identityHashCode(mod)));
LOGGER.warn(CHUNK_MANAGER, "Unable to register a callback for an unknown mod {} ({} : {})", mod, mod.getClass().getName(), Integer.toHexString(System.identityHashCode(mod)));
return;
}
@@ -703,12 +705,12 @@ public class ForgeChunkManager
ModContainer mc = getContainer(mod);
if (mc == null)
{
FMLLog.log.error("Failed to locate the container for mod instance {} ({} : {})", mod, mod.getClass().getName(), Integer.toHexString(System.identityHashCode(mod)));
LOGGER.error(CHUNK_MANAGER, "Failed to locate the container for mod instance {} ({} : {})", mod, mod.getClass().getName(), Integer.toHexString(System.identityHashCode(mod)));
return null;
}
if (playerTickets.get(player).size()>playerTicketLength)
{
FMLLog.log.warn("Unable to assign further chunkloading tickets to player {} (on behalf of mod {})", player, mc.getModId());
LOGGER.warn(CHUNK_MANAGER, "Unable to assign further chunkloading tickets to player {} (on behalf of mod {})", player, mc.getModId());
return null;
}
Ticket ticket = new Ticket(mc.getModId(),type,world,player);
@@ -730,13 +732,13 @@ public class ForgeChunkManager
ModContainer container = getContainer(mod);
if (container == null)
{
FMLLog.log.error("Failed to locate the container for mod instance {} ({} : {})", mod, mod.getClass().getName(), Integer.toHexString(System.identityHashCode(mod)));
LOGGER.error(CHUNK_MANAGER, "Failed to locate the container for mod instance {} ({} : {})", mod, mod.getClass().getName(), Integer.toHexString(System.identityHashCode(mod)));
return null;
}
String modId = container.getModId();
if (!callbacks.containsKey(modId))
{
FMLLog.log.fatal("The mod {} has attempted to request a ticket without a listener in place", modId);
LOGGER.fatal(CHUNK_MANAGER, "The mod {} has attempted to request a ticket without a listener in place", modId);
throw new RuntimeException("Invalid ticket request");
}
@@ -746,7 +748,7 @@ public class ForgeChunkManager
{
if (!warnedMods.contains(modId))
{
FMLLog.log.info("The mod {} has attempted to allocate a chunkloading ticket beyond it's currently allocated maximum: {}", modId, allowedCount);
LOGGER.info(CHUNK_MANAGER, "The mod {} has attempted to allocate a chunkloading ticket beyond it's currently allocated maximum: {}", modId, allowedCount);
warnedMods.add(modId);
}
return null;
@@ -810,7 +812,7 @@ public class ForgeChunkManager
}
if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket))
{
FMLLog.log.fatal("The mod {} attempted to force load a chunk with an invalid ticket. This is not permitted.", ticket.modId);
LOGGER.fatal(CHUNK_MANAGER, "The mod {} attempted to force load a chunk with an invalid ticket. This is not permitted.", ticket.modId);
return;
}
ticket.requestedChunks.add(chunk);
@@ -913,7 +915,7 @@ public class ForgeChunkManager
for (String modId : ticketSet.keySet())
{
NBTTagCompound ticketHolder = new NBTTagCompound();
ticketList.appendTag(ticketHolder);
ticketList.add(ticketHolder);
ticketHolder.setString("Owner", modId);
NBTTagList tickets = new NBTTagList();
@@ -939,11 +941,11 @@ public class ForgeChunkManager
ticket.setInteger("chunkZ", MathHelper.floor(tick.entity.chunkCoordZ));
ticket.setLong("PersistentIDMSB", tick.entity.getPersistentID().getMostSignificantBits());
ticket.setLong("PersistentIDLSB", tick.entity.getPersistentID().getLeastSignificantBits());
tickets.appendTag(ticket);
tickets.add(ticket);
}
else if (tick.ticketType != Type.ENTITY)
{
tickets.appendTag(ticket);
tickets.add(ticket);
}
}
}
@@ -956,7 +958,7 @@ public class ForgeChunkManager
}
catch (IOException e)
{
FMLLog.log.warn("Unable to write forced chunk data to {} - chunkloading won't work", chunkLoaderData.getAbsolutePath(), e);
LOGGER.warn(CHUNK_MANAGER, "Unable to write forced chunk data to {} - chunkloading won't work", chunkLoaderData.getAbsolutePath(), e);
}
return false;
});
@@ -1025,14 +1027,14 @@ public class ForgeChunkManager
private static void loadChunkEntities(Chunk chunk, NBTTagCompound nbt, World world)
{
NBTTagList entities = nbt.getTagList("Entities", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < entities.tagCount(); ++i)
for (int i = 0; i < entities.size(); ++i)
{
AnvilChunkLoader.readChunkEntity(entities.getCompoundTagAt(i), world, chunk);
chunk.setHasEntities(true);
}
NBTTagList tileEntities = nbt.getTagList("TileEntities", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < tileEntities.tagCount(); ++i)
for (int i = 0; i < tileEntities.size(); ++i)
{
TileEntity tileEntity = TileEntity.create(world, tileEntities.getCompoundTagAt(i));
if (tileEntity != null) chunk.addTileEntity(tileEntity);
@@ -1055,7 +1057,7 @@ public class ForgeChunkManager
dest.delete();
}
cfgFile.renameTo(dest);
FMLLog.log.error("A critical error occurred reading the forgeChunkLoading.cfg file, defaults will be used - the invalid file is backed up at forgeChunkLoading.cfg.bak", e);
LOGGER.error(CHUNK_MANAGER, "A critical error occurred reading the forgeChunkLoading.cfg file, defaults will be used - the invalid file is backed up at forgeChunkLoading.cfg.bak", e);
}
syncConfigDefaults();
}
@@ -1108,7 +1110,7 @@ public class ForgeChunkManager
temp.setMinValue(0);
dormantChunkCacheSize = temp.getInt(0);
propOrder.add("dormantChunkCacheSize");
FMLLog.log.info("Configured a dormant chunk cache size of {}", temp.getInt(0));
LOGGER.info(CHUNK_MANAGER, "Configured a dormant chunk cache size of {}", temp.getInt(0));
temp = config.get("defaults", "asyncChunkLoading", true);
temp.setComment("Load chunks asynchronously for players, reducing load on the server thread.\n" +
@@ -149,13 +149,13 @@ import net.minecraftforge.fml.common.LoaderState;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher;
import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher.ConnectionType;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.network.ConnectionType;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import net.minecraftforge.fml.network.NetworkHooks;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.RegistryManager;
@@ -0,0 +1,105 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.asm;
import java.nio.file.Path;
import java.util.List;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
/**
* Removes the final modifier from fields with the @ObjectHolder annotation, prevents the JITer from in lining them so our runtime replacements can work.
* Will also de-finalize all fields in on class level annotations.
*/
public class ObjectHolderDefinalize implements ILaunchPluginService {
private final String OBJECT_HOLDER = "Lnet/minecraftforge/registries/ObjectHolder;"; //Don't directly reference this to prevent class loading.
@Override
public String name() {
return "object_holder_definalize";
}
@Override public void addResource(Path resource, String name) { }
@Override public <T> T getExtension() { return null; } // ?
@Override
public boolean handlesClass(Type classType, boolean isEmpty)
{
return !isEmpty; //Check for annotations?
}
private boolean hasHolder(List<AnnotationNode> lst)
{
return lst != null && lst.stream().anyMatch(n -> n.desc.equals(OBJECT_HOLDER));
}
private String getValue(List<AnnotationNode> lst)
{
AnnotationNode ann = lst.stream().filter(n -> n.desc.equals(OBJECT_HOLDER)).findFirst().get();
if (ann.values != null)
{
for (int x = 0; x < ann.values.size() - 1; x += 2) {
if (ann.values.get(x).equals("value")) {
return (String)ann.values.get(x + 1);
}
}
}
return null;
}
@Override
public ClassNode processClass(ClassNode classNode, Type classType)
{
//Must be public static finals, and non-array objects
final int flags = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
//Fix Annotated Fields before injecting from class level
classNode.fields.stream().filter(f -> ((f.access & flags) == flags) && f.desc.startsWith("L") && hasHolder(f.visibleAnnotations)).forEach(f ->
{
f.access &= ~Opcodes.ACC_FINAL; //Strip final
f.access |= Opcodes.ACC_SYNTHETIC; //Add Synthetic so we can check in runtime. ? Good idea?
});
if (hasHolder(classNode.visibleAnnotations)) //Class level, de-finalize all fields and add @ObjectHolder to them!
{
@SuppressWarnings("unused")
String value = getValue(classNode.visibleAnnotations);
classNode.fields.stream().filter(f -> ((f.access & flags) == flags) && f.desc.startsWith("L")).forEach(f ->
{
f.access &= ~Opcodes.ACC_FINAL;
f.access |= Opcodes.ACC_SYNTHETIC;
/*if (!hasHolder(f.visibleAnnotations)) //Add field level annotation, doesn't do anything until after we figure out how ASMDataTable is gatherered
{
if (value == null)
f.visitAnnotation(OBJECT_HOLDER, true);
else
f.visitAnnotation(OBJECT_HOLDER, true).visit("value", value + ":" + f.name.toLowerCase());
}*/
});
}
return classNode;
}
}
@@ -0,0 +1,134 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.asm;
import java.nio.file.Path;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.InstructionAdapter;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
/**
* Modifies specified enums to allow runtime extension by making the $VALUES field non-final and
* injecting constructor calls which are not valid in normal java code.
*/
public class RuntimeEnumExtender implements ILaunchPluginService {
private static final Logger LOGGER = LogManager.getLogger();
private final Type STRING = Type.getType(String.class);
private final Type ARRAY_UTILS = Type.getType("Lorg/apache/commons/lang3/ArrayUtils;"); //Don't directly reference this to prevent class loading.
private final String ADD_DESC = Type.getMethodDescriptor(Type.getType(Object[].class), Type.getType(Object[].class), Type.getType(Object.class));
private final Type ENUM_HELPER = Type.getType("Lnet/minecraftforge/common/util/EnumHelper;"); //Again, not direct reference to prevent class loading.
private final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class));
@Override
public String name() {
return "runtime_enum_extender";
}
@Override public void addResource(Path resource, String name) { }
@Override public <T> T getExtension() { return null; } // ?
@Override
public boolean handlesClass(Type classType, boolean isEmpty)
{
return !isEmpty; //Any way to determine if its a enum at this level?
}
@Override
public ClassNode processClass(ClassNode classNode, Type classType)
{
if ((classNode.access & Opcodes.ACC_ENUM) == 0)
return classNode;
Type array = Type.getType("[" + classType.getInternalName());
final int flags = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
FieldNode values = classNode.fields.stream().filter(f -> f.desc.contentEquals(array.getDescriptor()) && ((f.access & flags) == flags)).findFirst().orElse(null);
//Static methods named "create", with first argument as a string, and returning this type
classNode.methods.stream().filter(m -> ((m.access & Opcodes.ACC_STATIC) != 0) && m.name.equals("create") && Type.getReturnType(m.desc).equals(classType)).forEach(mtd ->
{
Type[] args = Type.getArgumentTypes(mtd.desc);
if (args.length == 0 || !args[0].equals(STRING))
return;
Type[] ctrArgs = new Type[args.length + 1];
ctrArgs[0] = STRING;
ctrArgs[1] = Type.INT_TYPE;
for (int x = 1; x < args.length; x++)
ctrArgs[1 + x] = args[x];
String desc = Type.getMethodDescriptor(Type.VOID_TYPE, ctrArgs);
MethodNode ctr = classNode.methods.stream().filter(m -> m.name.equals("<init>") && m.desc.equals(desc)).findFirst().orElse(null);
if (ctr == null)
{
LOGGER.error("Enum has create method with no matching constructor:");
LOGGER.error(" Target: " + desc);
classNode.methods.stream().filter(m -> m.name.equals("<init>")).forEach(m -> LOGGER.error(" :" + m.desc));
throw new IllegalStateException("Enum has create method with no matching constructor: " + desc);
}
if (values == null)
{
LOGGER.error("Enum has create method but we could not find $VALUES:");
classNode.fields.stream().filter(f -> (f.access & Opcodes.ACC_STATIC) != 0).forEach(m -> LOGGER.error(" " + m.name + " " + m.desc));
throw new IllegalStateException("Enum has create method but we could not find $VALUES");
}
values.access &= values.access & ~Opcodes.ACC_FINAL; //Strip the final so JITer doesn't inline things.
mtd.instructions.clear();
InstructionAdapter ins = new InstructionAdapter(mtd);
//ret = new ThisType(name, VALUES.length + 1, args..)
ins.anew(classType);
ins.dup();
ins.load(0, STRING);
ins.getstatic(classType.getInternalName(), values.name, values.desc);
ins.iconst(1);
ins.add(Type.INT_TYPE);
for (int x = 1; x < args.length; x++)
ins.load(x, args[x]);
ins.invokespecial(classType.getDescriptor(), "<init>", desc, false);
ins.store(1, classType);
// VALUES = ArrayUtils.add(VALUES, ret)
ins.getstatic(classType.getInternalName(), values.name, values.desc);
ins.load(1, classType);
ins.invokestatic(ARRAY_UTILS.getDescriptor(), "add", ADD_DESC, false);
ins.checkcast(array);
ins.putstatic(classType.getInternalName(), values.name, values.desc);
//EnumHelper.cleanEnumCache(ThisType.class)
ins.visitLdcInsn(classType);
ins.invokestatic(ENUM_HELPER.getInternalName(), "cleanEnumCache", CLEAN_DESC, false);
//return ret
ins.load(1, classType);
ins.areturn(classType);
});
return classNode;
}
}
@@ -65,11 +65,11 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.OreIngredient;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.GameData;
import net.minecraftforge.registries.RegistryManager;
@@ -29,7 +29,7 @@ import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistries;
import javax.annotation.Nullable;
@@ -27,207 +27,21 @@ import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import net.minecraftforge.fml.common.EnhancedRuntimeException;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraft.block.BlockPressurePlate.Sensitivity;
import net.minecraft.block.material.Material;
import net.minecraft.enchantment.EnumEnchantmentType;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EnumCreatureAttribute;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.entity.item.EntityPainting.EnumArt;
import net.minecraft.entity.passive.HorseArmorType;
import net.minecraft.entity.passive.IAnimals;
import net.minecraft.entity.player.EntityPlayer.SleepResult;
import net.minecraft.item.EnumAction;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.Item;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.item.ItemArmor.ArmorMaterial;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.gen.structure.StructureStrongholdPieces.Stronghold.Door;
import net.minecraftforge.classloading.FMLForgePlugin;
import org.apache.commons.lang3.ArrayUtils;
import javax.annotation.Nullable;
public class EnumHelper
{
private static Object reflectionFactory = null;
private static Method newConstructorAccessor = null;
private static Method newInstance = null;
private static Method newFieldAccessor = null;
private static Method fieldAccessorSet = null;
private static boolean isSetup = false;
//Some enums are decompiled with extra arguments, so lets check for that
private static Class<?>[][] commonTypes =
{
{EnumAction.class},
{ArmorMaterial.class, String.class, int.class, int[].class, int.class, SoundEvent.class, float.class},
{EnumArt.class, String.class, int.class, int.class, int.class, int.class},
{EnumCreatureAttribute.class},
{EnumCreatureType.class, Class.class, int.class, Material.class, boolean.class, boolean.class},
{Door.class},
{EnumEnchantmentType.class, Predicate.class},
{Sensitivity.class},
{RayTraceResult.Type.class},
{EnumSkyBlock.class, int.class},
{SleepResult.class},
{ToolMaterial.class, int.class, int.class, float.class, float.class, int.class},
{EnumRarity.class, TextFormatting.class, String.class},
{HorseArmorType.class, String.class, int.class},
{EntityLiving.SpawnPlacementType.class, BiPredicate.class}
};
@Nullable
public static EnumAction addAction(String name)
{
return addEnum(EnumAction.class, name);
}
@Nullable
public static ArmorMaterial addArmorMaterial(String name, String textureName, int durability, int[] reductionAmounts, int enchantability, SoundEvent soundOnEquip, float toughness)
{
return addEnum(ArmorMaterial.class, name, textureName, durability, reductionAmounts, enchantability, soundOnEquip, toughness);
}
@Nullable
public static EnumArt addArt(String name, String tile, int sizeX, int sizeY, int offsetX, int offsetY)
{
return addEnum(EnumArt.class, name, tile, sizeX, sizeY, offsetX, offsetY);
}
@Nullable
public static EnumCreatureAttribute addCreatureAttribute(String name)
{
return addEnum(EnumCreatureAttribute.class, name);
}
@Nullable
public static EnumCreatureType addCreatureType(String name, Class<? extends IAnimals> typeClass, int maxNumber, Material material, boolean peaceful, boolean animal)
{
return addEnum(EnumCreatureType.class, name, typeClass, maxNumber, material, peaceful, animal);
}
@Nullable
public static Door addDoor(String name)
{
return addEnum(Door.class, name);
}
@Nullable
public static EnumEnchantmentType addEnchantmentType(String name, Predicate<Item> delegate)
{
return addEnum(EnumEnchantmentType.class, name, delegate);
}
@Nullable
public static Sensitivity addSensitivity(String name)
{
return addEnum(Sensitivity.class, name);
}
@Nullable
public static RayTraceResult.Type addMovingObjectType(String name)
{
return addEnum(RayTraceResult.Type.class, name);
}
@Nullable
public static EnumSkyBlock addSkyBlock(String name, int lightValue)
{
return addEnum(EnumSkyBlock.class, name, lightValue);
}
@Nullable
public static SleepResult addStatus(String name)
{
return addEnum(SleepResult.class, name);
}
@Nullable
public static ToolMaterial addToolMaterial(String name, int harvestLevel, int maxUses, float efficiency, float damage, int enchantability)
{
return addEnum(ToolMaterial.class, name, harvestLevel, maxUses, efficiency, damage, enchantability);
}
@Nullable
public static EnumRarity addRarity(String name, TextFormatting color, String displayName)
{
return addEnum(EnumRarity.class, name, color, displayName);
}
@Nullable
public static EntityLiving.SpawnPlacementType addSpawnPlacementType(String name, BiPredicate<IBlockAccess, BlockPos> predicate)
{
return addEnum(EntityLiving.SpawnPlacementType.class, name, predicate);
}
/**
*
* @param name the name of the new {@code HorseArmorType}
* @param textureLocation the path to the texture for this armor type. It must follow the format domain:path and be relative to the assets folder.
* @param armorStrength how much protection this armor type should give
* @return the new {@code HorseArmorType}, or null if it could not be created
*/
@Nullable
public static HorseArmorType addHorseArmor(String name, String textureLocation, int armorStrength)
{
return addEnum(HorseArmorType.class, name, textureLocation, armorStrength);
}
private static void setup()
{
if (isSetup)
{
return;
}
try
{
Method getReflectionFactory = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("getReflectionFactory");
reflectionFactory = getReflectionFactory.invoke(null);
newConstructorAccessor = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("newConstructorAccessor", Constructor.class);
newInstance = Class.forName("sun.reflect.ConstructorAccessor").getDeclaredMethod("newInstance", Object[].class);
newFieldAccessor = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("newFieldAccessor", Field.class, boolean.class);
fieldAccessorSet = Class.forName("sun.reflect.FieldAccessor").getDeclaredMethod("set", Object.class, Object.class);
}
catch (Exception e)
{
FMLLog.log.error("Error setting up EnumHelper.", e);
}
isSetup = true;
}
/*
/*
* Everything below this is found at the site below, and updated to be able to compile in Eclipse/Java 1.6+
* Also modified for use in decompiled code.
* Found at: http://niceideas.ch/roller2/badtrash/entry/java_create_enum_instances_dynamically
*/
private static Object getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes) throws Exception
{
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
return newConstructorAccessor.invoke(reflectionFactory, enumClass.getDeclaredConstructor(parameterTypes));
}
private static < T extends Enum<? >> T makeEnum(Class<T> enumClass, @Nullable String value, int ordinal, Class<?>[] additionalTypes, @Nullable Object[] additionalValues) throws Exception
{
int additionalParamsCount = additionalValues == null ? 0 : additionalValues.length;
Object[] params = new Object[additionalParamsCount + 2];
params[0] = value;
params[1] = ordinal;
if (additionalValues != null)
{
System.arraycopy(additionalValues, 0, params, 2, additionalValues.length);
}
return enumClass.cast(newInstance.invoke(getConstructorAccessor(enumClass, additionalTypes), new Object[] {params}));
}
public static void setFailsafeFieldValue(Field field, @Nullable Object target, @Nullable Object value) throws Exception
{
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
Object fieldAccessor = newFieldAccessor.invoke(reflectionFactory, field, false);
fieldAccessorSet.invoke(fieldAccessor, target, value);
//new Enum(name, values.size() + 1, params)
}
private static void blankField(Class<?> enumClass, String fieldName) throws Exception
@@ -237,190 +51,35 @@ public class EnumHelper
if (field.getName().contains(fieldName))
{
field.setAccessible(true);
setFailsafeFieldValue(field, enumClass, null);
field.set(enumClass, null);
break;
}
}
}
private static void cleanEnumCache(Class<?> enumClass) throws Exception
//Class holds caches of the enum constants used for Enum.valueOf() and reflection magic. So we need to invalidate those caches when we add something new. They will automtically be re-built.
public static void cleanEnumCache(Class<?> enumClass) throws Exception
{
blankField(enumClass, "enumConstantDirectory");
blankField(enumClass, "enumConstants");
}
@Nullable
private static <T extends Enum<? >> T addEnum(Class<T> enumType, String enumName, Object... paramValues)
{
setup();
return addEnum(commonTypes, enumType, enumName, paramValues);
}
@Nullable
protected static <T extends Enum<? >> T addEnum(Class<?>[][] map, Class<T> enumType, String enumName, Object... paramValues)
{
for (Class<?>[] lookup : map)
{
if (lookup[0] == enumType)
{
Class<?>[] paramTypes = new Class<?>[lookup.length - 1];
if (paramTypes.length > 0)
{
System.arraycopy(lookup, 1, paramTypes, 0, paramTypes.length);
}
return addEnum(enumType, enumName, paramTypes, paramValues);
}
}
return null;
}
//Tests an enum is compatible with these args, throws an error if not.
public static void testEnum(Class<? extends Enum<?>> enumType, Class<?>[] paramTypes)
{
addEnum(true, enumType, null, paramTypes, (Object[])null);
}
@Nullable
public static <T extends Enum<? >> T addEnum(Class<T> enumType, String enumName, Class<?>[] paramTypes, Object... paramValues)
{
return addEnum(false, enumType, enumName, paramTypes, paramValues);
}
@SuppressWarnings({ "unchecked", "serial" })
@Nullable
private static <T extends Enum<? >> T addEnum(boolean test, final Class<T> enumType, @Nullable String enumName, final Class<?>[] paramTypes, @Nullable Object[] paramValues)
private static <T extends Enum<?> & IExpandableEnum<?>> T addEnum(boolean test, final Class<T> enumType, T newValue)
{
if (!isSetup)
{
setup();
}
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields)
{
String name = field.getName();
if (name.equals("$VALUES") || name.equals("ENUM$VALUES")) //Added 'ENUM$VALUES' because Eclipse's internal compiler doesn't follow standards
{
valuesField = field;
break;
}
}
int flags = (FMLForgePlugin.RUNTIME_DEOBF ? Modifier.PUBLIC : Modifier.PRIVATE) | Modifier.STATIC | Modifier.FINAL | 0x1000 /*SYNTHETIC*/;
if (valuesField == null)
{
String valueType = String.format("[L%s;", enumType.getName().replace('.', '/'));
for (Field field : fields)
{
if ((field.getModifiers() & flags) == flags &&
field.getType().getName().replace('.', '/').equals(valueType)) //Apparently some JVMs return .'s and some don't..
{
valuesField = field;
break;
}
}
}
if (valuesField == null)
{
final List<String> lines = Lists.newArrayList();
lines.add(String.format("Could not find $VALUES field for enum: %s", enumType.getName()));
lines.add(String.format("Runtime Deobf: %s", FMLForgePlugin.RUNTIME_DEOBF));
lines.add(String.format("Flags: %s", String.format("%16s", Integer.toBinaryString(flags)).replace(' ', '0')));
lines.add( "Fields:");
for (Field field : fields)
{
String mods = String.format("%16s", Integer.toBinaryString(field.getModifiers())).replace(' ', '0');
lines.add(String.format(" %s %s: %s", mods, field.getName(), field.getType().getName()));
}
for (String line : lines)
FMLLog.log.fatal(line);
if (test)
{
throw new EnhancedRuntimeException("Could not find $VALUES field for enum: " + enumType.getName())
{
@Override
protected void printStackTrace(WrappedPrintStream stream)
{
for (String line : lines)
stream.println(line);
}
};
}
return null;
}
if (test)
{
Object ctr = null;
Exception ex = null;
try
{
ctr = getConstructorAccessor(enumType, paramTypes);
}
catch (Exception e)
{
ex = e;
}
if (ctr == null || ex != null)
{
throw new EnhancedRuntimeException(String.format("Could not find constructor for Enum %s", enumType.getName()), ex)
{
private String toString(Class<?>[] cls)
{
StringBuilder b = new StringBuilder();
for (int x = 0; x < cls.length; x++)
{
b.append(cls[x].getName());
if (x != cls.length - 1)
b.append(", ");
}
return b.toString();
}
@Override
protected void printStackTrace(WrappedPrintStream stream)
{
stream.println("Target Arguments:");
stream.println(" java.lang.String, int, " + toString(paramTypes));
stream.println("Found Constructors:");
for (Constructor<?> ctr : enumType.getDeclaredConstructors())
{
stream.println(" " + toString(ctr.getParameterTypes()));
}
}
};
}
return null;
}
valuesField.setAccessible(true);
try
{
T[] previousValues = (T[])valuesField.get(enumType);
T[] previousValues = enumType.getEnumConstants();
T newValue = makeEnum(enumType, enumName, previousValues.length, paramTypes, paramValues);
setFailsafeFieldValue(valuesField, null, ArrayUtils.add(previousValues, newValue));
newValue.__set_values__(ArrayUtils.add(previousValues, newValue));
cleanEnumCache(enumType);
return newValue;
}
catch (Exception e)
{
FMLLog.log.error("Error adding enum with EnumHelper.", e);
throw new RuntimeException(e);
}
}
static
{
if (!isSetup)
{
setup();
}
}
}
@@ -1,100 +0,0 @@
/*
* ByteArraySeekableSource.java
*
* Created on May 17, 2006, 12:41 PM
* Copyright (c) 2006 Heiko Klein
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
package net.minecraftforge.fml.repackage.com.nothome.delta;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Wraps a byte buffer as a source
*/
public class ByteBufferSeekableSource implements SeekableSource {
private ByteBuffer bb;
private ByteBuffer cur;
/**
* Constructs a new ByteArraySeekableSource.
*/
public ByteBufferSeekableSource(byte[] source) {
this(ByteBuffer.wrap(source));
}
/**
* Constructs a new ByteArraySeekableSource.
*/
public ByteBufferSeekableSource(ByteBuffer bb) {
if (bb == null)
throw new NullPointerException("bb");
this.bb = bb;
bb.rewind();
try {
seek(0);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void seek(long pos) throws IOException {
cur = bb.slice();
if (pos > cur.limit())
throw new IOException("pos " + pos + " cannot seek " + cur.limit());
cur.position((int) pos);
}
@Override
public int read(ByteBuffer dest) throws IOException {
if (!cur.hasRemaining())
return -1;
int c = 0;
while (cur.hasRemaining() && dest.hasRemaining()) {
dest.put(cur.get());
c++;
}
return c;
}
@Override
public void close() throws IOException {
bb = null;
cur = null;
}
/**
* Returns a debug <code>String</code>.
*/
@Override
public String toString()
{
return "BBSeekable" +
" bb=" + this.bb.position() + "-" + bb.limit() +
" cur=" + this.cur.position() + "-" + cur.limit() +
"";
}
}
@@ -1,162 +0,0 @@
/*
*
* Copyright (c) 2001 Torgeir Veimo
* Copyright (c) 2002 Nicolas PERIDONT
* Copyright (c) 2006 Heiko Klein
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
package net.minecraftforge.fml.repackage.com.nothome.delta;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import com.google.common.collect.Maps;
/**
* Checksum computation class.
*/
public class Checksum {
static final boolean debug = false;
private Map<Long,Integer> checksums = Maps.newHashMap();
private static final char single_hash[] = {
/* Random numbers generated using SLIB's pseudo-random number generator. */
0xbcd1, 0xbb65, 0x42c2, 0xdffe, 0x9666, 0x431b, 0x8504, 0xeb46,
0x6379, 0xd460, 0xcf14, 0x53cf, 0xdb51, 0xdb08, 0x12c8, 0xf602,
0xe766, 0x2394, 0x250d, 0xdcbb, 0xa678, 0x02af, 0xa5c6, 0x7ea6,
0xb645, 0xcb4d, 0xc44b, 0xe5dc, 0x9fe6, 0x5b5c, 0x35f5, 0x701a,
0x220f, 0x6c38, 0x1a56, 0x4ca3, 0xffc6, 0xb152, 0x8d61, 0x7a58,
0x9025, 0x8b3d, 0xbf0f, 0x95a3, 0xe5f4, 0xc127, 0x3bed, 0x320b,
0xb7f3, 0x6054, 0x333c, 0xd383, 0x8154, 0x5242, 0x4e0d, 0x0a94,
0x7028, 0x8689, 0x3a22, 0x0980, 0x1847, 0xb0f1, 0x9b5c, 0x4176,
0xb858, 0xd542, 0x1f6c, 0x2497, 0x6a5a, 0x9fa9, 0x8c5a, 0x7743,
0xa8a9, 0x9a02, 0x4918, 0x438c, 0xc388, 0x9e2b, 0x4cad, 0x01b6,
0xab19, 0xf777, 0x365f, 0x1eb2, 0x091e, 0x7bf8, 0x7a8e, 0x5227,
0xeab1, 0x2074, 0x4523, 0xe781, 0x01a3, 0x163d, 0x3b2e, 0x287d,
0x5e7f, 0xa063, 0xb134, 0x8fae, 0x5e8e, 0xb7b7, 0x4548, 0x1f5a,
0xfa56, 0x7a24, 0x900f, 0x42dc, 0xcc69, 0x02a0, 0x0b22, 0xdb31,
0x71fe, 0x0c7d, 0x1732, 0x1159, 0xcb09, 0xe1d2, 0x1351, 0x52e9,
0xf536, 0x5a4f, 0xc316, 0x6bf9, 0x8994, 0xb774, 0x5f3e, 0xf6d6,
0x3a61, 0xf82c, 0xcc22, 0x9d06, 0x299c, 0x09e5, 0x1eec, 0x514f,
0x8d53, 0xa650, 0x5c6e, 0xc577, 0x7958, 0x71ac, 0x8916, 0x9b4f,
0x2c09, 0x5211, 0xf6d8, 0xcaaa, 0xf7ef, 0x287f, 0x7a94, 0xab49,
0xfa2c, 0x7222, 0xe457, 0xd71a, 0x00c3, 0x1a76, 0xe98c, 0xc037,
0x8208, 0x5c2d, 0xdfda, 0xe5f5, 0x0b45, 0x15ce, 0x8a7e, 0xfcad,
0xaa2d, 0x4b5c, 0xd42e, 0xb251, 0x907e, 0x9a47, 0xc9a6, 0xd93f,
0x085e, 0x35ce, 0xa153, 0x7e7b, 0x9f0b, 0x25aa, 0x5d9f, 0xc04d,
0x8a0e, 0x2875, 0x4a1c, 0x295f, 0x1393, 0xf760, 0x9178, 0x0f5b,
0xfa7d, 0x83b4, 0x2082, 0x721d, 0x6462, 0x0368, 0x67e2, 0x8624,
0x194d, 0x22f6, 0x78fb, 0x6791, 0xb238, 0xb332, 0x7276, 0xf272,
0x47ec, 0x4504, 0xa961, 0x9fc8, 0x3fdc, 0xb413, 0x007a, 0x0806,
0x7458, 0x95c6, 0xccaa, 0x18d6, 0xe2ae, 0x1b06, 0xf3f6, 0x5050,
0xc8e8, 0xf4ac, 0xc04c, 0xf41c, 0x992f, 0xae44, 0x5f1b, 0x1113,
0x1738, 0xd9a8, 0x19ea, 0x2d33, 0x9698, 0x2fe9, 0x323f, 0xcde2,
0x6d71, 0xe37d, 0xb697, 0x2c4f, 0x4373, 0x9102, 0x075d, 0x8e25,
0x1672, 0xec28, 0x6acb, 0x86cc, 0x186e, 0x9414, 0xd674, 0xd1a5
};
/**
* Initialize checksums for source. The checksum for the <code>chunkSize</code> bytes at offset
* <code>chunkSize</code> * i is inserted into a hash map.
*/
public Checksum(SeekableSource source, int chunkSize) throws IOException {
ByteBuffer bb = ByteBuffer.allocate(chunkSize * 2);
int count = 0;
while (true) {
source.read(bb);
bb.flip();
if (bb.remaining() < chunkSize)
break;
while (bb.remaining() >= chunkSize) {
long queryChecksum = queryChecksum0(bb, chunkSize);
checksums.put(queryChecksum, count++);
}
bb.compact();
}
}
/**
* Finds the checksum computed from the buffer.
* Marks, gets, then resets the buffer.
*/
public static long queryChecksum(ByteBuffer bb, int len) {
bb.mark();
long sum = queryChecksum0(bb, len);
bb.reset();
return sum;
}
private static long queryChecksum0(ByteBuffer bb, int len) {
int high = 0; int low = 0;
for (int i = 0; i < len; i++) {
low += single_hash[bb.get()+128];
high += low;
}
return ((high & 0xffff) << 16) | (low & 0xffff);
}
/**
* Increments a checksum.
* @param checksum initial checksum
* @param out byte leaving view
* @param in byte entering view
* @param chunkSize size of chunks
* @return new checksum
*/
public static long incrementChecksum(long checksum, byte out, byte in, int chunkSize) {
char old_c = single_hash[out+128];
char new_c = single_hash[in+128];
int low = ((int)((checksum) & 0xffff) - old_c + new_c) & 0xffff;
int high = ((int)((checksum) >> 16) - (old_c * chunkSize) + low) & 0xffff;
return (high << 16) | (low & 0xffff);
}
/**
* 256 random hash values.
*/
public static char[] getSingleHash() {
return single_hash;
}
/**
* Finds the index of a checksum.
*/
public int findChecksumIndex(long hashf) {
if (!checksums.containsKey(hashf))
return -1;
return checksums.get(hashf);
}
/**
* Returns a debug <code>String</code>.
*/
@Override
public String toString()
{
return super.toString() +
" checksums=" + this.checksums;
}
}
@@ -1,79 +0,0 @@
/*
*
* Copyright (c) 2001 Torgeir Veimo
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
package net.minecraftforge.fml.repackage.com.nothome.delta;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* For debugging patch generation.
*/
public class DebugDiffWriter implements DiffWriter {
private ByteArrayOutputStream os = new ByteArrayOutputStream();
/**
* Constructs a new DebugDiffWriter.
*/
public DebugDiffWriter() {}
@Override
public void addCopy(long offset, int length) throws IOException {
if (os.size() > 0)
writeBuf();
System.err.println("COPY off: " + offset + ", len: " + length);
}
@Override
public void addData(byte b) throws IOException {
os.write(b);
writeBuf();
}
private void writeBuf() {
System.err.print("DATA: ");
byte[] ba = os.toByteArray();
for (int ix = 0; ix < ba.length; ix++) {
if (ba[ix] == '\n')
System.err.print("\\n");
else
System.err.print(String.valueOf((char) ba[ix]));
//System.err.print("0x" + Integer.toHexString(buf[ix]) + " "); // hex output
}
System.err.println("");
os.reset();
}
@Override
public void flush() throws IOException {
System.err.println("FLUSH");
}
@Override
public void close() throws IOException {
System.err.println("CLOSE");
}
}
@@ -1,447 +0,0 @@
/*
*
* Copyright (c) 2001 Torgeir Veimo
* Copyright (c) 2002 Nicolas PERIDONT
* Bug Fixes: Daniel Morrione [email protected]
* Copyright (c) 2006 Heiko Klein
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Change Log:
* iiimmddyyn nnnnn Description
* ---------- ----- -------------------------------------------------------
* gls100603a Fixes from Torgeir Veimo and Dan Morrione
* gls110603a Stream not being closed thus preventing a file from
* being subsequently deleted.
* gls031504a Error being written to stderr rather than throwing exception
*/
package net.minecraftforge.fml.repackage.com.nothome.delta;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
/**
* Class for computing deltas against a source.
* The source file is read by blocks and a hash is computed per block.
* Then the target is scanned for matching blocks.
* <p/>
* This class is not thread safe. Use one instance per thread.
* <p/>
* This class should support files over 4GB in length, although you must
* use a larger checksum size, such as 1K, as all checksums use "int" indexing.
* Newer versions may eventually support paging in/out of checksums.
*/
public class Delta {
/**
* Debug flag.
*/
final static boolean debug = false;
/**
* Default size of 16.
* For "Lorem ipsum" text files (see the tests) the ideal size is about 14.
* Any smaller and the patch size becomes actually be larger.
* <p>
* Use a size like 64 or 128 for large files.
*/
public static final int DEFAULT_CHUNK_SIZE = 1<<4;
/**
* Chunk Size.
*/
private int S;
private SourceState source;
private TargetState target;
private DiffWriter output;
/**
* Constructs a new Delta.
* In the future, additional constructor arguments will set the algorithm details.
*/
public Delta() {
setChunkSize(DEFAULT_CHUNK_SIZE);
}
/**
* Sets the chunk size used.
* Larger chunks are faster and use less memory, but create larger patches
* as well.
*
* @param size
*/
public void setChunkSize(int size) {
if (size <= 0)
throw new IllegalArgumentException("Invalid size");
S = size;
}
/**
* Compares the source bytes with target bytes, writing to output.
*/
public void compute(byte source[], byte target[], OutputStream output)
throws IOException {
compute(new ByteBufferSeekableSource(source),
new ByteArrayInputStream(target),
new GDiffWriter(output));
}
/**
* Compares the source bytes with target bytes, returning output.
*/
public byte[] compute(byte source[], byte target[])
throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
compute(source, target, os);
return os.toByteArray();
}
/**
* Compares the source bytes with target input, writing to output.
*/
public void compute(byte[] sourceBytes, InputStream inputStream,
DiffWriter diffWriter) throws IOException
{
compute(new ByteBufferSeekableSource(sourceBytes),
inputStream, diffWriter);
}
/**
* Compares the source file with a target file, writing to output.
*
* @param output will be closed
*/
public void compute(File sourceFile, File targetFile, DiffWriter output)
throws IOException {
RandomAccessFileSeekableSource source = new RandomAccessFileSeekableSource(new RandomAccessFile(sourceFile, "r"));
InputStream is = new BufferedInputStream(new FileInputStream(targetFile));
try {
compute(source, is, output);
} finally {
source.close();
is.close();
}
}
/**
* Compares the source with a target, writing to output.
*
* @param output will be closed
*/
public void compute(SeekableSource seekSource, InputStream targetIS, DiffWriter output)
throws IOException {
if (debug) {
debug("using match length S = " + S);
}
source = new SourceState(seekSource);
target = new TargetState(targetIS);
this.output = output;
if (debug)
debug("checksums " + source.checksum);
while (!target.eof()) {
debug("!target.eof()");
int index = target.find(source);
if (index != -1) {
if (debug)
debug("found hash " + index);
long offset = (long)index * S;
source.seek(offset);
int match = target.longestMatch(source);
if (match >= S) {
if (debug)
debug("output.addCopy("+offset+","+match+")");
output.addCopy(offset, match);
} else {
// move the position back according to how much we can't copy
target.tbuf.position(target.tbuf.position() - match);
addData();
}
} else {
addData();
}
}
output.close();
}
private void addData() throws IOException {
int i = target.read();
if (debug)
debug("addData " + Integer.toHexString(i));
if (i == -1)
return;
output.addData((byte)i);
}
class SourceState {
private Checksum checksum;
private SeekableSource source;
public SourceState(SeekableSource source) throws IOException {
checksum = new Checksum(source, S);
this.source = source;
source.seek(0);
}
public void seek(long index) throws IOException {
source.seek(index);
}
/**
* Returns a debug <code>String</code>.
*/
@Override
public String toString()
{
return "Source"+
" checksum=" + this.checksum +
" source=" + this.source +
"";
}
}
class TargetState {
private ReadableByteChannel c;
private ByteBuffer tbuf = ByteBuffer.allocate(blocksize());
private ByteBuffer sbuf = ByteBuffer.allocate(blocksize());
private long hash;
private boolean hashReset = true;
private boolean eof;
TargetState(InputStream targetIS) throws IOException {
c = Channels.newChannel(targetIS);
tbuf.limit(0);
}
private int blocksize() {
return Math.min(1024 * 16, S * 4);
}
/**
* Returns the index of the next N bytes of the stream.
*/
public int find(SourceState source) throws IOException {
if (eof)
return -1;
sbuf.clear();
sbuf.limit(0);
if (hashReset) {
debug("hashReset");
while (tbuf.remaining() < S) {
tbuf.compact();
int read = c.read(tbuf);
tbuf.flip();
if (read == -1) {
debug("target ending");
return -1;
}
}
hash = Checksum.queryChecksum(tbuf, S);
hashReset = false;
}
if (debug)
debug("hash " + hash + " " + dump());
return source.checksum.findChecksumIndex(hash);
}
public boolean eof() {
return eof;
}
/**
* Reads a byte.
* @throws IOException
*/
public int read() throws IOException {
if (tbuf.remaining() <= S) {
readMore();
if (!tbuf.hasRemaining()) {
eof = true;
return -1;
}
}
byte b = tbuf.get();
if (tbuf.remaining() >= S) {
byte nchar = tbuf.get( tbuf.position() + S -1 );
hash = Checksum.incrementChecksum(hash, b, nchar, S);
} else {
debug("out of char");
}
return b & 0xFF;
}
/**
* Returns the longest match length at the source location.
*/
public int longestMatch(SourceState source) throws IOException {
debug("longestMatch");
int match = 0;
hashReset = true;
while (true) {
if (!sbuf.hasRemaining()) {
sbuf.clear();
int read = source.source.read(sbuf);
sbuf.flip();
if (read == -1)
return match;
}
if (!tbuf.hasRemaining()) {
readMore();
if (!tbuf.hasRemaining()) {
debug("target ending");
eof = true;
return match;
}
}
if (sbuf.get() != tbuf.get()) {
tbuf.position(tbuf.position() - 1);
return match;
}
match++;
}
}
private void readMore() throws IOException {
if (debug)
debug("readMore " + tbuf);
tbuf.compact();
c.read(tbuf);
tbuf.flip();
}
void hash() {
hash = Checksum.queryChecksum(tbuf, S);
}
/**
* Returns a debug <code>String</code>.
*/
@Override
public String toString()
{
return "Target[" +
" targetBuff=" + dump() + // this.tbuf +
" sourceBuff=" + this.sbuf +
" hashf=" + this.hash +
" eof=" + this.eof +
"]";
}
private String dump() { return dump(tbuf); }
private String dump(ByteBuffer bb) {
return getTextDump(bb);
}
private void append(StringBuffer sb, int value) {
char b1 = (char)((value >> 4) & 0x0F);
char b2 = (char)((value) & 0x0F);
sb.append( Character.forDigit(b1, 16) );
sb.append( Character.forDigit(b2, 16) );
}
public String getTextDump(ByteBuffer bb)
{
StringBuffer sb = new StringBuffer(bb.remaining() * 2);
bb.mark();
while (bb.hasRemaining()) {
int val = bb.get();
if (val > 32 && val < 127)
sb.append(" ").append((char)val);
else
append(sb, val);
}
bb.reset();
return sb.toString();
}
}
/**
* Creates a patch using file names.
*/
public static void main(String argv[]) throws Exception {
if (argv.length != 3) {
System.err.println("usage Delta [-d] source target [output]");
System.err.println("either -d or an output filename must be specified.");
System.err.println("aborting..");
return;
}
DiffWriter output = null;
File sourceFile = null;
File targetFile = null;
if (argv[0].equals("-d")) {
sourceFile = new File(argv[1]);
targetFile = new File(argv[2]);
output = new DebugDiffWriter();
} else {
sourceFile = new File(argv[0]);
targetFile = new File(argv[1]);
output =
new GDiffWriter(
new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(new File(argv[2])))));
}
if (sourceFile.length() > Integer.MAX_VALUE
|| targetFile.length() > Integer.MAX_VALUE) {
System.err.println(
"source or target is too large, max length is "
+ Integer.MAX_VALUE);
System.err.println("aborting..");
output.close();
return;
}
Delta d = new Delta();
d.compute(sourceFile, targetFile, output);
output.flush();
output.close();
if (debug) //gls031504a
System.out.println("finished generating delta");
}
private void debug(String s) {
if (debug)
System.err.println(s);
}
}
@@ -1,58 +0,0 @@
/*
*
* Copyright (c) 2001 Torgeir Veimo
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
package net.minecraftforge.fml.repackage.com.nothome.delta;
import java.io.Closeable;
import java.io.IOException;
/**
* Interface for DIFF writers.
*/
public interface DiffWriter extends Closeable {
/**
* Add a GDIFF copy instruction.
*/
public void addCopy(long offset, int length) throws IOException;
/**
* Add a GDIFF data instruction.
* Implementors should buffer the data.
*/
public void addData(byte b) throws IOException;
/**
* Flushes to output, e.g. any data added.
*/
public void flush() throws IOException;
/**
* Closes this stream.
* Note that {@link DiffWriter} will invoke this method at the end.
*/
@Override
public void close() throws IOException;
}
@@ -1,248 +0,0 @@
/*
*
* Copyright (c) 2001 Torgeir Veimo
* Copyright (c) 2006 Heiko Klein
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
package net.minecraftforge.fml.repackage.com.nothome.delta;
import org.apache.commons.io.IOUtils;
import static net.minecraftforge.fml.repackage.com.nothome.delta.GDiffWriter.COPY_INT_INT;
import static net.minecraftforge.fml.repackage.com.nothome.delta.GDiffWriter.COPY_INT_UBYTE;
import static net.minecraftforge.fml.repackage.com.nothome.delta.GDiffWriter.COPY_INT_USHORT;
import static net.minecraftforge.fml.repackage.com.nothome.delta.GDiffWriter.COPY_LONG_INT;
import static net.minecraftforge.fml.repackage.com.nothome.delta.GDiffWriter.COPY_USHORT_INT;
import static net.minecraftforge.fml.repackage.com.nothome.delta.GDiffWriter.COPY_USHORT_UBYTE;
import static net.minecraftforge.fml.repackage.com.nothome.delta.GDiffWriter.COPY_USHORT_USHORT;
import static net.minecraftforge.fml.repackage.com.nothome.delta.GDiffWriter.DATA_INT;
import static net.minecraftforge.fml.repackage.com.nothome.delta.GDiffWriter.DATA_MAX;
import static net.minecraftforge.fml.repackage.com.nothome.delta.GDiffWriter.DATA_USHORT;
import static net.minecraftforge.fml.repackage.com.nothome.delta.GDiffWriter.EOF;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
/**
* This class patches an input file with a GDIFF patch file.
*
* The patch file follows the GDIFF file specification available at
*
* <a href="http://www.w3.org/TR/NOTE-gdiff-19970901.html">http://www.w3.org/TR/NOTE-gdiff-19970901.html</a>.
*/
public class GDiffPatcher {
private ByteBuffer buf = ByteBuffer.allocate(1024);
private byte buf2[] = buf.array();
/**
* Constructs a new GDiffPatcher.
*/
public GDiffPatcher() {
}
/**
* Patches to an output file.
*/
public void patch(File sourceFile, File patchFile, File outputFile)
throws IOException
{
RandomAccessFileSeekableSource source =new RandomAccessFileSeekableSource(new RandomAccessFile(sourceFile, "r"));
InputStream patch = null;
OutputStream output = null;
try {
patch = new FileInputStream(patchFile);
output = new FileOutputStream(outputFile);
patch(source, patch, output);
} finally {
IOUtils.closeQuietly(source);
IOUtils.closeQuietly(patch);
IOUtils.closeQuietly(output);
}
}
/**
* Patches to an output stream.
*/
public void patch(byte[] source, InputStream patch, OutputStream output) throws IOException {
patch(new ByteBufferSeekableSource(source), patch, output);
}
/**
* Patches in memory, returning the patch result.
*/
public byte[] patch(byte[] source, byte[] patch) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
patch(source, new ByteArrayInputStream(patch), os);
return os.toByteArray();
}
/**
* Patches to an output stream.
*/
public void patch(SeekableSource source, InputStream patch, OutputStream out) throws IOException {
DataOutputStream outOS = new DataOutputStream(out);
DataInputStream patchIS = new DataInputStream(patch);
// the magic string is 'd1 ff d1 ff' + the version number
if (patchIS.readUnsignedByte() != 0xd1 ||
patchIS.readUnsignedByte() != 0xff ||
patchIS.readUnsignedByte() != 0xd1 ||
patchIS.readUnsignedByte() != 0xff ||
patchIS.readUnsignedByte() != 0x04) {
throw new PatchException("magic string not found, aborting!");
}
while (true) {
int command = patchIS.readUnsignedByte();
if (command == EOF)
break;
int length;
int offset;
if (command <= DATA_MAX) {
append(command, patchIS, outOS);
continue;
}
switch (command) {
case DATA_USHORT: // ushort, n bytes following; append
length = patchIS.readUnsignedShort();
append(length, patchIS, outOS);
break;
case DATA_INT: // int, n bytes following; append
length = patchIS.readInt();
append(length, patchIS, outOS);
break;
case COPY_USHORT_UBYTE:
offset = patchIS.readUnsignedShort();
length = patchIS.readUnsignedByte();
copy(offset, length, source, outOS);
break;
case COPY_USHORT_USHORT:
offset = patchIS.readUnsignedShort();
length = patchIS.readUnsignedShort();
copy(offset, length, source, outOS);
break;
case COPY_USHORT_INT:
offset = patchIS.readUnsignedShort();
length = patchIS.readInt();
copy(offset, length, source, outOS);
break;
case COPY_INT_UBYTE:
offset = patchIS.readInt();
length = patchIS.readUnsignedByte();
copy(offset, length, source, outOS);
break;
case COPY_INT_USHORT:
offset = patchIS.readInt();
length = patchIS.readUnsignedShort();
copy(offset, length, source, outOS);
break;
case COPY_INT_INT:
offset = patchIS.readInt();
length = patchIS.readInt();
copy(offset, length, source, outOS);
break;
case COPY_LONG_INT:
long loffset = patchIS.readLong();
length = patchIS.readInt();
copy(loffset, length, source, outOS);
break;
default:
throw new IllegalStateException("command " + command);
}
}
outOS.flush();
}
private void copy(long offset, int length, SeekableSource source, OutputStream output)
throws IOException
{
source.seek(offset);
while (length > 0) {
int len = Math.min(buf.capacity(), length);
buf.clear().limit(len);
int res = source.read(buf);
if (res == -1)
throw new EOFException("in copy " + offset + " " + length);
output.write(buf.array(), 0, res);
length -= res;
}
}
private void append(int length, InputStream patch, OutputStream output) throws IOException {
while (length > 0) {
int len = Math.min(buf2.length, length);
int res = patch.read(buf2, 0, len);
if (res == -1)
throw new EOFException("cannot read " + length);
output.write(buf2, 0, res);
length -= res;
}
}
/**
* Simple command line tool to patch a file.
*/
public static void main(String argv[]) {
if (argv.length != 3) {
System.err.println("usage GDiffPatch source patch output");
System.err.println("aborting..");
return;
}
try {
File sourceFile = new File(argv[0]);
File patchFile = new File(argv[1]);
File outputFile = new File(argv[2]);
if (sourceFile.length() > Integer.MAX_VALUE ||
patchFile.length() > Integer.MAX_VALUE) {
System.err.println("source or patch is too large, max length is " + Integer.MAX_VALUE);
System.err.println("aborting..");
return;
}
GDiffPatcher patcher = new GDiffPatcher();
patcher.patch(sourceFile, patchFile, outputFile);
System.out.println("finished patching file");
} catch (Exception ioe) { //gls031504a
System.err.println("error while patching: " + ioe);
}
}
}
@@ -1,178 +0,0 @@
/*
*
* Copyright (c) 2001 Torgeir Veimo
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
package net.minecraftforge.fml.repackage.com.nothome.delta;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* Outputs a diff following the GDIFF file specification available at
* http://www.w3.org/TR/NOTE-gdiff-19970901.html.
*/
public class GDiffWriter implements DiffWriter {
/**
* Max length of a chunk.
*/
public static final int CHUNK_SIZE = Short.MAX_VALUE;
public static final byte EOF = 0;
/**
* Max length for single length data encode.
*/
public static final int DATA_MAX = 246;
public static final int DATA_USHORT = 247;
public static final int DATA_INT = 248;
public static final int COPY_USHORT_UBYTE = 249;
public static final int COPY_USHORT_USHORT = 250;
public static final int COPY_USHORT_INT = 251;
public static final int COPY_INT_UBYTE = 252;
public static final int COPY_INT_USHORT = 253;
public static final int COPY_INT_INT = 254;
public static final int COPY_LONG_INT = 255;
private ByteArrayOutputStream buf = new ByteArrayOutputStream();
private boolean debug = false;
private DataOutputStream output = null;
/**
* Constructs a new GDiffWriter.
*/
public GDiffWriter(DataOutputStream os) throws IOException {
this.output = os;
// write magic string "d1 ff d1 ff 04"
output.writeByte(0xd1);
output.writeByte(0xff);
output.writeByte(0xd1);
output.writeByte(0xff);
output.writeByte(0x04);
}
/**
* Constructs a new GDiffWriter.
*/
public GDiffWriter(OutputStream output) throws IOException {
this(new DataOutputStream(output));
}
@Override
public void addCopy(long offset, int length) throws IOException {
writeBuf();
//output debug data
if (debug)
System.err.println("COPY off: " + offset + ", len: " + length);
// output real data
if (offset > Integer.MAX_VALUE) {
// Actually, we don't support longer files than int.MAX_VALUE at the moment..
output.writeByte(COPY_LONG_INT);
output.writeLong(offset);
output.writeInt(length);
} else if (offset < 65536) {
if (length < 256) {
output.writeByte(COPY_USHORT_UBYTE);
output.writeShort((int)offset);
output.writeByte(length);
} else if (length > 65535) {
output.writeByte(COPY_USHORT_INT);
output.writeShort((int)offset);
output.writeInt(length);
} else {
output.writeByte(COPY_USHORT_USHORT);
output.writeShort((int)offset);
output.writeShort(length);
}
} else {
if (length < 256) {
output.writeByte(COPY_INT_UBYTE);
output.writeInt((int)offset);
output.writeByte(length);
} else if (length > 65535) {
output.writeByte(COPY_INT_INT);
output.writeInt((int)offset);
output.writeInt(length);
} else {
output.writeByte(COPY_INT_USHORT);
output.writeInt((int)offset);
output.writeShort(length);
}
}
}
/**
* Adds a data byte.
*/
@Override
public void addData(byte b) throws IOException {
buf.write(b);
if (buf.size() >= CHUNK_SIZE)
writeBuf();
}
private void writeBuf() throws IOException {
if (buf.size() > 0) {
if (buf.size() <= DATA_MAX) {
output.writeByte(buf.size());
} else if (buf.size() <= 65535) {
output.writeByte(DATA_USHORT);
output.writeShort(buf.size());
} else {
output.writeByte(DATA_INT);
output.writeInt(buf.size());
}
buf.writeTo(output);
buf.reset();
}
}
/**
* Flushes accumulated data bytes, if any.
*/
@Override
public void flush() throws IOException
{
writeBuf();
output.flush();
}
/**
* Writes the final EOF byte, closes the underlying stream.
*/
@Override
public void close() throws IOException {
this.flush();
output.write(EOF);
output.close();
}
}
@@ -1,51 +0,0 @@
/*
* PatchException.java
*
* Created on June 6, 2006, 9:34 PM
* Copyright (c) 2006 Heiko Klein
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
package net.minecraftforge.fml.repackage.com.nothome.delta;
import java.io.IOException;
/**
* Thrown when a patch is invalid.
*/
public class PatchException extends IOException {
private static final long serialVersionUID = 1;
/**
* Creates a new instance of <code>PatchException</code> without detail message.
*/
public PatchException() {
}
/**
* Constructs an instance of <code>PatchException</code> with the specified detail message.
* @param msg the detail message.
*/
public PatchException(String msg) {
super(msg);
}
}
@@ -1,78 +0,0 @@
/*
* RandomAccessFileSeekableSource.java
*
* Created on May 17, 2006, 1:45 PM
* Copyright (c) 2006 Heiko Klein
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*
*/
package net.minecraftforge.fml.repackage.com.nothome.delta;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
/**
* Wraps a random access file.
*/
public class RandomAccessFileSeekableSource implements SeekableSource {
private RandomAccessFile raf;
/**
* Constructs a new RandomAccessFileSeekableSource.
* @param raf
*/
public RandomAccessFileSeekableSource(RandomAccessFile raf) {
if (raf == null)
throw new NullPointerException("raf");
this.raf = raf;
}
@Override
public void seek(long pos) throws IOException {
raf.seek(pos);
}
public int read(byte[] b, int off, int len) throws IOException {
return raf.read(b, off, len);
}
public long length() throws IOException {
return raf.length();
}
@Override
public void close() throws IOException {
raf.close();
}
@Override
public int read(ByteBuffer bb) throws IOException {
int c = raf.read(bb.array(), bb.position(), bb.remaining());
if (c == -1)
return -1;
bb.position(bb.position() + c);
return c;
}
}
@@ -1,51 +0,0 @@
/*
* SeekableSource.java
*
* Created on May 17, 2006, 12:33 PM
* Copyright (c) 2006 Heiko Klein
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
package net.minecraftforge.fml.repackage.com.nothome.delta;
import java.io.Closeable;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
/**
* For sources of random-access data, such as {@link RandomAccessFile}.
*/
public interface SeekableSource extends Closeable {
/**
* Sets the position for the next {@link #read(ByteBuffer)}.
*/
void seek(long pos) throws IOException ;
/**
* Reads up to {@link ByteBuffer#remaining()} bytes from the source,
* returning the number of bytes read, or -1 if no bytes were read
* and EOF was reached.
*/
int read(ByteBuffer bb) throws IOException;
}
@@ -31,7 +31,8 @@ import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.message.SimpleMessage;
import java.util.Collection;
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.registry;
package net.minecraftforge.registries;
import net.minecraft.block.Block;
import net.minecraft.enchantment.Enchantment;
@@ -29,10 +29,9 @@ import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionType;
import net.minecraft.util.SoundEvent;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.common.registry.VillagerRegistry;
import net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession;
import net.minecraftforge.registries.GameData;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.RegistryManager;
/**
* A class that exposes static references to all vanilla and Forge registries.
@@ -198,19 +198,9 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
return Collections.unmodifiableSet(this.names.keySet());
}
/**
* @deprecated use {@link #getValuesCollection} to avoid copying
*/
@Deprecated
@Override
public List<V> getValues()
{
return ImmutableList.copyOf(this.names.values());
}
@Nonnull
@Override
public Collection<V> getValuesCollection()
public Collection<V> getValues()
{
return Collections.unmodifiableSet(this.names.values());
}
@@ -793,7 +783,7 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
NBTTagCompound tag = new NBTTagCompound();
tag.setString("K", e.getKey().toString());
tag.setInteger("V", e.getValue());
ids.appendTag(tag);
ids.add(tag);
});
data.setTag("ids", ids);
@@ -803,7 +793,7 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
NBTTagCompound tag = new NBTTagCompound();
tag.setString("K", e.getKey().toString());
tag.setString("V", e.getKey().toString());
aliases.appendTag(tag);
aliases.add(tag);
});
data.setTag("aliases", aliases);
@@ -813,7 +803,7 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
NBTTagCompound tag = new NBTTagCompound();
tag.setString("K", e.getKey().toString());
tag.setString("V", e.getValue());
overrides.appendTag(tag);
overrides.add(tag);
});
data.setTag("overrides", overrides);
@@ -821,7 +811,7 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
data.setIntArray("blocked", blocked);
NBTTagList dummied = new NBTTagList();
this.dummied.stream().sorted().forEach(e -> dummied.appendTag(new NBTTagString(e.toString())));
this.dummied.stream().sorted().forEach(e -> dummied.add(new NBTTagString(e.toString())));
data.setTag("dummied", dummied);
return data;
@@ -846,24 +836,7 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
list.forEach(e ->
{
NBTTagCompound comp = (NBTTagCompound)e;
String v = comp.getString("V");
if (v.indexOf(':') == -1) //Forge Bug: https://github.com/MinecraftForge/MinecraftForge/issues/4894 TODO: Remove in 1.13
{
ret.overrides.put(new ResourceLocation(comp.getString("K")), v);
}
else
{
ResourceLocation aliask = new ResourceLocation(comp.getString("K"));
ResourceLocation aliasv = new ResourceLocation(v);
if (aliasv.equals(aliask))
{
FMLLog.log.warn("Found unrecoverable 4894 bugged alias/override: {} -> {}, skipping.", aliask, aliasv);
}
else
{
ret.aliases.put(aliask, aliasv);
}
}
ret.overrides.put(new ResourceLocation(comp.getString("K")), comp.getString("V"));
});
list = nbt.getTagList("overrides", 10);
@@ -30,7 +30,7 @@ import javax.annotation.Nullable;
* if another entry overrides existing ones in the registry.
*/
@SuppressWarnings("unchecked")
public abstract class ForgeRegistryEntry<V extends ForgeRegistryEntry<V>> implements IForgeRegistryEntry<V>
public abstract class ForgeRegistryEntry<V extends IForgeRegistryEntry<V>> implements IForgeRegistryEntry<V>
{
@SuppressWarnings("serial")
private final TypeToken<V> token = new TypeToken<V>(getClass()){};
@@ -21,7 +21,7 @@ package net.minecraftforge.registries;
import net.minecraft.util.ResourceLocation;
public interface IForgeRegistryModifiable<V extends ForgeRegistryEntry<V>> extends IForgeRegistry<V>
public interface IForgeRegistryModifiable<V extends IForgeRegistryEntry<V>> extends IForgeRegistry<V>
{
void clear();
V remove(ResourceLocation key);
@@ -122,7 +122,7 @@ class NamespacedDefaultedWrapper<V extends IForgeRegistryEntry<V>> extends Regis
@Nullable
public V getRandomObject(Random random)
{
Collection<V> values = this.delegate.getValuesCollection();
Collection<V> values = this.delegate.getValues();
return values.stream().skip(random.nextInt(values.size())).findFirst().orElse(null);
}
@@ -117,7 +117,7 @@ class NamespacedWrapper<V extends IForgeRegistryEntry<V>> extends RegistryNamesp
@Nullable
public V getRandomObject(Random random)
{
Collection<V> values = this.delegate.getValuesCollection();
Collection<V> values = this.delegate.getValues();
return values.stream().skip(random.nextInt(values.size())).findFirst().orElse(null);
}
@@ -0,0 +1,42 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.registries;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* ObjectHolder can be used to automatically populate public static final fields with entries
* from the registry. These values can then be referred within mod code directly.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
public @interface ObjectHolder
{
/**
* If used on a class, this represents a modid only.
* If used on a field, it represents a name, which can be abbreviated or complete.
* Abbreviated names derive their modid from an enclosing ObjectHolder at the class level.
*
* @return either a modid or a name based on the rules above
*/
String value();
}
@@ -20,7 +20,6 @@
package net.minecraftforge.registries;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.LinkedList;
@@ -28,23 +27,23 @@ import java.util.Queue;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder;
import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Internal class used in tracking {@link ObjectHolder} references
*/
@SuppressWarnings("rawtypes")
class ObjectHolderRef
{
private static final Logger LOGGER = LogManager.getLogger();
private Field field;
private ResourceLocation injectedObject;
private boolean isValid;
private ForgeRegistry<?> registry;
@SuppressWarnings("unchecked")
ObjectHolderRef(Field field, ResourceLocation injectedObject, boolean extractFromExistingValues)
{
registry = getRegistryForType(field);
@@ -66,7 +65,7 @@ class ObjectHolderRef
}
else
{
this.injectedObject = ((ForgeRegistryEntry)existing).getRegistryName();
this.injectedObject = ((IForgeRegistryEntry)existing).getRegistryName();
}
}
catch (IllegalAccessException e)
@@ -83,13 +82,12 @@ class ObjectHolderRef
{
throw new IllegalStateException(String.format("The ObjectHolder annotation cannot apply to a field that does not map to a registry. Ensure the registry was created during the RegistryEvent.NewRegistry event. (found : %s at %s.%s)", field.getType().getName(), field.getClass().getName(), field.getName()));
}
try
field.setAccessible(true);
if (Modifier.isFinal(field.getModifiers()))
{
FinalFieldHelper.makeWritable(field);
}
catch (ReflectiveOperationException e)
{
throw new RuntimeException(e);
throw new RuntimeException("@ObjectHolder on final field, our transformer did not run? " + field.getDeclaringClass().getName() + "/" + field.getName());
}
}
@@ -137,46 +135,16 @@ class ObjectHolderRef
if (thing == null)
{
FMLLog.log.debug("Unable to lookup {} for {}. This means the object wasn't registered. It's likely just mod options.", injectedObject, field);
LOGGER.debug("Unable to lookup {} for {}. This means the object wasn't registered. It's likely just mod options.", injectedObject, field);
return;
}
try
{
FinalFieldHelper.setField(field, null, thing);
field.set(null, thing);
}
catch (IllegalArgumentException | ReflectiveOperationException e)
{
FMLLog.log.warn("Unable to set {} with value {} ({})", this.field, thing, this.injectedObject, e);
}
}
private static class FinalFieldHelper
{
private static Field modifiersField;
private static Object reflectionFactory;
private static Method newFieldAccessor;
private static Method fieldAccessorSet;
static Field makeWritable(Field f) throws ReflectiveOperationException
{
f.setAccessible(true);
if (modifiersField == null)
{
Method getReflectionFactory = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("getReflectionFactory");
reflectionFactory = getReflectionFactory.invoke(null);
newFieldAccessor = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("newFieldAccessor", Field.class, boolean.class);
fieldAccessorSet = Class.forName("sun.reflect.FieldAccessor").getDeclaredMethod("set", Object.class, Object.class);
modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
}
modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);
return f;
}
static void setField(Field field, @Nullable Object instance, Object thing) throws ReflectiveOperationException
{
Object fieldAccessor = newFieldAccessor.invoke(reflectionFactory, field, false);
fieldAccessorSet.invoke(fieldAccessor, instance, thing);
LOGGER.warn("Unable to set {} with value {} ({})", this.field, thing, this.injectedObject, e);
}
}
}
@@ -26,66 +26,48 @@ import java.util.Map;
import java.util.Set;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Opcodes;
/**
* Internal registry for tracking {@link ObjectHolder} references
*/
public enum ObjectHolderRegistry
{
INSTANCE;
private static final Logger LOGGER = LogManager.getLogger();
private List<ObjectHolderRef> objectHolders = Lists.newArrayList();
public void findObjectHolders(ASMDataTable table)
{
FMLLog.log.info("Processing ObjectHolder annotations");
Set<ASMData> allObjectHolders = table.getAll(GameRegistry.ObjectHolder.class.getName());
LOGGER.info("Processing ObjectHolder annotations");
Set<ASMData> allObjectHolders = table.getAll(ObjectHolder.class.getName());
Map<String, String> classModIds = Maps.newHashMap();
Map<String, Class<?>> classCache = Maps.newHashMap();
for (ASMData data : table.getAll(Mod.class.getName()))
{
String modid = (String)data.getAnnotationInfo().get("modid");
classModIds.put(data.getClassName(), modid);
}
for (ASMData data : allObjectHolders)
{
String className = data.getClassName();
String annotationTarget = data.getObjectName();
String value = (String) data.getAnnotationInfo().get("value");
boolean isClass = className.equals(annotationTarget);
if (isClass)
{
scanTarget(classModIds, classCache, className, annotationTarget, value, isClass, false);
}
}
table.getAll(Mod.class.getName()).forEach(data -> classModIds.put(data.getClassName(), (String)data.getAnnotationInfo().get("value")));
// double pass - get all the class level annotations first, then the field level annotations
for (ASMData data : allObjectHolders)
allObjectHolders.stream().filter(data -> data.getObjectName().equals(data.getClassName())).forEach(data ->
{
String className = data.getClassName();
String annotationTarget = data.getObjectName();
String value = (String) data.getAnnotationInfo().get("value");
boolean isClass = className.equals(annotationTarget);
if (!isClass)
{
scanTarget(classModIds, classCache, className, annotationTarget, value, isClass, false);
}
}
scanTarget(classModIds, classCache, "net.minecraft.init.Blocks", null, "minecraft", true, true);
scanTarget(classModIds, classCache, "net.minecraft.init.Items", null, "minecraft", true, true);
scanTarget(classModIds, classCache, "net.minecraft.init.MobEffects", null, "minecraft", true, true);
scanTarget(classModIds, classCache, "net.minecraft.init.Biomes", null, "minecraft", true, true);
scanTarget(classModIds, classCache, "net.minecraft.init.Enchantments", null, "minecraft", true, true);
scanTarget(classModIds, classCache, "net.minecraft.init.SoundEvents", null, "minecraft", true, true);
scanTarget(classModIds, classCache, "net.minecraft.init.PotionTypes", null, "minecraft", true, true);
FMLLog.log.info("Found {} ObjectHolder annotations", objectHolders.size());
String value = (String)data.getAnnotationInfo().get("value");
scanTarget(classModIds, classCache, data.getClassName(), data.getObjectName(), value, true, data.getClassName().startsWith("net.minecraft.init"));
});
allObjectHolders.stream().filter(data -> !data.getObjectName().equals(data.getClassName())).forEach(data ->
{
String value = (String)data.getAnnotationInfo().get("value");
scanTarget(classModIds, classCache, data.getClassName(), data.getObjectName(), value, false, false);
});
LOGGER.info("Found {} ObjectHolder annotations", objectHolders.size());
}
private void scanTarget(Map<String, String> classModIds, Map<String, Class<?>> classCache, String className, @Nullable String annotationTarget, String value, boolean isClass, boolean extractFromValue)
@@ -119,7 +101,7 @@ public enum ObjectHolderRegistry
String prefix = classModIds.get(className);
if (prefix == null)
{
FMLLog.log.warn("Found an unqualified ObjectHolder annotation ({}) without a modid context at {}.{}, ignoring", value, className, annotationTarget);
LOGGER.warn("Found an unqualified ObjectHolder annotation ({}) without a modid context at {}.{}, ignoring", value, className, annotationTarget);
throw new IllegalStateException("Unqualified reference to ObjectHolder");
}
value = prefix + ":" + value;
@@ -140,11 +122,10 @@ public enum ObjectHolderRegistry
private void scanClassForFields(Map<String, String> classModIds, String className, String value, Class<?> clazz, boolean extractFromExistingValues)
{
classModIds.put(className, value);
final int flags = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_SYNTHETIC;
for (Field f : clazz.getFields())
{
int mods = f.getModifiers();
boolean isMatch = Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods);
if (!isMatch || f.isAnnotationPresent(ObjectHolder.class))
if (((f.getModifiers() & flags) != flags) || f.isAnnotationPresent(ObjectHolder.class))
{
continue;
}
@@ -162,12 +143,9 @@ public enum ObjectHolderRegistry
public void applyObjectHolders()
{
FMLLog.log.info("Applying holder lookups");
for (ObjectHolderRef ohr : objectHolders)
{
ohr.apply();
}
FMLLog.log.info("Holder lookups applied");
LOGGER.info("Applying holder lookups");
objectHolders.forEach(ObjectHolderRef::apply);
LOGGER.info("Holder lookups applied");
}
}