repo_id
stringclasses
383 values
file_path
stringlengths
7
168
content
stringlengths
0
1.75M
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\rfb\AngelicaRfbPlugin.java
package com.gtnewhorizons.angelica.loading.rfb; import com.gtnewhorizons.angelica.loading.rfb.transformers.RFBAngelicaRedirector; import com.gtnewhorizons.angelica.loading.rfb.transformers.RFBSodiumBlockTransformer; import com.gtnewhorizons.retrofuturabootstrap.api.PluginContext; import com.gtnewhorizons.retrofuturabootstrap.api.RetroFuturaBootstrap; import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer; import com.gtnewhorizons.retrofuturabootstrap.api.RfbPlugin; import net.minecraft.launchwrapper.Launch; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class AngelicaRfbPlugin implements RfbPlugin { @Override public void onConstruction(@NotNull PluginContext ctx) { Launch.blackboard.put("angelica.rfbPluginLoaded", Boolean.TRUE); } @Override public @NotNull RfbClassTransformer @Nullable [] makeTransformers() { final boolean isServer = (null == RetroFuturaBootstrap.API.launchClassLoader().findClassMetadata("net.minecraft.client.main.Main")); if (isServer) { return null; } final boolean isObf = RetroFuturaBootstrap.API.launchClassLoader().findClassMetadata("net.minecraft.world.World") == null; return new RfbClassTransformer[] { new RFBAngelicaRedirector(), new RFBSodiumBlockTransformer(isObf) }; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\shared\AngelicaClassDump.java
package com.gtnewhorizons.angelica.loading.shared; import com.gtnewhorizon.gtnhlib.asm.ASMUtil; import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle; public class AngelicaClassDump { private static final boolean DUMP_CLASS = Boolean.getBoolean("angelica.dumpClass"); public static void dumpClass(String className, byte[] originalBytes, byte[] transformedBytes, Object transformer) { if (DUMP_CLASS) { ASMUtil.saveAsRawClassFile(originalBytes, className + "_PRE", transformer); ASMUtil.saveAsRawClassFile(transformedBytes, className + "_POST", transformer); } } public static void dumpRFBClass(String className, ClassNodeHandle classNode, Object transformer) { if (DUMP_CLASS) { final byte[] originalBytes = classNode.getOriginalBytes(); final byte[] transformedBytes = classNode.computeBytes(); ASMUtil.saveAsRawClassFile(originalBytes, className + "_PRE", transformer); ASMUtil.saveAsRawClassFile(transformedBytes, className + "_POST", transformer); } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\shared\package-info.java
/** * Package that contains classes that may be loaded both by RFB and FML classloaders, the code contained in this package * should not reference any code from outside of this package to avoid causing hard to debug classloading issues unless * the code is known to be safe with different classloaders. */ package com.gtnewhorizons.angelica.loading.shared;
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\CompatHandlers.java
package com.gtnewhorizons.angelica.loading.fml.compat; import com.gtnewhorizons.angelica.config.CompatConfig; import com.gtnewhorizons.angelica.loading.fml.compat.handlers.ExtraUtilsCompatHandler; import com.gtnewhorizons.angelica.loading.fml.compat.handlers.ImmersiveEngineeringCompatHandler; import com.gtnewhorizons.angelica.loading.fml.compat.handlers.StacksOnStacksCompatHandler; import com.gtnewhorizons.angelica.loading.fml.compat.handlers.ThaumcraftCompatHandler; import com.gtnewhorizons.angelica.loading.fml.compat.handlers.ThaumicHorizonsCompatHandler; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Supplier; public enum CompatHandlers { STACKS_ON_STACKS(() -> CompatConfig.fixStacksOnStacks, new StacksOnStacksCompatHandler()), EXTRA_UTILS(() -> CompatConfig.fixExtraUtils, new ExtraUtilsCompatHandler()), IMMERSIVE_ENGINEERING(() -> CompatConfig.fixImmersiveEngineering, new ImmersiveEngineeringCompatHandler()), THAUMCRAFT(() -> CompatConfig.fixThaumcraft, new ThaumcraftCompatHandler()), THAUMIC_HORIZONS(() -> CompatConfig.fixThaumicHorizons, new ThaumicHorizonsCompatHandler()); private final Supplier<Boolean> applyIf; private final ICompatHandler handler; CompatHandlers(Supplier<Boolean> applyIf, ICompatHandler handler) { this.applyIf = applyIf; this.handler = handler; } private static List<ICompatHandler> compatHandlers = null; public static List<ICompatHandler> getHandlers() { if (compatHandlers != null) { return compatHandlers; } compatHandlers = new ArrayList<>(); for (CompatHandlers value : values()) { if (value.applyIf.get()) { compatHandlers.add(value.handler); } } return compatHandlers; } /** * Returns extra transformers as well as the main transformer. * Returns an empty list if no handlers registered. */ public static List<String> getTransformers() { final List<ICompatHandler> handlers = getHandlers(); if (handlers.isEmpty()) { return Collections.emptyList(); } List<String> transformers = new ArrayList<>(); for (ICompatHandler handler : handlers) { if (handler.extraTransformers() != null) { transformers.addAll(handler.extraTransformers()); } } transformers.add("com.gtnewhorizons.angelica.loading.fml.transformers.GenericCompatTransformer"); return transformers; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\ICompatHandler.java
package com.gtnewhorizons.angelica.loading.fml.compat; import java.util.List; import java.util.Map; public interface ICompatHandler { default Map<String, List<String>> getFieldLevelTessellator() { return null; } default Map<String, List<String>> getTileEntityNullGuard() { return null; } default Map<String, Boolean> getThreadSafeISBRHAnnotations() { return null; } default Map<String, List<String>> getHUDCachingEarlyReturn() { return null; } default List<String> extraTransformers() { return null; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\transformers\AngelicaRedirectorTransformer.java
package com.gtnewhorizons.angelica.loading.fml.transformers; import com.gtnewhorizons.angelica.loading.AngelicaTweaker; import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump; import com.gtnewhorizons.angelica.loading.shared.transformers.AngelicaRedirector; import net.minecraft.launchwrapper.IClassTransformer; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.ClassNode; /** IClassTransformer wrapper for {@link AngelicaRedirector} */ public class AngelicaRedirectorTransformer implements IClassTransformer { private final AngelicaRedirector inner; private final String[] exclusions; public AngelicaRedirectorTransformer() { inner = new AngelicaRedirector(); exclusions = inner.getTransformerExclusions(); } @Override public byte[] transform(final String className, String transformedName, byte[] basicClass) { if (basicClass == null) return null; // Ignore classes that are excluded from transformation - Doesn't fully work without the // TransformerExclusions due to some nested classes for (String exclusion : exclusions) { if (transformedName.startsWith(exclusion)) return basicClass; } if (!inner.shouldTransform(basicClass)) { return basicClass; } final ClassReader cr = new ClassReader(basicClass); final ClassNode cn = new ClassNode(); cr.accept(cn, 0); final boolean changed = inner.transformClassNode(transformedName, cn); if (changed) { final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cn.accept(cw); final byte[] bytes = cw.toByteArray(); AngelicaClassDump.dumpClass(transformedName, basicClass, bytes, this); return bytes; } return basicClass; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\transformers\GenericCompatTransformer.java
package com.gtnewhorizons.angelica.loading.fml.transformers; import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump; import com.gtnewhorizons.angelica.loading.fml.compat.ICompatHandler; import com.gtnewhorizons.angelica.loading.fml.compat.CompatHandlers; import com.gtnewhorizons.angelica.loading.fml.compat.transformers.generic.FieldLevelTessellatorTransformer; import com.gtnewhorizons.angelica.loading.fml.compat.transformers.generic.HUDCachingEarlyReturnTransformer; import com.gtnewhorizons.angelica.loading.fml.compat.transformers.generic.ThreadSafeISBRHAnnotationTransformer; import com.gtnewhorizons.angelica.loading.fml.compat.transformers.generic.TileEntityNullGuardTransformer; import it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import net.minecraft.launchwrapper.IClassTransformer; import org.spongepowered.asm.lib.ClassReader; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.transformers.MixinClassWriter; import java.util.List; import java.util.Map; import java.util.Set; public class GenericCompatTransformer implements IClassTransformer { private final Map<String, List<String>> fieldLevelTessellator = new Object2ObjectOpenHashMap<>(); private final Map<String, List<String>> tileEntityNullGuard = new Object2ObjectOpenHashMap<>(); private final Map<String, Boolean> threadSafeIBSRH = new Object2BooleanOpenHashMap<>(); private final Map<String, List<String>> hudCachingEarlyReturn = new Object2ObjectOpenHashMap<>(); private final Set<String> targetedClasses = new ObjectOpenHashSet<>(); public GenericCompatTransformer() { for (ICompatHandler handler : CompatHandlers.getHandlers()) { registerHandler(handler); } buildTargetClassSet(); } private void registerHandler(ICompatHandler handler) { if (handler.getFieldLevelTessellator() != null) { fieldLevelTessellator.putAll(handler.getFieldLevelTessellator()); } if (handler.getTileEntityNullGuard() != null) { tileEntityNullGuard.putAll(handler.getTileEntityNullGuard()); } if (handler.getThreadSafeISBRHAnnotations() != null) { threadSafeIBSRH.putAll(handler.getThreadSafeISBRHAnnotations()); } if (handler.getHUDCachingEarlyReturn() != null) { hudCachingEarlyReturn.putAll(handler.getHUDCachingEarlyReturn()); } } private void buildTargetClassSet() { targetedClasses.addAll(fieldLevelTessellator.keySet()); targetedClasses.addAll(tileEntityNullGuard.keySet()); targetedClasses.addAll(threadSafeIBSRH.keySet()); targetedClasses.addAll(hudCachingEarlyReturn.keySet()); } @Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (basicClass == null) return null; if (!targetedClasses.contains(transformedName)) return basicClass; ClassReader cr = new ClassReader(basicClass); ClassNode cn = new ClassNode(); cr.accept(cn, 0); if (fieldLevelTessellator.containsKey(transformedName)) { FieldLevelTessellatorTransformer.transform(cn, fieldLevelTessellator.get(transformedName)); } if (tileEntityNullGuard.containsKey(transformedName)) { TileEntityNullGuardTransformer.transform(cn, tileEntityNullGuard.get(transformedName)); } if (threadSafeIBSRH.containsKey(transformedName)) { ThreadSafeISBRHAnnotationTransformer.transform(cn, threadSafeIBSRH.get(transformedName)); } if (hudCachingEarlyReturn.containsKey(transformedName)) { HUDCachingEarlyReturnTransformer.transform(cn, hudCachingEarlyReturn.get(transformedName)); } MixinClassWriter cw = new MixinClassWriter(MixinClassWriter.COMPUTE_MAXS | MixinClassWriter.COMPUTE_FRAMES); cn.accept(cw); final byte[] bytes = cw.toByteArray(); AngelicaClassDump.dumpClass(transformedName, basicClass, bytes, this); return bytes; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\transformers\SodiumBlockTransformer.java
package com.gtnewhorizons.angelica.loading.fml.transformers; import com.gtnewhorizons.angelica.loading.AngelicaTweaker; import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump; import com.gtnewhorizons.angelica.loading.shared.transformers.AngelicaRedirector; import com.gtnewhorizons.angelica.loading.shared.transformers.SodiumBlockTransform; import net.minecraft.launchwrapper.IClassTransformer; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.ClassNode; public class SodiumBlockTransformer implements IClassTransformer { private final SodiumBlockTransform inner; private final String[] exclusions; public SodiumBlockTransformer() { this.inner = new SodiumBlockTransform(AngelicaTweaker.isObfEnv()); this.exclusions = inner.getTransformerExclusions(); this.inner.setSodiumSetting(); } /** * Delete the global vanilla bounding box fields off the Block object. {@link AngelicaRedirector} * replaces these with a thread-safe alternative. */ @Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (basicClass == null) return null; for (String exclusion : exclusions) { if (transformedName.startsWith(exclusion)) return basicClass; } if (!inner.shouldTransform(basicClass)) { return basicClass; } final ClassReader cr = new ClassReader(basicClass); final ClassNode cn = new ClassNode(); cr.accept(cn, 0); final boolean changed = inner.transformClassNode(transformedName, cn); if (changed) { final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cn.accept(cw); final byte[] bytes = cw.toByteArray(); AngelicaClassDump.dumpClass(transformedName, basicClass, bytes, this); return bytes; } return basicClass; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\tweakers\AngelicaLateTweaker.java
package com.gtnewhorizons.angelica.loading.fml.tweakers; import cpw.mods.fml.relauncher.FMLRelaunchLog; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader; import java.io.File; import java.util.List; public class AngelicaLateTweaker implements ITweaker { @Override public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) { // no-op } @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { // no-op } @Override public String getLaunchTarget() { return null; } @Override public String[] getLaunchArguments() { // Run after Mixins, but before LWJGl3ify String transformer = "com.gtnewhorizons.angelica.loading.fml.transformers.AngelicaRedirectorTransformer"; FMLRelaunchLog.finer("Registering transformer %s", transformer); Launch.classLoader.registerTransformer(transformer); return new String[0]; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\tweakers\IncompatibleModsDisablerTweaker.java
package com.gtnewhorizons.angelica.loading.fml.tweakers; import cpw.mods.fml.relauncher.CoreModManager; import cpw.mods.fml.relauncher.FMLRelaunchLog; import net.minecraft.launchwrapper.IClassTransformer; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader; import org.spongepowered.asm.launch.platform.MixinContainer; import org.spongepowered.asm.launch.platform.MixinPlatformManager; import org.spongepowered.asm.launch.platform.container.IContainerHandle; import org.spongepowered.asm.mixin.transformer.Config; import java.io.File; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class IncompatibleModsDisablerTweaker implements ITweaker { private static final boolean DISABLE_OPTIFINE_FASTCRAFT_BETTERFPS = true; @Override public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) { // no-op } @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { if (DISABLE_OPTIFINE_FASTCRAFT_BETTERFPS) { FMLRelaunchLog.info("[Angelica/IncompatibleModsDisablerTweaker] Disabling Optifine, Fastcraft, BetterFPS, and other incompatible mods (if present)"); disableIncompatibleMods(classLoader); } } @Override public String getLaunchTarget() { return null; } @Override public String[] getLaunchArguments() { return new String[0]; } @SuppressWarnings("unchecked") private void disableIncompatibleMods(LaunchClassLoader lcl) { // Remove transformers, Mod Containers, and mixins for Optifine, Fastcraft, BetterFPS and other incompatible mods try { final Field xformersField = lcl.getClass().getDeclaredField("transformers"); xformersField.setAccessible(true); final List<IClassTransformer> xformers = (List<IClassTransformer>) xformersField.get(lcl); for (int idx = xformers.size() - 1; idx >= 0; idx--) { final String name = xformers.get(idx).getClass().getName(); if (name.startsWith("optifine") || name.startsWith("fastcraft") || name.startsWith("me.guichaguri.betterfps")) { FMLRelaunchLog.info("[Angelica/IncompatibleModsDisablerTweaker] Removing transformer " + name); xformers.remove(idx); } } } catch (Exception e) { throw new RuntimeException(e); } try { final Class<?> loaderClass = Class.forName("cpw.mods.fml.common.Loader", true, lcl); final Field injectedContainersField = loaderClass.getDeclaredField("injectedContainers"); injectedContainersField.setAccessible(true); final List<String> containers = (List<String>) injectedContainersField.get(loaderClass); for (int idx = containers.size() - 1; idx >= 0; idx--) { final String name = containers.get(idx); if (name.startsWith("optifine") || name.startsWith("fastcraft")) { FMLRelaunchLog.info("[Angelica/IncompatibleModsDisablerTweaker] Removing mod container " + name); containers.remove(idx); } } final Field reparsedCoremodsField = CoreModManager.class.getDeclaredField("reparsedCoremods"); final Field loadedCoremodsField = CoreModManager.class.getDeclaredField("loadedCoremods"); reparsedCoremodsField.setAccessible(true); loadedCoremodsField.setAccessible(true); final ArrayList<String> reparsedCoremods = (ArrayList<String>) reparsedCoremodsField.get(CoreModManager.class); final ArrayList<String> loadedCoremods = (ArrayList<String>) loadedCoremodsField.get(CoreModManager.class); for (int idx = reparsedCoremods.size() - 1; idx >= 0; idx--) { final String coreMod = reparsedCoremods.get(idx); if (coreMod.startsWith("optimizationsandtweaks")) { FMLRelaunchLog.info("[Angelica/IncompatibleModsDisablerTweaker] Removing reparsed coremod " + coreMod); // Fool the CoreModManager into not checking for a mod container again later loadedCoremods.add(reparsedCoremods.remove(idx)); } } } catch (Exception e) { throw new RuntimeException(e); } try { final ArrayList<String> mixinConfigsDefault = (ArrayList<String>) Launch.blackboard.get("mixin.configs.default"); if (mixinConfigsDefault != null) { for (int idx = mixinConfigsDefault.size() - 1; idx >= 0; idx--) { final String name = mixinConfigsDefault.get(idx); if (name != null && name.contains("optimizationsandtweaks")) { FMLRelaunchLog.info("[Angelica/IncompatibleModsDisablerTweaker] Removing mixin config " + name); mixinConfigsDefault.remove(idx); } } } final Set<Config> mixinConfigs = (Set<Config>) Launch.blackboard.get("mixin.configs.queue"); final Set<Config> toRemove = new HashSet<>(); if (mixinConfigs != null) { for (Config config : mixinConfigs) { final String name = config.getName(); if (name != null && name.contains("optimizationsandtweaks")) { FMLRelaunchLog.info("[Angelica/IncompatibleModsDisablerTweaker] Removing queued mixin config " + config.getName()); toRemove.add(config); } } mixinConfigs.removeAll(toRemove); } final MixinPlatformManager platformManager = (MixinPlatformManager) Launch.blackboard.get("mixin.platform"); if (platformManager != null) { final Field containersField = platformManager.getClass().getDeclaredField("containers"); containersField.setAccessible(true); final Map<IContainerHandle, MixinContainer> containers = (Map<IContainerHandle, MixinContainer>) containersField.get(platformManager); for (Map.Entry<IContainerHandle, MixinContainer> entry : containers.entrySet()) { final String attribute = entry.getKey().getAttribute("MixinConfigs"); if (attribute != null && attribute.contains("optimizationsandtweaks")) { FMLRelaunchLog.info("[Angelica/IncompatibleModsDisablerTweaker] Removing mixin container " + entry.getKey().toString()); containers.remove(entry.getKey()); } } } } catch (Exception e) { throw new RuntimeException(e); } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\tweakers\package-info.java
/** * ITweaker needs to be in a standalone package * because FML adds the whole package to the class * loader exclusions and that causes really hard to * find bugs. ITweakers also get class loaded * by the parent class loader and not LaunchClassLoader, * as a result the ITweakers should not reference any * class otherwise it will load them (maybe a second time) * on the parent class loader. */ package com.gtnewhorizons.angelica.loading.fml.tweakers;
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\tweakers\SodiumLateTweaker.java
package com.gtnewhorizons.angelica.loading.fml.tweakers; import cpw.mods.fml.relauncher.FMLRelaunchLog; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader; import java.io.File; import java.util.List; public class SodiumLateTweaker implements ITweaker { @Override public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) { // no-op } @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { // no-op } @Override public String getLaunchTarget() { return null; } @Override public String[] getLaunchArguments() { String transformer = "com.gtnewhorizons.angelica.loading.fml.transformers.SodiumBlockTransformer"; FMLRelaunchLog.finer("Registering transformer %s", transformer); Launch.classLoader.registerTransformer(transformer); return new String[0]; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\tweakers\XaerosTransformerDisablerTweaker.java
package com.gtnewhorizons.angelica.loading.fml.tweakers; import cpw.mods.fml.relauncher.FMLRelaunchLog; import net.minecraft.launchwrapper.IClassTransformer; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.LaunchClassLoader; import java.io.File; import java.lang.reflect.Field; import java.util.List; public class XaerosTransformerDisablerTweaker implements ITweaker { @Override public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) { // no-op } @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { try { final Field xformersField = classLoader.getClass().getDeclaredField("transformers"); xformersField.setAccessible(true); @SuppressWarnings("unchecked") List<IClassTransformer> transformers = (List<IClassTransformer>) xformersField.get(classLoader); for (int idx = transformers.size() - 1; idx >= 0; idx--) { final String name = transformers.get(idx).getClass().getName(); if (name.startsWith("xaero.common.core.transformer.GuiIngameForgeTransformer")) { transformers.remove(idx); FMLRelaunchLog.info("[Angelica/XaerosTransformerDisablerTweaker] Removed transformer " + name); } } } catch (Exception e) { throw new RuntimeException(e); } } @Override public String getLaunchTarget() { return null; } @Override public String[] getLaunchArguments() { return new String[0]; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\handlers\ExtraUtilsCompatHandler.java
package com.gtnewhorizons.angelica.loading.fml.compat.handlers; import com.google.common.collect.ImmutableMap; import com.gtnewhorizons.angelica.loading.fml.compat.ICompatHandler; import java.util.Map; public class ExtraUtilsCompatHandler implements ICompatHandler { @Override public Map<String, Boolean> getThreadSafeISBRHAnnotations() { return ImmutableMap.of( "com.rwtema.extrautils.block.render.RenderBlockColor", false, "com.rwtema.extrautils.block.render.RenderBlockConnectedTextures", true, "com.rwtema.extrautils.block.render.RenderBlockConnectedTexturesEthereal", true, "com.rwtema.extrautils.block.render.RenderBlockFullBright", false, "com.rwtema.extrautils.block.render.RenderBlockSpike", false); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\handlers\ImmersiveEngineeringCompatHandler.java
package com.gtnewhorizons.angelica.loading.fml.compat.handlers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.gtnewhorizons.angelica.loading.fml.compat.ICompatHandler; import java.util.List; import java.util.Map; public class ImmersiveEngineeringCompatHandler implements ICompatHandler { @Override public Map<String, List<String>> getTileEntityNullGuard() { final List<String> renderWorldBlockExclusive = ImmutableList.of("renderWorldBlock"); return ImmutableMap.<String, List<String>>builder() .put("blusunrize.immersiveengineering.client.render.BlockRenderClothDevices", renderWorldBlockExclusive) .put("blusunrize.immersiveengineering.client.render.BlockRenderMetalDecoration", renderWorldBlockExclusive) .put("blusunrize.immersiveengineering.client.render.BlockRenderMetalDevices", renderWorldBlockExclusive) .put("blusunrize.immersiveengineering.client.render.BlockRenderMetalDevices2", renderWorldBlockExclusive) .put("blusunrize.immersiveengineering.client.render.BlockRenderWoodenDecoration", renderWorldBlockExclusive) .put("blusunrize.immersiveengineering.client.render.BlockRenderWoodenDevices", renderWorldBlockExclusive) .build(); } @Override public Map<String, Boolean> getThreadSafeISBRHAnnotations() { return ImmutableMap.<String, Boolean>builder() .put("blusunrize.immersiveengineering.client.render.BlockRenderClothDevices", false) .put("blusunrize.immersiveengineering.client.render.BlockRenderMetalDecoration", false) .put("blusunrize.immersiveengineering.client.render.BlockRenderMetalDevices", false) .put("blusunrize.immersiveengineering.client.render.BlockRenderMetalDevices2", false) .put("blusunrize.immersiveengineering.client.render.BlockRenderMetalMultiblocks", false) .put("blusunrize.immersiveengineering.client.render.BlockRenderStoneDevices", false) .put("blusunrize.immersiveengineering.client.render.BlockRenderWoodenDecoration", false) .put("blusunrize.immersiveengineering.client.render.BlockRenderWoodenDevices", false) .build(); } @Override public List<String> extraTransformers() { return ImmutableList.of("com.gtnewhorizons.angelica.loading.fml.compat.transformers.specific.ImmersiveEngineeringTransformer"); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\handlers\StacksOnStacksCompatHandler.java
package com.gtnewhorizons.angelica.loading.fml.compat.handlers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.gtnewhorizons.angelica.loading.fml.compat.ICompatHandler; import java.util.List; import java.util.Map; public class StacksOnStacksCompatHandler implements ICompatHandler { @Override public Map<String, List<String>> getFieldLevelTessellator() { return ImmutableMap .of("com.tierzero.stacksonstacks.util.ClientUtils", ImmutableList.of("drawQuad", "drawRectangularPrism")); } @Override public Map<String, List<String>> getTileEntityNullGuard() { return ImmutableMap .of("com.tierzero.stacksonstacks.client.render.RenderTilePile", ImmutableList.of("renderWorldBlock")); } @Override public Map<String, Boolean> getThreadSafeISBRHAnnotations() { return ImmutableMap.of("com.tierzero.stacksonstacks.client.render.RenderTilePile", true); } @Override public List<String> extraTransformers() { return ImmutableList.of("com.gtnewhorizons.angelica.loading.fml.compat.transformers.specific.StacksOnStacksTransformer"); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\handlers\ThaumcraftCompatHandler.java
package com.gtnewhorizons.angelica.loading.fml.compat.handlers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.gtnewhorizons.angelica.loading.fml.compat.ICompatHandler; import java.util.List; import java.util.Map; public class ThaumcraftCompatHandler implements ICompatHandler { @Override public Map<String, List<String>> getHUDCachingEarlyReturn() { return ImmutableMap.of("thaumcraft.client.lib.RenderEventHandler", ImmutableList.of("renderOverlay")); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\handlers\ThaumicHorizonsCompatHandler.java
package com.gtnewhorizons.angelica.loading.fml.compat.handlers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.gtnewhorizons.angelica.loading.fml.compat.ICompatHandler; import java.util.List; import java.util.Map; public class ThaumicHorizonsCompatHandler implements ICompatHandler { @Override public Map<String, List<String>> getHUDCachingEarlyReturn() { return ImmutableMap .of("com.kentington.thaumichorizons.client.lib.RenderEventHandler", ImmutableList.of("renderOverlay")); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\transformers\generic\FieldLevelTessellatorTransformer.java
package com.gtnewhorizons.angelica.loading.fml.compat.transformers.generic; import com.gtnewhorizons.angelica.loading.AngelicaTweaker; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.FieldInsnNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.LabelNode; import org.spongepowered.asm.lib.tree.LocalVariableNode; import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.lib.tree.VarInsnNode; import java.util.ArrayList; import java.util.List; public class FieldLevelTessellatorTransformer { public static void transform(ClassNode cn, List<String> patchMethods) { for (MethodNode method : cn.methods) { if (patchMethods.contains(method.name)) { injectLocalTessellatorAndReplaceFieldUsage(method); } } } private static void injectLocalTessellatorAndReplaceFieldUsage(MethodNode mn) { // This part searches the instructions to see if there is any usage of a Tessellator field // which is NOT owned by Minecraft itself. This means anyone that caches it into a field will get caught // but not direct usage of Tessellator.instance.whatever() List<String> fields = new ArrayList<>(); for (int i = 0; i < mn.instructions.size(); i++) { AbstractInsnNode in = mn.instructions.get(i); if (in instanceof FieldInsnNode fin) { if ((fin.getOpcode() == Opcodes.GETSTATIC || fin.getOpcode() == Opcodes.GETFIELD) && fin.desc.equals("Lnet/minecraft/client/renderer/Tessellator;") && !fin.owner.equals("net/minecraft/client/renderer/Tessellator")) { fields.add(fin.owner + ";" + fin.name); } } } if (fields.isEmpty()) return; // Injects a new local to store our new local Tessellator in int localIndex = mn.maxLocals; LabelNode startLabel = new LabelNode(); LabelNode endLabel = new LabelNode(); LocalVariableNode tesNode = new LocalVariableNode( "tes", "Lnet/minecraft/client/renderer/Tessellator;", null, startLabel, endLabel, localIndex); mn.localVariables.add(tesNode); // Actually initialize the new local Tessellator InsnList list = new InsnList(); list.add(startLabel); list.add( new FieldInsnNode( Opcodes.GETSTATIC, "net/minecraft/client/renderer/Tessellator", AngelicaTweaker.obf("instance", "field_78398_a"), "Lnet/minecraft/client/renderer/Tessellator;")); list.add(new VarInsnNode(Opcodes.ASTORE, localIndex)); mn.instructions.insert(list); // This searches through all the instructions and finds usage of the previously discovered fields, then it // replaces them // with an ALOAD for our new local instead of the GETSTATIC/GETFIELD for (int i = 0; i < mn.instructions.size(); i++) { AbstractInsnNode in = mn.instructions.get(i); if (in instanceof FieldInsnNode fin) { String hash = fin.owner + ";" + fin.name; if ((fin.getOpcode() == Opcodes.GETSTATIC || fin.getOpcode() == Opcodes.GETFIELD) && fin.desc.equals("Lnet/minecraft/client/renderer/Tessellator;") && fields.contains(hash)) { mn.instructions.insertBefore(in, new VarInsnNode(Opcodes.ALOAD, localIndex)); mn.instructions.remove(in); } } } mn.instructions.add(endLabel); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\transformers\generic\HUDCachingEarlyReturnTransformer.java
package com.gtnewhorizons.angelica.loading.fml.compat.transformers.generic; import com.gtnewhorizons.angelica.loading.AngelicaTweaker; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.InsnNode; import org.spongepowered.asm.lib.tree.JumpInsnNode; import org.spongepowered.asm.lib.tree.LabelNode; import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.lib.tree.MethodNode; import java.util.List; public class HUDCachingEarlyReturnTransformer { private static final String HUDCaching = "com/gtnewhorizons/angelica/hudcaching/HUDCaching$HUDCachingHooks"; public static void transform(ClassNode cn, List<String> patchMethods) { for (MethodNode method : cn.methods) { if (patchMethods.contains(method.name)) { InsnList list = new InsnList(); LabelNode exitLabel = new LabelNode(); list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, HUDCaching, "shouldReturnEarly", "()Z", false)); list.add(new JumpInsnNode(Opcodes.IFEQ, exitLabel)); if (method.desc.endsWith("Z") || method.desc.endsWith("I")) { list.add(new InsnNode(Opcodes.ICONST_0)); list.add(new InsnNode(Opcodes.IRETURN)); } else if (method.desc.endsWith("V")) { list.add(new InsnNode(Opcodes.RETURN)); } else { AngelicaTweaker.LOGGER.warn( "HUDCaching Conditional Return - Unknown return type: {}#{}:{}", cn.name, method.name, method.desc ); return; } list.add(exitLabel); method.instructions.insert(list); } } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\transformers\generic\ThreadSafeISBRHAnnotationTransformer.java
package com.gtnewhorizons.angelica.loading.fml.compat.transformers.generic; import org.spongepowered.asm.lib.tree.AnnotationNode; import org.spongepowered.asm.lib.tree.ClassNode; import java.util.ArrayList; import java.util.Arrays; public class ThreadSafeISBRHAnnotationTransformer { public static void transform(ClassNode cn, boolean perThread) { if (cn.visibleAnnotations == null) { cn.visibleAnnotations = new ArrayList<>(); } AnnotationNode isbrhAnnotation = new AnnotationNode("Lcom/gtnewhorizons/angelica/api/ThreadSafeISBRH;"); isbrhAnnotation.values = Arrays.asList("perThread", perThread); cn.visibleAnnotations.add(isbrhAnnotation); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\transformers\generic\TileEntityNullGuardTransformer.java
package com.gtnewhorizons.angelica.loading.fml.compat.transformers.generic; import com.gtnewhorizons.angelica.loading.AngelicaTweaker; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.InsnNode; import org.spongepowered.asm.lib.tree.JumpInsnNode; import org.spongepowered.asm.lib.tree.LabelNode; import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.lib.tree.TypeInsnNode; import org.spongepowered.asm.lib.tree.VarInsnNode; import java.util.List; public class TileEntityNullGuardTransformer { public static void transform(ClassNode cn, List<String> patchMethods) { for (MethodNode method : cn.methods) { if (patchMethods.contains(method.name)) { injectGetTileEntityNullGuard(method); } } } public static void injectGetTileEntityNullGuard(MethodNode mn) { /* * Searching for the following pattern: * L0 { * ... * INVOKEINTERFACE net/minecraft/world/IBlockAccess.getTileEntity(III)Lnet/minecraft/tileentity/TileEntity; * CHECKCAST * * ASTORE x * } * L1 {... * Then injecting the following after the ASTORE such that we get * L0 { * ASTORE x * ALOAD x * IFNONNULL L1 * ICONST_0 * IRETURN * } * L1 {... * Ultimately this converts: * MyTileEntity tile = (MyTileEntity) world.getTileEntity(x, y, z); * doSomethingWithTileEntity(tile); * into: * MyTileEntity tile = (MyTileEntity) world.getTileEntity(x, y, z); * if (tile == null) { * return false; * } else { * doSomethingWithTileEntity(tile); * } */ for (int i = 0; i < mn.instructions.size(); i++) { AbstractInsnNode in = mn.instructions.get(i); if (in instanceof MethodInsnNode min) { if (min.getOpcode() == Opcodes.INVOKEINTERFACE && min.name.equals(AngelicaTweaker.obf("getTileEntity", "func_147438_o")) && min.owner.equals("net/minecraft/world/IBlockAccess")) { AbstractInsnNode castNodeAbstract = min.getNext(); if (castNodeAbstract instanceof TypeInsnNode castNodeType) { if (castNodeType.getOpcode() == Opcodes.CHECKCAST) { AbstractInsnNode astoreNodeAbstract = castNodeType.getNext(); if (astoreNodeAbstract instanceof VarInsnNode astoreNodeVar) { if (astoreNodeVar.getOpcode() == Opcodes.ASTORE) { InsnList list = new InsnList(); LabelNode exit = new LabelNode(); list.add(new VarInsnNode(Opcodes.ALOAD, astoreNodeVar.var)); list.add(new JumpInsnNode(Opcodes.IFNONNULL, exit)); if (mn.desc.endsWith("Z") || mn.desc.endsWith("I")) { list.add(new InsnNode(Opcodes.ICONST_0)); list.add(new InsnNode(Opcodes.IRETURN)); } else if (mn.desc.endsWith("V")) { list.add(new InsnNode(Opcodes.RETURN)); } else { AngelicaTweaker.LOGGER.warn("TileEntityNullGuard - Unknown Return Type: {}:{}", mn.name, mn.desc); return; } list.add(exit); mn.instructions.insert(astoreNodeVar, list); } } } } } } } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\transformers\specific\ImmersiveEngineeringTransformer.java
package com.gtnewhorizons.angelica.loading.fml.compat.transformers.specific; import com.gtnewhorizons.angelica.loading.AngelicaTweaker; import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump; import net.minecraft.launchwrapper.IClassTransformer; import org.spongepowered.asm.lib.ClassReader; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.FieldInsnNode; import org.spongepowered.asm.lib.tree.InsnNode; import org.spongepowered.asm.lib.tree.JumpInsnNode; import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.transformers.MixinClassWriter; import java.util.ArrayList; import java.util.List; public class ImmersiveEngineeringTransformer implements IClassTransformer { private static final String BlockRenderClothDevices = "blusunrize.immersiveengineering.client.render.BlockRenderClothDevices"; private static final String BlockRenderMetalDevices2 = "blusunrize.immersiveengineering.client.render.BlockRenderMetalDevices2"; private static final String BlockRenderStoneDevices = "blusunrize.immersiveengineering.client.render.BlockRenderStoneDevices"; private static final String ClientUtils = "blusunrize.immersiveengineering.client.ClientUtils"; private static final List<String> transformedClasses = new ArrayList<>(); private static final List<String> staticRenderPassPatches = new ArrayList<>(); static { transformedClasses.add(BlockRenderClothDevices); transformedClasses.add(BlockRenderMetalDevices2); transformedClasses.add(BlockRenderStoneDevices); transformedClasses.add(ClientUtils); staticRenderPassPatches.add(BlockRenderClothDevices); staticRenderPassPatches.add(BlockRenderMetalDevices2); staticRenderPassPatches.add(BlockRenderStoneDevices); } @Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (basicClass == null) return null; if (!transformedClasses.contains(transformedName)) return basicClass; final ClassReader cr = new ClassReader(basicClass); final ClassNode cn = new ClassNode(); cr.accept(cn, 0); if (transformedName.equals(ClientUtils)) { transformClientUtils(cn); } if (staticRenderPassPatches.contains(transformedName)) { staticRenderPassPatcher(cn); } MixinClassWriter cw = new MixinClassWriter(MixinClassWriter.COMPUTE_FRAMES); cn.accept(cw); final byte[] bytes = cw.toByteArray(); AngelicaTweaker.LOGGER.info("[AngelicaCompat]Extra Transformers: Applied ImmersiveEngineeringTransformer"); AngelicaClassDump.dumpClass(transformedName, basicClass, bytes, this); return bytes; } private void staticRenderPassPatcher(ClassNode cn) { for (MethodNode mn : cn.methods) { if (mn.name.equals("renderWorldBlock")) { for (int i = 0; i < mn.instructions.size(); i++) { AbstractInsnNode ain = mn.instructions.get(i); // So far every one of these has been named renderPass, eventually might need to make the name dynamic and possibly care about owner? // Maybe this is common in other mods, possibly could generalize this transformation further if it comes up more. if (ain instanceof FieldInsnNode fin && fin.getOpcode() == Opcodes.GETSTATIC && fin.name.equals("renderPass")) { MethodInsnNode getRenderPass = new MethodInsnNode(Opcodes.INVOKESTATIC, "net/minecraftforge/client/ForgeHooksClient", "getWorldRenderPass", "()I"); mn.instructions.insert(fin, getRenderPass); mn.instructions.remove(fin); } } } } } private void transformClientUtils(ClassNode cn) { for (MethodNode mn : cn.methods) { // This patches an if (world != null) check to just be if (false) in order to make the block of code not run // The block of code in question calls OpenGL to update the lightmap texture coordinates, which is illegal from an ISBRH // in Angelica. It doesn't seem to make anything not work by causing this to not happen. if (mn.name.equals("renderStaticWavefrontModelWithIcon") || mn.name.equals("renderStaticWavefrontModel")) { if ( mn.desc.equals("(Lnet/minecraft/world/IBlockAccess;IIILnet/minecraftforge/client/model/obj/WavefrontObject;Lnet/minecraft/util/IIcon;Lnet/minecraft/client/renderer/Tessellator;Lblusunrize/immersiveengineering/common/util/chickenbones/Matrix4;Lblusunrize/immersiveengineering/common/util/chickenbones/Matrix4;IZFFF[Ljava/lang/String;)V") || mn.desc.equals("(Lnet/minecraft/world/IBlockAccess;IIILnet/minecraftforge/client/model/obj/WavefrontObject;Lnet/minecraft/client/renderer/Tessellator;Lblusunrize/immersiveengineering/common/util/chickenbones/Matrix4;Lblusunrize/immersiveengineering/common/util/chickenbones/Matrix4;IZFFF[Ljava/lang/String;)V") ) { for (int i = 0; i < mn.instructions.size(); i++) { AbstractInsnNode ain = mn.instructions.get(i); if (ain instanceof JumpInsnNode jump && jump.getOpcode() == Opcodes.IFNULL) { InsnNode iconst = new InsnNode(Opcodes.ICONST_0); jump.setOpcode(Opcodes.IFEQ); mn.instructions.insertBefore(jump, iconst); break; } } } } } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\fml\compat\transformers\specific\StacksOnStacksTransformer.java
package com.gtnewhorizons.angelica.loading.fml.compat.transformers.specific; import com.google.common.collect.ImmutableList; import com.gtnewhorizons.angelica.loading.AngelicaTweaker; import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump; import net.minecraft.launchwrapper.IClassTransformer; import org.spongepowered.asm.lib.ClassReader; import org.spongepowered.asm.lib.ClassWriter; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.FieldInsnNode; import org.spongepowered.asm.lib.tree.FieldNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.InsnNode; import org.spongepowered.asm.lib.tree.LabelNode; import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.lib.tree.TypeInsnNode; import org.spongepowered.asm.lib.tree.VarInsnNode; import java.util.List; public class StacksOnStacksTransformer implements IClassTransformer { private static final String RenderTilePile = "com.tierzero.stacksonstacks.client.render.RenderTilePile"; private static final List<String> staticRemovers = ImmutableList.of("ingotRender", "gemRender", "dustRender"); private static final String ClientUtils = "com.tierzero.stacksonstacks.util.ClientUtils"; @Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (basicClass == null) return null; if (!transformedName.equals(RenderTilePile) && !transformedName.equals(ClientUtils)) return basicClass; final ClassReader cr = new ClassReader(basicClass); final ClassNode cn = new ClassNode(); cr.accept(cn, 0); if (transformedName.equals(RenderTilePile)) { transformRenderTilePile(cn); } else { transformClientUtils(cn); } ClassWriter cw = new ClassWriter(0); cn.accept(cw); final byte[] bytes = cw.toByteArray(); AngelicaTweaker.LOGGER.info("[AngelicaCompat]Extra Transformers: Applied StacksOnStacksTransformer"); AngelicaClassDump.dumpClass(transformedName, basicClass, bytes, this); return bytes; } /** * Injects initializers for the field level PileRender objects which used to be static into the <init> */ private static InsnList buildPilerRenderInitializer(String type) { LabelNode start = new LabelNode(); LabelNode end = new LabelNode(); InsnList list = new InsnList(); list.add(start); list.add(new VarInsnNode(Opcodes.ALOAD, 0)); list.add(new TypeInsnNode(Opcodes.NEW, "com/tierzero/stacksonstacks/client/render/PileRender" + type)); list.add(new InsnNode(Opcodes.DUP)); list.add( new MethodInsnNode( Opcodes.INVOKESPECIAL, "com/tierzero/stacksonstacks/client/render/PileRender" + type, "<init>", "()V")); list.add( new FieldInsnNode( Opcodes.PUTFIELD, "com/tierzero/stacksonstacks/client/render/RenderTilePile", type.toLowerCase() + "Render", "Lcom/tierzero/stacksonstacks/client/render/PileRender;")); list.add(end); return list; } private static void transformRenderTilePile(ClassNode cn) { MethodNode clinit = null; for (MethodNode mn : cn.methods) { // Handles injecting field initializers for the various PileRender fields which used to be static // but we're removing <clinit> entirely and doing the initialization in <init> if (mn.name.equals("<init>")) { AbstractInsnNode objectInsn = null; // This removes the early return, and gets a reference to the self initialization so we can insert after for (int i = 0; i < mn.instructions.size(); i++) { AbstractInsnNode ain = mn.instructions.get(i); if (ain.getOpcode() == Opcodes.RETURN) mn.instructions.remove(ain); if (ain.getOpcode() == Opcodes.INVOKESPECIAL) objectInsn = mn.instructions.get(i); } // Build the initializer InsnLists and then insert them in reverse order, such that the dustRender comes // last // because we are adding the return opcode back in as part of that one's InsnList InsnList ingotRender = buildPilerRenderInitializer("Ingot"); InsnList gemRender = buildPilerRenderInitializer("Gem"); InsnList dustRender = buildPilerRenderInitializer("Dust"); dustRender.add(new InsnNode(Opcodes.RETURN)); mn.instructions.insert(objectInsn, dustRender); mn.instructions.insert(objectInsn, gemRender); mn.instructions.insert(objectInsn, ingotRender); } // Just catching the MethodNode for <clinit> so we can remove it later after we're done iterating if (mn.name.equals("<clinit>")) { clinit = mn; } if (mn.name.equals("renderWorldBlock")) { for (int i = 0; i < mn.instructions.size(); i++) { AbstractInsnNode in = mn.instructions.get(i); // This part removes the GETSTATIC for the field level PileRender objects which used to be static, // and replaces them with // a non-static GETFIELD if (in instanceof FieldInsnNode fin) { if (fin.getOpcode() == Opcodes.GETSTATIC && staticRemovers.contains(fin.name)) { FieldInsnNode nonStatic = new FieldInsnNode( Opcodes.GETFIELD, "com/tierzero/stacksonstacks/client/render/RenderTilePile", fin.name, "Lcom/tierzero/stacksonstacks/client/render/PileRender;"); mn.instructions.insertBefore(fin, new VarInsnNode(Opcodes.ALOAD, 0)); mn.instructions.insertBefore(fin, nonStatic); mn.instructions.remove(fin); } } } } } // Remove clinit after iterating. Nothing else happens in here besides the field initialization, so no reason to // drill down // into the instructions if (clinit != null) cn.methods.remove(clinit); // Remove the static access bits from the desired field names for (FieldNode fn : cn.fields) { if (staticRemovers.contains(fn.name)) { fn.access = fn.access & (~Opcodes.ACC_STATIC); } } } private static void transformClientUtils(ClassNode cn) { // Various things throughout the ISBRH call these functions which in turn call GL11.glPush/PopMatrix // Upon checking, these aren't called anywhere but in the ISBRH, and they're entirely unnecessary in there. // This just makes the methods no-op, since they aren't required by any other part of the mod to be working. for (MethodNode mn : cn.methods) { if (mn.name.equals("pushMatrix")) { for (int i = 0; i < mn.instructions.size(); i++) { AbstractInsnNode in = mn.instructions.get(i); if (in.getOpcode() == Opcodes.INVOKESTATIC) { mn.instructions.remove(in); } } } else if (mn.name.equals("popMatrix")) { for (int i = 0; i < mn.instructions.size(); i++) { AbstractInsnNode in = mn.instructions.get(i); if (in.getOpcode() == Opcodes.INVOKESTATIC) { mn.instructions.remove(in); } } } } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\rfb\transformers\RFBAngelicaRedirector.java
package com.gtnewhorizons.angelica.loading.rfb.transformers; import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump; import com.gtnewhorizons.angelica.loading.shared.transformers.AngelicaRedirector; import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle; import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader; import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer; import org.intellij.lang.annotations.Pattern; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.jar.Manifest; /** RfbClassTransformer wrapper for {@link AngelicaRedirector} */ public class RFBAngelicaRedirector implements RfbClassTransformer { private final AngelicaRedirector inner; public RFBAngelicaRedirector() { inner = new AngelicaRedirector(); } @Pattern("[a-z0-9-]+") @Override public @NotNull String id() { return "redirector"; } @Override public @NotNull String @Nullable [] sortAfter() { return new String[] {"*", "mixin:mixin"}; } @Override public @NotNull String @Nullable [] sortBefore() { return new String[] {"lwjgl3ify:redirect"}; } @Override public @NotNull String @Nullable [] additionalExclusions() { return inner.getTransformerExclusions(); } @Override public boolean shouldTransformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { if (!classNode.isPresent()) { return false; } if (!classNode.isOriginal()) { // If a class is already a transformed ClassNode, conservatively continue processing. return true; } return inner.shouldTransform(classNode.getOriginalBytes()); } @Override public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { final boolean changed = inner.transformClassNode(className, classNode.getNode()); if (changed) { classNode.computeMaxs(); AngelicaClassDump.dumpRFBClass(className, classNode, this); } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\rfb\transformers\RFBSodiumBlockTransformer.java
package com.gtnewhorizons.angelica.loading.rfb.transformers; import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump; import com.gtnewhorizons.angelica.loading.shared.transformers.SodiumBlockTransform; import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle; import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader; import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer; import org.intellij.lang.annotations.Pattern; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.jar.Manifest; public class RFBSodiumBlockTransformer implements RfbClassTransformer { private final SodiumBlockTransform inner; public RFBSodiumBlockTransformer(boolean isObf) { inner = new SodiumBlockTransform(isObf); } @Pattern("[a-z0-9-]+") @Override public @NotNull String id() { return "sodiumblocktransform"; } @Override public @NotNull String @Nullable [] sortAfter() { return new String[]{"*", "mixin:mixin"}; } @Override public @NotNull String @Nullable [] sortBefore() { return new String[]{"lwjgl3ify:redirect"}; } @Override public @NotNull String @Nullable [] additionalExclusions() { return inner.getTransformerExclusions(); } @Override public boolean shouldTransformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { if (!classNode.isPresent()) { return false; } if (!classNode.isOriginal()) { // If a class is already a transformed ClassNode, conservatively continue processing. return true; } return inner.shouldTransform(classNode.getOriginalBytes()); } @Override public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { final boolean changed = inner.transformClassNode(className, classNode.getNode()); if (changed) { classNode.computeMaxs(); AngelicaClassDump.dumpRFBClass(className, classNode, this); } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\shared\transformers\AngelicaRedirector.java
package com.gtnewhorizons.angelica.loading.shared.transformers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.gtnewhorizon.gtnhlib.asm.ClassConstantPoolParser; import net.minecraft.launchwrapper.Launch; import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * This transformer redirects many GL calls to our custom GLStateManager * <p> * THIS CLASS MIGHT BE LOADED ON A DIFFERENT CLASS LOADER, * IT SHOULD NOT CALL ANY CODE FROM THE MAIN MOD */ public final class AngelicaRedirector { private static final boolean ASSERT_MAIN_THREAD = Boolean.getBoolean("angelica.assertMainThread"); private static final boolean LOG_SPAM = Boolean.getBoolean("angelica.redirectorLogspam"); private static final Logger LOGGER = LogManager.getLogger("AngelicaRedirector"); private static final String Drawable = "org/lwjgl/opengl/Drawable"; private static final String GLStateManager = "com/gtnewhorizons/angelica/glsm/GLStateManager"; private static final String GL11 = "org/lwjgl/opengl/GL11"; private static final String GL12 = "org/lwjgl/opengl/GL12"; private static final String GL13 = "org/lwjgl/opengl/GL13"; private static final String GL14 = "org/lwjgl/opengl/GL14"; private static final String GL20 = "org/lwjgl/opengl/GL20"; private static final String Project = "org/lwjgl/util/glu/Project"; private static final String OpenGlHelper = "net/minecraft/client/renderer/OpenGlHelper"; private static final String EXTBlendFunc = "org/lwjgl/opengl/EXTBlendFuncSeparate"; private static final String ARBMultiTexture = "org/lwjgl/opengl/ARBMultitexture"; private static final String MinecraftClient = "net.minecraft.client"; private static final String SplashProgress = "cpw.mods.fml.client.SplashProgress"; private static final Set<String> ExcludedMinecraftMainThreadChecks = ImmutableSet.of( "startGame", "func_71384_a", "initializeTextures", "func_77474_a" ); private static final ClassConstantPoolParser cstPoolParser = new ClassConstantPoolParser(GL11, GL12, GL13, GL14, GL20, OpenGlHelper, EXTBlendFunc, ARBMultiTexture, Project); private static final Map<String, Map<String, String>> methodRedirects = new HashMap<>(); private static final Map<Integer, String> glCapRedirects = new HashMap<>(); static { glCapRedirects.put(org.lwjgl.opengl.GL11.GL_ALPHA_TEST, "AlphaTest"); glCapRedirects.put(org.lwjgl.opengl.GL11.GL_BLEND, "Blend"); glCapRedirects.put(org.lwjgl.opengl.GL11.GL_DEPTH_TEST, "DepthTest"); glCapRedirects.put(org.lwjgl.opengl.GL11.GL_CULL_FACE, "Cull"); glCapRedirects.put(org.lwjgl.opengl.GL11.GL_LIGHTING, "Lighting"); glCapRedirects.put(org.lwjgl.opengl.GL11.GL_TEXTURE_2D, "Texture"); glCapRedirects.put(org.lwjgl.opengl.GL11.GL_FOG, "Fog"); glCapRedirects.put(org.lwjgl.opengl.GL12.GL_RESCALE_NORMAL, "RescaleNormal"); glCapRedirects.put(org.lwjgl.opengl.GL11.GL_SCISSOR_TEST, "ScissorTest"); methodRedirects.put(GL11, RedirectMap.newMap() .add("glAlphaFunc") .add("glBegin") .add("glBindTexture") .add("glBlendFunc") .add("glCallList") .add("glCallLists") .add("glClear") .add("glClearColor") .add("glClearDepth") .add("glClearStencil") .add("glClipPlane") .add("glColor3b") .add("glColor3d") .add("glColor3f") .add("glColor3ub") .add("glColor4b") .add("glColor4d") .add("glColor4f") .add("glColor4ub") .add("glColorMask") .add("glColorMaterial") .add("glDeleteLists") .add("glDeleteTextures") .add("glDepthFunc") .add("glDepthMask") .add("glDepthRange") .add("glDrawArrays") .add("glDrawBuffer") .add("glDrawElements") .add("glEdgeFlag") .add("glEnd") .add("glEndList") .add("glFog") .add("glFogf") .add("glFogi") .add("glFrustum") .add("glGetBoolean") .add("glGetFloat") .add("glGetInteger") .add("glGetLight") .add("glGetMaterial") .add("glGetTexLevelParameteri") .add("glGetTexParameterf") .add("glGetTexParameteri") .add("glIsEnabled") .add("glMaterial") .add("glMaterialf") .add("glMateriali") .add("glLight") .add("glLightf") .add("glLighti") .add("glLightModel") .add("glLightModelf") .add("glLightModeli") .add("glLineStipple") .add("glLineWidth") .add("glListBase") .add("glLoadIdentity") .add("glLoadMatrix") .add("glLogicOp") .add("glMatrixMode") .add("glMultMatrix") .add("glNewList") .add("glNormal3b") .add("glNormal3d") .add("glNormal3f") .add("glNormal3i") .add("glOrtho") .add("glPopAttrib") .add("glPopMatrix") .add("glPushAttrib") .add("glPushMatrix") .add("glRasterPos2d") .add("glRasterPos2f") .add("glRasterPos2i") .add("glRasterPos3d") .add("glRasterPos3f") .add("glRasterPos3i") .add("glRasterPos4d") .add("glRasterPos4f") .add("glRasterPos4i") .add("glRotated") .add("glRotatef") .add("glScaled") .add("glScalef") .add("glShadeModel") .add("glTexCoord1d") .add("glTexCoord1f") .add("glTexCoord2d") .add("glTexCoord2f") .add("glTexCoord3d") .add("glTexCoord3f") .add("glTexCoord4d") .add("glTexCoord4f") .add("glTexImage1D") .add("glTexImage2D") .add("glTexImage3D") .add("glTexSubImage1D") .add("glTexSubImage2D") .add("glCopyTexImage1D") .add("glCopyTexImage2D") .add("glCopyTexSubImage1D") .add("glCopyTexSubImage2D") .add("glPixelStoref") .add("glPixelStorei") .add("glTexParameter") .add("glTexParameterf") .add("glTexParameteri") .add("glTexParameteri") .add("glCullFace") .add("glFrontFace") .add("glHint") .add("glLineStipple") .add("glLineWidth") .add("glPointSize") .add("glPolygonMode") .add("glPolygonOffset") .add("glReadBuffer") .add("glSampleCoverage") .add("glScissor") .add("glStencilFunc") .add("glStencilFuncSeparate") .add("glStencilMask") .add("glStencilMaskSeparate") .add("glStencilOp") .add("glStencilOpSeparate") .add("glTranslated") .add("glTranslatef") .add("glVertex2d") .add("glVertex2f") .add("glVertex3d") .add("glVertex3f") .add("glVertexPointer") .add("glColorPointer") .add("glEnableClientState") .add("glDisableClientState") .add("glViewport") ); methodRedirects.put(GL12, RedirectMap.newMap() .add("glTexImage3D") .add("glTexSubImage3D") .add("glCopyTexSubImage3D") ); methodRedirects.put(GL13, RedirectMap.newMap() .add("glActiveTexture") .add("glSampleCoverage") ); methodRedirects.put(GL14, RedirectMap.newMap() .add("glBlendFuncSeparate", "tryBlendFuncSeparate") .add("glBlendColor") .add("glBlendEquation") ); methodRedirects.put(GL20, RedirectMap.newMap() .add("glBlendEquationSeparate") .add("glDrawBuffers") .add("glStencilFuncSeparate") .add("glStencilMaskSeparate") .add("glStencilOpSeparate") .add("glUseProgram") ); methodRedirects.put(OpenGlHelper, RedirectMap.newMap() .add("glBlendFunc", "tryBlendFuncSeparate") .add("func_148821_a", "tryBlendFuncSeparate")); methodRedirects.put(EXTBlendFunc, RedirectMap.newMap().add("glBlendFuncSeparateEXT", "tryBlendFuncSeparate")); methodRedirects.put(ARBMultiTexture, RedirectMap.newMap().add("glActiveTextureARB")); methodRedirects.put(Project, RedirectMap.newMap().add("gluPerspective")); } public String[] getTransformerExclusions() { return new String[]{ "org.lwjgl", "com.gtnewhorizons.angelica.glsm.", "com.gtnewhorizons.angelica.transform", "com.gtnewhorizon.gtnhlib.asm.", "me.eigenraven.lwjgl3ify" }; } public boolean shouldTransform(byte[] basicClass) { return cstPoolParser.find(basicClass, true); } /** @return Was the class changed? */ public boolean transformClassNode(String transformedName, ClassNode cn) { if (cn == null) { return false; } boolean changed = false; for (MethodNode mn : cn.methods) { if (transformedName.equals("net.minecraft.client.renderer.OpenGlHelper") && (mn.name.equals("glBlendFunc") || mn.name.equals("func_148821_a"))) { continue; } boolean redirectInMethod = false; for (AbstractInsnNode node : mn.instructions.toArray()) { if (node instanceof MethodInsnNode mNode) { if (mNode.owner.equals(GL11) && (mNode.name.equals("glEnable") || mNode.name.equals("glDisable")) && mNode.desc.equals("(I)V")) { final AbstractInsnNode prevNode = node.getPrevious(); String name = null; if (prevNode instanceof LdcInsnNode ldcNode) { name = glCapRedirects.get(((Integer) ldcNode.cst)); } else if (prevNode instanceof IntInsnNode intNode) { name = glCapRedirects.get(intNode.operand); } if (name != null) { if (mNode.name.equals("glEnable")) { name = "enable" + name; } else { name = "disable" + name; } } if (LOG_SPAM) { if (name == null) { LOGGER.info("Redirecting call in {} from GL11.{}(I)V to GLStateManager.{}(I)V", transformedName, mNode.name, mNode.name); } else { LOGGER.info("Redirecting call in {} from GL11.{}(I)V to GLStateManager.{}()V", transformedName, mNode.name, name); } } mNode.owner = GLStateManager; if (name != null) { mNode.name = name; mNode.desc = "()V"; mn.instructions.remove(prevNode); } changed = true; redirectInMethod = true; } else if (mNode.owner.startsWith(Drawable) && mNode.name.equals("makeCurrent")) { mNode.setOpcode(Opcodes.INVOKESTATIC); mNode.owner = GLStateManager; mNode.desc = "(L" + Drawable + ";)V"; mNode.itf = false; changed = true; if (LOG_SPAM) { LOGGER.info("Redirecting call in {} to GLStateManager.makeCurrent()", transformedName); } } else { final Map<String, String> redirects = methodRedirects.get(mNode.owner); if (redirects != null && redirects.containsKey(mNode.name)) { if (LOG_SPAM) { final String shortOwner = mNode.owner.substring(mNode.owner.lastIndexOf("/") + 1); LOGGER.info("Redirecting call in {} from {}.{}{} to GLStateManager.{}{}", transformedName, shortOwner, mNode.name, mNode.desc, redirects.get(mNode.name), mNode.desc); } mNode.owner = GLStateManager; mNode.name = redirects.get(mNode.name); changed = true; redirectInMethod = true; } } } } if (ASSERT_MAIN_THREAD && redirectInMethod && !transformedName.startsWith(SplashProgress) && !(transformedName.startsWith(MinecraftClient) && ExcludedMinecraftMainThreadChecks.contains(mn.name))) { mn.instructions.insert(new MethodInsnNode(Opcodes.INVOKESTATIC, GLStateManager, "assertMainThread", "()V", false)); } } return changed; } private static class RedirectMap<K> extends HashMap<K, K> { public static RedirectMap<String> newMap() { return new RedirectMap<>(); } public RedirectMap<K> add(K name) { this.put(name, name); return this; } public RedirectMap<K> add(K name, K newName) { this.put(name, newName); return this; } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\loading\shared\transformers\SodiumBlockTransform.java
package com.gtnewhorizons.angelica.loading.shared.transformers; import com.google.common.collect.ImmutableList; import com.gtnewhorizon.gtnhlib.asm.ClassConstantPoolParser; import net.minecraft.launchwrapper.Launch; import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class SodiumBlockTransform { public SodiumBlockTransform(boolean isObf) { this.IS_OBF = isObf; } private final boolean IS_OBF; private static final boolean LOG_SPAM = Boolean.getBoolean("angelica.redirectorLogspam"); private static final Logger LOGGER = LogManager.getLogger("SodiumBlockTransformer"); private static final String BlockClass = "net/minecraft/block/Block"; private static final String BlockPackage = "net/minecraft/block/Block"; private static final String ThreadedBlockData = "com/gtnewhorizons/angelica/glsm/ThreadedBlockData"; private static final List<Pair<String, String>> BlockBoundsFields = ImmutableList.of( Pair.of("minX", "field_149759_B"), Pair.of("minY", "field_149760_C"), Pair.of("minZ", "field_149754_D"), Pair.of("maxX", "field_149755_E"), Pair.of("maxY", "field_149756_F"), Pair.of("maxZ", "field_149757_G") ); /** All classes in <tt>net.minecraft.block.*</tt> are the block subclasses save for these. */ private static final String[] VanillaBlockExclusions = { "net/minecraft/block/IGrowable", "net/minecraft/block/ITileEntityProvider", "net/minecraft/block/BlockEventData", "net/minecraft/block/BlockSourceImpl", "net/minecraft/block/material/" }; private static final ClassConstantPoolParser cstPoolParser = new ClassConstantPoolParser(BlockPackage); private static final Set<String> moddedBlockSubclasses = Collections.newSetFromMap(new ConcurrentHashMap<>()); // Block owners we *shouldn't* redirect because they shadow one of our fields private static final Set<String> blockOwnerExclusions = Collections.newSetFromMap(new ConcurrentHashMap<>()); // Needed because the config is loaded in LaunchClassLoader, but we need to access it in the parent system loader. private static final MethodHandle angelicaConfigSodiumEnabledGetter; private static boolean isSodiumEnabled; static { try { final Class<?> angelicaConfig = Class.forName("com.gtnewhorizons.angelica.config.AngelicaConfig", true, Launch.classLoader); angelicaConfigSodiumEnabledGetter = MethodHandles.lookup().findStaticGetter(angelicaConfig, "enableSodium", boolean.class); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } private static boolean isSodiumEnabled() { if (isSodiumEnabled) return true; try { return (boolean) angelicaConfigSodiumEnabledGetter.invokeExact(); } catch (Throwable e) { throw new RuntimeException(e); } } private boolean isVanillaBlockSubclass(String className) { if (className.startsWith(BlockPackage)) { for (String exclusion : VanillaBlockExclusions) { if (className.startsWith(exclusion)) { return false; } } return true; } return false; } private boolean isBlockSubclass(String className) { return isVanillaBlockSubclass(className) || moddedBlockSubclasses.contains(className); } private String getFieldName(Pair<String, String> fieldPair) { return IS_OBF ? fieldPair.getRight() : fieldPair.getLeft(); } public String[] getTransformerExclusions() { return new String[]{ "org.lwjgl", "com.gtnewhorizons.angelica.glsm.", "com.gtnewhorizons.angelica.transform", "com.gtnewhorizon.gtnhlib.asm.", "me.eigenraven.lwjgl3ify" }; } public boolean shouldTransform(byte[] basicClass) { return cstPoolParser.find(basicClass, true); } /** @return Was the class changed? */ public boolean transformClassNode(String transformedName, ClassNode cn) { if (cn == null) { return false; } if ("net.minecraft.block.Block".equals(transformedName) && isSodiumEnabled()) { cn.fields.removeIf(field -> BlockBoundsFields.stream().anyMatch(pair -> field.name.equals(pair.getLeft()) || field.name.equals(pair.getRight()))); } // Track subclasses of Block if (!isVanillaBlockSubclass(cn.name) && isBlockSubclass(cn.superName)) { moddedBlockSubclasses.add(cn.name); cstPoolParser.addString(cn.name); } // Check if this class shadows any fields of the parent class if (moddedBlockSubclasses.contains(cn.name)) { // If a superclass shadows, then so do we, because JVM will resolve a reference on our class to that // superclass boolean doWeShadow; if (blockOwnerExclusions.contains(cn.superName)) { doWeShadow = true; } else { // Check if we declare any known field names boolean b = false; for (Pair<String, String> pair : BlockBoundsFields) { boolean result = false; for (FieldNode field : cn.fields) { if (field.name.equals(getFieldName(pair))) { result = true; break; } } if (result) { b = true; break; } } doWeShadow = b; } if (doWeShadow) { LOGGER.info("Class '{}' shadows one or more block bounds fields, these accesses won't be redirected!", cn.name); blockOwnerExclusions.add(cn.name); } } boolean changed = false; for (MethodNode mn : cn.methods) { for (AbstractInsnNode node : mn.instructions.toArray()) { if ((node.getOpcode() == Opcodes.GETFIELD || node.getOpcode() == Opcodes.PUTFIELD) && node instanceof FieldInsnNode fNode) { if (!blockOwnerExclusions.contains(fNode.owner) && isBlockSubclass(fNode.owner) && isSodiumEnabled()) { Pair<String, String> fieldToRedirect = BlockBoundsFields.stream() .filter(pair -> fNode.name.equals(getFieldName(pair))) .findFirst() .orElse(null); if (fieldToRedirect != null) { if (LOG_SPAM) { LOGGER.info("Redirecting Block.{} in {} to thread-safe wrapper", fNode.name, transformedName); } // Perform the redirect fNode.name = fieldToRedirect.getLeft(); // use unobfuscated name fNode.owner = ThreadedBlockData; // Inject getter before the field access, to turn Block -> ThreadedBlockData final MethodInsnNode getter = new MethodInsnNode(Opcodes.INVOKESTATIC, ThreadedBlockData, "get", "(L" + BlockClass + ";)L" + ThreadedBlockData + ";", false); if (node.getOpcode() == Opcodes.GETFIELD) { mn.instructions.insertBefore(fNode, getter); } else if (node.getOpcode() == Opcodes.PUTFIELD) { // FIXME: this code assumes doubles // Stack: Block, double final InsnList beforePut = new InsnList(); beforePut.add(new InsnNode(Opcodes.DUP2_X1)); // Stack: double, Block, double beforePut.add(new InsnNode(Opcodes.POP2)); // Stack: double, Block beforePut.add(getter); // Stack: double, ThreadedBlockData beforePut.add(new InsnNode(Opcodes.DUP_X2)); // Stack: ThreadedBlockData, double, ThreadedBlockData beforePut.add(new InsnNode(Opcodes.POP)); // Stack: ThreadedBlockData, double mn.instructions.insertBefore(fNode, beforePut); } changed = true; } } } } } return changed; } public void setSodiumSetting() { isSodiumEnabled = true; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\dummy\DummyTessellator.java
package com.gtnewhorizons.angelica.mixins.dummy; import net.minecraft.client.renderer.Tessellator; /** * No-op tessellator to replace the inconvienent one */ public class DummyTessellator extends Tessellator { public static Tessellator instance = new DummyTessellator(); @Override public void startDrawingQuads() {} @Override public void setColorOpaque_I(int whocares) {} @Override public void addVertex(double thing1, double thing2, double thereaintnothing3) {} @Override public int draw() { return 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\hooks\FluidHooks.java
package com.gtnewhorizons.angelica.mixins.hooks; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraftforge.fluids.BlockFluidBase; public class FluidHooks { /** * {@link BlockFluidBase#getFluid()} that uses the given Block instead of fetching it from the world again */ public static double getFlowDirection(IBlockAccess world, int x, int y, int z, BlockFluidBase block) { if (!block.getMaterial().isLiquid()) { return -1000.0; } Vec3 vec = block.getFlowVector(world, x, y, z); return vec.xCoord == 0.0D && vec.zCoord == 0.0D ? -1000.0D : Math.atan2(vec.zCoord, vec.xCoord) - Math.PI / 2D; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\EntityRendererAccessor.java
package com.gtnewhorizons.angelica.mixins.interfaces; import net.minecraft.entity.player.EntityPlayer; public interface EntityRendererAccessor { float invokeGetNightVisionBrightness(EntityPlayer entityPlayer, float partialTicks); }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\FontRendererAccessor.java
package com.gtnewhorizons.angelica.mixins.interfaces; import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer; import net.minecraft.util.ResourceLocation; public interface FontRendererAccessor { int angelica$drawStringBatched(String text, int x, int y, int argb, boolean dropShadow); BatchingFontRenderer angelica$getBatcher(); void angelica$bindTexture(ResourceLocation location); }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\GuiIngameAccessor.java
package com.gtnewhorizons.angelica.mixins.interfaces; public interface GuiIngameAccessor { void callRenderVignette(float brightness, int width, int height); void callRenderPumpkinBlur(int width, int height); void callRenderPortal(float partialTicks, int width, int height); }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\GuiIngameForgeAccessor.java
package com.gtnewhorizons.angelica.mixins.interfaces; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.util.ResourceLocation; public interface GuiIngameForgeAccessor { void callRenderCrosshairs(int width, int height); void callRenderHelmet(ScaledResolution res, float partialTicks, boolean hasScreen, int mouseX, int mouseY); void callRenderPortal(int width, int height, float partialTicks); void callBind(ResourceLocation res); }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\IGameSettingsExt.java
package com.gtnewhorizons.angelica.mixins.interfaces; public interface IGameSettingsExt { boolean angelica$showFpsGraph(); void angelica$setShowFpsGraph(boolean renderFpsGraph); }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\IModelRenderer.java
package com.gtnewhorizons.angelica.mixins.interfaces; public interface IModelRenderer { void angelica$resetDisplayList(); }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\IPatchedTextureAtlasSprite.java
package com.gtnewhorizons.angelica.mixins.interfaces; public interface IPatchedTextureAtlasSprite { void markNeedsAnimationUpdate(); boolean needsAnimationUpdate(); void unmarkNeedsAnimationUpdate(); void updateAnimationsDryRun(); }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\IRenderGlobalExt.java
package com.gtnewhorizons.angelica.mixins.interfaces; public interface IRenderGlobalExt { void scheduleTerrainUpdate(); void reload(); }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\IRenderingRegistryExt.java
package com.gtnewhorizons.angelica.mixins.interfaces; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; public interface IRenderingRegistryExt { ISimpleBlockRenderingHandler getISBRH(int modelId); }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\ISpriteExt.java
package com.gtnewhorizons.angelica.mixins.interfaces; import net.minecraft.client.resources.data.AnimationMetadataSection; public interface ISpriteExt { boolean isAnimation(); int getFrame(); void callUpload(int frameIndex); AnimationMetadataSection getMetadata(); }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\ITexturesCache.java
package com.gtnewhorizons.angelica.mixins.interfaces; import net.minecraft.util.IIcon; import java.util.Set; public interface ITexturesCache { Set<IIcon> getRenderedTextures(); void enableTextureTracking(); void track(IPatchedTextureAtlasSprite sprite); }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\RenderGameOverlayEventAccessor.java
package com.gtnewhorizons.angelica.mixins.interfaces; import net.minecraft.client.gui.ScaledResolution; public interface RenderGameOverlayEventAccessor { void setPartialTicks(float value); void setResolution(ScaledResolution resolution); void setMouseX(int mouseX); void setMouseY(int mouseY); }
Angelica
src\main\java\com\gtnewhorizons\angelica\mixins\interfaces\ResourceAccessor.java
package com.gtnewhorizons.angelica.mixins.interfaces; import java.util.List; public interface ResourceAccessor { List angelica$getDefaultResourcePacks(); }
Angelica
src\main\java\com\prupe\mcpatcher\MCLogger.java
package com.prupe.mcpatcher; import jss.notfine.config.MCPatcherForgeConfig; import java.util.HashMap; import java.util.Map; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; public class MCLogger { private static final org.apache.logging.log4j.Logger MAIN_LOGGER = org.apache.logging.log4j.LogManager.getLogger("MCPatcherForge"); private static final Map<String, MCLogger> allLoggers = new HashMap<>(); public static final Level ERROR = new ErrorLevel(); private static final long FLOOD_INTERVAL = 1000L; private static final long FLOOD_REPORT_INTERVAL = 5000L; private static final int FLOOD_LEVEL = Level.INFO.intValue(); private final String logPrefix; private final Logger logger; private boolean flooding; private long lastFloodReport; private int floodCount; private long lastMessage = System.currentTimeMillis(); public static MCLogger getLogger(Category category) { return getLogger(category, category.name); } public static synchronized MCLogger getLogger(Category category, String logPrefix) { MCLogger logger = allLoggers.get(category.name); if (logger == null) { logger = new MCLogger(category, logPrefix); allLoggers.put(category.name, logger); } return logger; } private MCLogger(Category category, String logPrefix) { this.logPrefix = logPrefix; logger = Logger.getLogger(category.name); logger.setLevel(switch (category) { case CUSTOM_COLORS -> MCPatcherForgeConfig.CustomColors.logging.level; case CUSTOM_ITEM_TEXTURES -> MCPatcherForgeConfig.CustomItemTextures.logging.level; case CONNECTED_TEXTURES -> MCPatcherForgeConfig.ConnectedTextures.logging.level; case EXTENDED_HD -> MCPatcherForgeConfig.ExtendedHD.logging.level; case RANDOM_MOBS -> MCPatcherForgeConfig.RandomMobs.logging.level; case BETTER_SKIES -> MCPatcherForgeConfig.BetterSkies.logging.level; default -> Level.INFO; }); logger.setUseParentHandlers(false); logger.addHandler(new Handler() { private final Formatter formatter = new Formatter() { @Override public String format(LogRecord record) { Level level = record.getLevel(); if (level == Level.CONFIG) { return record.getMessage(); } else { String message = record.getMessage(); StringBuilder prefix = new StringBuilder(); while (message.startsWith("\n")) { prefix.append("\n"); message = message.substring(1); } return prefix + "[" + MCLogger.this.logPrefix + "/" + level.toString() + "]: " + message; } } }; @Override public void publish(LogRecord record) { MAIN_LOGGER.info(formatter.format(record)); } @Override public void flush() {} @Override public void close() throws SecurityException {} }); } private boolean checkFlood() { long now = System.currentTimeMillis(); boolean showFloodMessage = false; if (now - lastMessage > FLOOD_INTERVAL) { if (flooding) { reportFlooding(now); flooding = false; } else { floodCount = 0; } } else if (flooding && now - lastFloodReport > FLOOD_REPORT_INTERVAL) { reportFlooding(now); showFloodMessage = true; } lastMessage = now; floodCount++; if (flooding) { return showFloodMessage; } else { return true; } } private void reportFlooding(long now) { if (floodCount > 0) { logger.log( Level.WARNING, String .format("%d flood messages dropped in the last %ds", floodCount, (now - lastFloodReport) / 1000L)); } floodCount = 0; lastFloodReport = now; } public boolean isLoggable(Level level) { return logger.isLoggable(level); } public void log(Level level, String format, Object... params) { if (isLoggable(level)) { if (level.intValue() >= FLOOD_LEVEL && !checkFlood()) { return; } logger.log(level, String.format(format, params)); } } public void severe(String format, Object... params) { log(Level.SEVERE, format, params); } public void error(String format, Object... params) { log(ERROR, format, params); } public void warning(String format, Object... params) { log(Level.WARNING, format, params); } public void info(String format, Object... params) { log(Level.INFO, format, params); } public void config(String format, Object... params) { log(Level.CONFIG, format, params); } public void fine(String format, Object... params) { log(Level.FINE, format, params); } public void finer(String format, Object... params) { log(Level.FINER, format, params); } public void finest(String format, Object... params) { log(Level.FINEST, format, params); } private static class ErrorLevel extends Level { private static final long serialVersionUID = 3987750897854233321L; protected ErrorLevel() { super("ERROR", (Level.WARNING.intValue() + Level.SEVERE.intValue()) / 2); } } public enum Category { CUSTOM_COLORS(MCPatcherUtils.CUSTOM_COLORS), CUSTOM_ITEM_TEXTURES(MCPatcherUtils.CUSTOM_ITEM_TEXTURES), CONNECTED_TEXTURES(MCPatcherUtils.CONNECTED_TEXTURES), EXTENDED_HD(MCPatcherUtils.EXTENDED_HD), RANDOM_MOBS(MCPatcherUtils.RANDOM_MOBS), BETTER_SKIES(MCPatcherUtils.BETTER_SKIES), TEXTURE_PACK("Texture Pack"), TILESHEET("Tilesheet"), BETTER_GLASS(MCPatcherUtils.BETTER_GLASS), ; public final String name; Category(String name) { this.name = name; } } }
Angelica
src\main\java\com\prupe\mcpatcher\MCPatcherUtils.java
package com.prupe.mcpatcher; import java.awt.image.BufferedImage; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipFile; import net.minecraft.launchwrapper.Launch; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * Collection of static methods available to mods at runtime. */ public class MCPatcherUtils { private static File minecraftDir; private static File gameDir; public static final String EXTENDED_HD = "Extended HD"; public static final String HD_FONT = "HD Font"; public static final String RANDOM_MOBS = "Random Mobs"; public static final String CUSTOM_COLORS = "Custom Colors"; public static final String CONNECTED_TEXTURES = "Connected Textures"; public static final String BETTER_SKIES = "Better Skies"; public static final String BETTER_GLASS = "Better Glass"; public static final String CUSTOM_ITEM_TEXTURES = "Custom Item Textures"; public static final String CUSTOM_ANIMATIONS = "Custom Animations"; public static final String MIPMAP = "Mipmap"; public static final String RENDER_PASS_CLASS = "com.prupe.mcpatcher.renderpass.RenderPass"; public static final String BLANK_PNG_FORMAT = "blank_%08x.png"; private static final Logger log = LogManager.getLogger(); private MCPatcherUtils() {} /** * Get the path to a file/directory within the minecraft folder. * * @param subdirs zero or more path components * @return combined path */ public static File getMinecraftPath(String... subdirs) { File f = minecraftDir; for (String s : subdirs) { f = new File(f, s); } return f; } /** * Get the path to a file/directory within the game folder. The game folder is usually the same as the minecraft * folder, but can be overridden via a launcher profile setting. * * @param subdirs zero or more path components * @return combined path */ public static File getGamePath(String... subdirs) { File f = gameDir; for (String s : subdirs) { f = new File(f, s); } return f; } /** * Get a value from a properties file. * * @param properties properties file * @param key property name * @param defaultValue default value if not found in properties file * @return property value */ public static String getStringProperty(Properties properties, String key, String defaultValue) { if (properties == null) { return defaultValue; } else { return properties.getProperty(key, defaultValue) .trim(); } } /** * Get a value from a properties file. * * @param properties properties file * @param key property name * @param defaultValue default value if not found in properties file * @return property value */ public static int getIntProperty(Properties properties, String key, int defaultValue) { if (properties != null) { String value = properties.getProperty(key, "") .trim(); if (!value.isEmpty()) { try { return Integer.parseInt(value); } catch (NumberFormatException e) {} } } return defaultValue; } /** * Get a value from a properties file. * * @param properties properties file * @param key property name * @param defaultValue default value if not found in properties file * @return property value */ public static int getHexProperty(Properties properties, String key, int defaultValue) { if (properties != null) { String value = properties.getProperty(key, "") .trim(); if (!value.isEmpty()) { try { return Integer.parseInt(value, 16); } catch (NumberFormatException e) {} } } return defaultValue; } /** * Get a value from a properties file. * * @param properties properties file * @param key property name * @param defaultValue default value if not found in properties file * @return property value */ public static boolean getBooleanProperty(Properties properties, String key, boolean defaultValue) { if (properties != null) { String value = properties.getProperty(key, "") .trim() .toLowerCase(); if (!value.isEmpty()) { return Boolean.parseBoolean(value); } } return defaultValue; } /** * Get a value from a properties file. * * @param properties properties file * @param key property name * @param defaultValue default value if not found in properties file * @return property value */ public static float getFloatProperty(Properties properties, String key, float defaultValue) { if (properties != null) { String value = properties.getProperty(key, "") .trim(); if (!value.isEmpty()) { try { return Float.parseFloat(value); } catch (NumberFormatException e) {} } } return defaultValue; } /** * Get a value from a properties file. * * @param properties properties file * @param key property name * @param defaultValue default value if not found in properties file * @return property value */ public static double getDoubleProperty(Properties properties, String key, double defaultValue) { if (properties != null) { String value = properties.getProperty(key, "") .trim(); if (!value.isEmpty()) { try { return Double.parseDouble(value); } catch (NumberFormatException e) {} } } return defaultValue; } /** * Convenience method to close a stream ignoring exceptions. * * @param closeable closeable object */ public static void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Convenience method to close a zip file ignoring exceptions. * * @param zip zip file */ public static void close(ZipFile zip) { if (zip != null) { try { zip.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Returns true if string is null or consists only of whitespace. * * @param s possibly null string * @return true if null or empty */ public static boolean isNullOrEmpty(String s) { return s == null || s.trim() .isEmpty(); } /** * Returns true if collection is null or empty. * * @param c possibly null collection * @return true if null or empty */ public static boolean isNullOrEmpty(Collection<?> c) { return c == null || c.isEmpty(); } /** * Returns true if map is null or empty. * * @param m possibly null map * @return true if null or empty */ public static boolean isNullOrEmpty(Map<?, ?> m) { return m == null || m.isEmpty(); } public static void setMinecraft(File gameDir) { minecraftDir = Launch.minecraftHome; if (gameDir == null || !gameDir.isDirectory()) { MCPatcherUtils.gameDir = minecraftDir; } else { MCPatcherUtils.gameDir = gameDir.getAbsoluteFile(); } log.info("MCPatcherUtils initialized:"); } /** * Get array of rgb values from image. * * @param image input image * @return rgb array */ public static int[] getImageRGB(BufferedImage image) { if (image == null) { return null; } else { int width = image.getWidth(); int height = image.getHeight(); int[] rgb = new int[width * height]; image.getRGB(0, 0, width, height, rgb, 0, width); return rgb; } } /** * Parse a comma-separated list of integers/ranges. * * @param list comma- or space-separated list, e.g., 2-4,5,8,12-20 * @param minValue smallest value allowed in the list * @param maxValue largest value allowed in the list * @return possibly empty integer array */ public static int[] parseIntegerList(String list, int minValue, int maxValue) { ArrayList<Integer> tmpList = new ArrayList<>(); Pattern p = Pattern.compile("(\\d*)-(\\d*)"); for (String token : list.replace(',', ' ') .split("\\s+")) { try { if (token.matches("\\d+")) { tmpList.add(Integer.parseInt(token)); } else { Matcher m = p.matcher(token); if (m.matches()) { String a = m.group(1); String b = m.group(2); int min = a.isEmpty() ? minValue : Integer.parseInt(a); int max = b.isEmpty() ? maxValue : Integer.parseInt(b); for (int i = min; i <= max; i++) { tmpList.add(i); } } } } catch (NumberFormatException e) {} } if (minValue <= maxValue) { for (int i = 0; i < tmpList.size();) { if (tmpList.get(i) < minValue || tmpList.get(i) > maxValue) { tmpList.remove(i); } else { i++; } } } int[] a = new int[tmpList.size()]; for (int i = 0; i < a.length; i++) { a[i] = tmpList.get(i); } return a; } }
Angelica
src\main\java\com\prupe\mcpatcher\cc\ColorizeBlock.java
package com.prupe.mcpatcher.cc; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; import org.lwjgl.opengl.GL11; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.biome.BiomeAPI; import com.prupe.mcpatcher.mal.biome.ColorMap; import com.prupe.mcpatcher.mal.biome.ColorMapBase; import com.prupe.mcpatcher.mal.biome.ColorUtils; import com.prupe.mcpatcher.mal.biome.IColorMap; import com.prupe.mcpatcher.mal.block.BlockAPI; import com.prupe.mcpatcher.mal.block.BlockStateMatcher; import com.prupe.mcpatcher.mal.block.RenderBlocksUtils; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.ResourceList; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import jss.notfine.config.MCPatcherForgeConfig; public class ColorizeBlock { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CUSTOM_COLORS); private static final boolean useWaterColors = MCPatcherForgeConfig.CustomColors.water; private static final boolean useTreeColors = MCPatcherForgeConfig.CustomColors.tree; private static final boolean useRedstoneColors = MCPatcherForgeConfig.CustomColors.redstone; private static final boolean useStemColors = MCPatcherForgeConfig.CustomColors.stem; private static final boolean useBlockColors = MCPatcherForgeConfig.CustomColors.otherBlocks; private static final boolean enableSmoothBiomes = MCPatcherForgeConfig.CustomColors.smoothBiomes; private static final boolean enableTestColorSmoothing = MCPatcherForgeConfig.CustomColors.testColorSmoothing; private static final ResourceLocation REDSTONE_COLORS = TexturePackAPI .newMCPatcherResourceLocation("colormap/redstone.png"); private static final ResourceLocation STEM_COLORS = TexturePackAPI .newMCPatcherResourceLocation("colormap/stem.png"); private static final ResourceLocation PUMPKIN_STEM_COLORS = TexturePackAPI .newMCPatcherResourceLocation("colormap/pumpkinstem.png"); private static final ResourceLocation MELON_STEM_COLORS = TexturePackAPI .newMCPatcherResourceLocation("colormap/melonstem.png"); private static final ResourceLocation SWAMPGRASSCOLOR = TexturePackAPI .newMCPatcherResourceLocation("colormap/swampgrass.png"); private static final ResourceLocation SWAMPFOLIAGECOLOR = TexturePackAPI .newMCPatcherResourceLocation("colormap/swampfoliage.png"); private static final ResourceLocation DEFAULT_GRASSCOLOR = new ResourceLocation( "minecraft:textures/colormap/grass.png"); private static final ResourceLocation DEFAULT_FOLIAGECOLOR = new ResourceLocation( "minecraft:textures/colormap/foliage.png"); private static final ResourceLocation PINECOLOR = TexturePackAPI .newMCPatcherResourceLocation("colormap/pine.png"); private static final ResourceLocation BIRCHCOLOR = TexturePackAPI .newMCPatcherResourceLocation("colormap/birch.png"); private static final ResourceLocation WATERCOLOR = TexturePackAPI .newMCPatcherResourceLocation("colormap/water.png"); private static final String PALETTE_BLOCK_KEY = "palette.block."; // bitmaps from palette.block.* private static final Map<Block, List<BlockStateMatcher>> blockColorMaps = new IdentityHashMap<>(); private static IColorMap waterColorMap; private static float[][] redstoneColor; // colormap/redstone.png private static final int blockBlendRadius = MCPatcherForgeConfig.CustomColors.blockBlendRadius; public static int blockColor; public static boolean isSmooth; public static float colorRedTopLeft; public static float colorRedBottomLeft; public static float colorRedBottomRight; public static float colorRedTopRight; public static float colorGreenTopLeft; public static float colorGreenBottomLeft; public static float colorGreenBottomRight; public static float colorGreenTopRight; public static float colorBlueTopLeft; public static float colorBlueBottomLeft; public static float colorBlueBottomRight; public static float colorBlueTopRight; private static final int[][][] FACE_VERTICES = new int[][][] { // bottom face (y=0) { { 0, 0, 1 }, // top left { 0, 0, 0 }, // bottom left { 1, 0, 0 }, // bottom right { 1, 0, 1 }, // top right }, // top face (y=1) { { 1, 1, 1 }, { 1, 1, 0 }, { 0, 1, 0 }, { 0, 1, 1 }, }, // north face (z=0) { { 0, 1, 0 }, { 1, 1, 0 }, { 1, 0, 0 }, { 0, 0, 0 }, }, // south face (z=1) { { 0, 1, 1 }, { 0, 0, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, }, // west face (x=0) { { 0, 1, 1 }, { 0, 1, 0 }, { 0, 0, 0 }, { 0, 0, 1 }, }, // east face (x=1) { { 1, 0, 1 }, { 1, 0, 0 }, { 1, 1, 0 }, { 1, 1, 1 }, }, // bottom face, water (y=0) { { 0, 0, 1 }, // top left { 0, 0, 0 }, // bottom left { 1, 0, 0 }, // bottom right { 1, 0, 1 }, // top right }, // top face, water (y=1) cycle by 2 { { 0, 1, 0 }, { 0, 1, 1 }, { 1, 1, 1 }, { 1, 1, 0 }, }, // north face, water (z=0) { { 0, 1, 0 }, { 1, 1, 0 }, { 1, 0, 0 }, { 0, 0, 0 }, }, // south face, water (z=1) cycle by 1 { { 1, 1, 1 }, { 0, 1, 1 }, { 0, 0, 1 }, { 1, 0, 1 }, }, // west face, water (x=0) { { 0, 1, 1 }, { 0, 1, 0 }, { 0, 0, 0 }, { 0, 0, 1 }, }, // east face, water (x=1) cycle by 2 { { 1, 1, 0 }, { 1, 1, 1 }, { 1, 0, 1 }, { 1, 0, 0 }, }, }; static { try { reset(); } catch (Exception e) { e.printStackTrace(); } } static void reset() { blockColorMaps.clear(); waterColorMap = null; resetVertexColors(); redstoneColor = null; } static void reloadAll(PropertiesFile properties) { if (useBlockColors) { reloadBlockColors(properties); } if (useTreeColors) { reloadFoliageColors(properties); } if (useWaterColors) { reloadWaterColors(properties); } if (ColorMap.useSwampColors) { reloadSwampColors(properties); } if (useRedstoneColors) { reloadRedstoneColors(properties); } if (useStemColors) { reloadStemColors(properties); } } private static void reloadFoliageColors(PropertiesFile properties) { IColorMap colorMap = ColorMap.loadVanillaColorMap(DEFAULT_GRASSCOLOR, SWAMPGRASSCOLOR); registerColorMap( colorMap, DEFAULT_GRASSCOLOR, "minecraft:grass:snowy=false minecraft:tallgrass:1,2:type=tall_grass,fern minecraft:double_plant:2,3:variant=double_grass,double_fern"); colorMap = ColorMap.loadVanillaColorMap(DEFAULT_FOLIAGECOLOR, SWAMPFOLIAGECOLOR); registerColorMap(colorMap, DEFAULT_FOLIAGECOLOR, "minecraft:leaves:0,4,8,12:variant=oak minecraft:vine"); registerColorMap(PINECOLOR, "minecraft:leaves:1,5,9,13:variant=spruce"); registerColorMap(BIRCHCOLOR, "minecraft:leaves:2,6,10,14:variant=birch"); } private static IColorMap wrapBlockMap(IColorMap map) { if (map == null) { return null; } else { if (blockBlendRadius > 0) { map = new ColorMapBase.Blended(map, blockBlendRadius); } map = new ColorMapBase.Chunked(map); map = new ColorMapBase.Outer(map); return map; } } private static void reloadWaterColors(PropertiesFile properties) { waterColorMap = registerColorMap(WATERCOLOR, "minecraft:flowing_water minecraft:water"); } private static void reloadSwampColors(PropertiesFile properties) { int[] lilypadColor = new int[] { 0x020830 }; if (Colorizer.loadIntColor("lilypad", lilypadColor, 0)) { IColorMap colorMap = new ColorMap.Fixed(lilypadColor[0]); registerColorMap(colorMap, Colorizer.COLOR_PROPERTIES, "minecraft:waterlily"); } } private static void reloadBlockColors(PropertiesFile properties) { for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (!key.startsWith(PALETTE_BLOCK_KEY)) { continue; } key = key.substring(PALETTE_BLOCK_KEY.length()) .trim(); ResourceLocation resource = TexturePackAPI.parseResourceLocation(Colorizer.COLOR_PROPERTIES, key); if (resource == null) { continue; } registerColorMap(resource, value); } for (ResourceLocation resource : ResourceList.getInstance() .listResources(ColorMap.BLOCK_COLORMAP_DIR, ".properties", false)) { Properties properties1 = TexturePackAPI.getProperties(resource); IColorMap colorMap = ColorMap.loadColorMap(true, resource, properties1); registerColorMap( colorMap, resource, MCPatcherUtils.getStringProperty(properties1, "blocks", getDefaultBlockName(resource))); } List<ResourceLocation> unusedPNGs = new ArrayList<>(ColorMap.unusedPNGs); for (ResourceLocation resource : unusedPNGs) { Properties properties1 = new Properties(); IColorMap colorMap = ColorMap.loadColorMap(true, resource, properties1); registerColorMap(colorMap, resource, getDefaultBlockName(resource)); } } private static String getDefaultBlockName(ResourceLocation resource) { return resource.getResourceDomain() + ":" + resource.getResourcePath() .replaceFirst(".*/", "") .replaceFirst("\\.[^.]*$", ""); } private static IColorMap registerColorMap(ResourceLocation resource, String idList) { IColorMap colorMap = ColorMap.loadColorMap(true, resource, null); return registerColorMap(colorMap, resource, idList); } private static IColorMap registerColorMap(IColorMap colorMap, ResourceLocation resource, String idList) { if (colorMap == null) { return null; } colorMap = wrapBlockMap(colorMap); for (String idString : idList.split("\\s+")) { BlockStateMatcher blockMatcher = BlockAPI.createMatcher(new PropertiesFile(logger, resource), idString); if (blockMatcher != null) { List<BlockStateMatcher> maps = blockColorMaps .computeIfAbsent(blockMatcher.getBlock(), k -> new ArrayList<>()); blockMatcher.setData(colorMap); maps.add(blockMatcher); if (resource != null) { logger.fine( "using %s for block %s, default color %06x", colorMap, blockMatcher, colorMap.getColorMultiplier()); } } } return colorMap; } private static void reloadRedstoneColors(PropertiesFile properties) { int[] rgb = MCPatcherUtils.getImageRGB(TexturePackAPI.getImage(REDSTONE_COLORS)); if (rgb != null && rgb.length >= 16) { redstoneColor = new float[16][]; for (int i = 0; i < 16; i++) { float[] f = new float[3]; ColorUtils.intToFloat3(rgb[i], f); redstoneColor[i] = f; } } } private static void reloadStemColors(PropertiesFile properties) { ResourceLocation resource = TexturePackAPI.hasResource(PUMPKIN_STEM_COLORS) ? PUMPKIN_STEM_COLORS : STEM_COLORS; registerMetadataRGB("minecraft:pumpkin_stem", resource, "age", 8); resource = TexturePackAPI.hasResource(MELON_STEM_COLORS) ? MELON_STEM_COLORS : STEM_COLORS; registerMetadataRGB("minecraft:melon_stem", resource, "age", 8); } private static void registerMetadataRGB(String blockName, ResourceLocation resource, String property, int length) { int[] rgb = MCPatcherUtils.getImageRGB(TexturePackAPI.getImage(resource)); if (rgb == null || rgb.length < length) { return; } for (int i = 0; i < length; i++) { IColorMap colorMap = new ColorMap.Fixed(rgb[i] & 0xffffff); String idList = String.format("%s:%d,%d:%s=%d", blockName, i, (i + length) & 0xf, property, i); registerColorMap(colorMap, resource, idList); } } static List<BlockStateMatcher> findColorMaps(Block block) { return blockColorMaps.get(block); } static IColorMap getThreadLocal(BlockStateMatcher matcher) { IColorMap newMap = (IColorMap) matcher.getThreadData(); if (newMap == null) { IColorMap oldMap = (IColorMap) matcher.getData(); newMap = oldMap.copy(); matcher.setThreadData(newMap); } return newMap; } private static IColorMap findColorMap(Block block, int metadata) { List<BlockStateMatcher> maps = findColorMaps(block); if (maps != null) { for (BlockStateMatcher matcher : maps) { if (matcher.match(block, metadata)) { return getThreadLocal(matcher); } } } return null; } private static IColorMap findColorMap(Block block, IBlockAccess blockAccess, int x, int y, int z) { List<BlockStateMatcher> maps = findColorMaps(block); if (maps != null) { for (BlockStateMatcher matcher : maps) { if (matcher.match(blockAccess, x, y, z)) { return getThreadLocal(matcher); } } } return null; } public static boolean colorizeBlock(Block block) { return colorizeBlock(block, 16); } public static boolean colorizeBlock(Block block, int metadata) { IColorMap colorMap = findColorMap(block, metadata); if (colorMap == null) { RenderBlocksUtils.setupColorMultiplier(block, false); return false; } else { RenderBlocksUtils.setupColorMultiplier(block, true); blockColor = colorMap.getColorMultiplier(); return true; } } public static boolean colorizeBlock(Block block, IBlockAccess blockAccess, int x, int y, int z) { IColorMap colorMap = findColorMap(block, blockAccess, x, y, z); return colorizeBlock(blockAccess, colorMap, x, y, z); } private static boolean colorizeBlock(IBlockAccess blockAccess, IColorMap colorMap, int x, int y, int z) { if (colorMap == null) { return false; } else { blockColor = colorMap.getColorMultiplier(blockAccess, x, y, z); return true; } } public static void computeWaterColor() { if (waterColorMap != null) { Colorizer.setColorF(waterColorMap.getColorMultiplier()); } } public static boolean computeWaterColor(boolean includeBaseColor, int x, int y, int z) { if (waterColorMap == null) { return false; } else { Colorizer.setColorF(waterColorMap.getColorMultiplierF(BiomeAPI.getWorld(), x, y, z)); if (includeBaseColor) { Colorizer.setColor[0] *= ColorizeEntity.waterBaseColor[0]; Colorizer.setColor[1] *= ColorizeEntity.waterBaseColor[1]; Colorizer.setColor[2] *= ColorizeEntity.waterBaseColor[2]; } return true; } } public static void colorizeWaterBlockGL(Block block) { if (block == Blocks.flowing_water || block == Blocks.water) { float[] waterColor; if (waterColorMap == null) { waterColor = ColorizeEntity.waterBaseColor; } else { waterColor = new float[3]; ColorUtils.intToFloat3(waterColorMap.getColorMultiplier(), waterColor); } GL11.glColor4f(waterColor[0], waterColor[1], waterColor[2], 1.0f); } } public static boolean computeRedstoneWireColor(int current) { if (redstoneColor == null) { return false; } else { System.arraycopy(redstoneColor[current & 0xf], 0, Colorizer.setColor, 0, 3); return true; } } public static int colorizeRedstoneWire(IBlockAccess blockAccess, int x, int y, int z, int defaultColor) { if (redstoneColor == null) { return defaultColor; } else { int metadata = Math.max(Math.min(blockAccess.getBlockMetadata(x, y, z), 15), 0); return ColorUtils.float3ToInt(redstoneColor[metadata]); } } private static float[] getVertexColor(IBlockAccess blockAccess, IColorMap colorMap, int x, int y, int z, int[] offsets) { if (enableTestColorSmoothing) { int rgb = 0; if ((x + offsets[0]) % 2 == 0) { rgb |= 0xff0000; } if ((y + offsets[1]) % 2 == 0) { rgb |= 0x00ff00; } if ((z + offsets[2]) % 2 == 0) { rgb |= 0x0000ff; } ColorUtils.intToFloat3(rgb, Colorizer.setColor); return Colorizer.setColor; } else { return colorMap.getColorMultiplierF(blockAccess, x + offsets[0], y + offsets[1], z + offsets[2]); } } // Called by asm @SuppressWarnings("unused") public static boolean setupBlockSmoothing(RenderBlocks renderBlocks, Block block, IBlockAccess blockAccess, int x, int y, int z, int face, float topLeft, float bottomLeft, float bottomRight, float topRight) { return RenderBlocksUtils.useColorMultiplier(face) && setupBiomeSmoothing( renderBlocks, block, blockAccess, x, y, z, face, true, topLeft, bottomLeft, bottomRight, topRight); } // TODO: remove @Deprecated public static boolean setupBlockSmoothingGrassSide(RenderBlocks renderBlocks, Block block, IBlockAccess blockAccess, int x, int y, int z, int face, float topLeft, float bottomLeft, float bottomRight, float topRight) { return checkBiomeSmoothing(block, face) && setupBiomeSmoothing( renderBlocks, block, blockAccess, x, y, z, face, true, topLeft, bottomLeft, bottomRight, topRight); } public static boolean setupBlockSmoothing(RenderBlocks renderBlocks, Block block, IBlockAccess blockAccess, int x, int y, int z, int face) { return checkBiomeSmoothing(block, face) && setupBiomeSmoothing(renderBlocks, block, blockAccess, x, y, z, face, true, 1.0f, 1.0f, 1.0f, 1.0f); } private static boolean checkBiomeSmoothing(Block block, int face) { return enableSmoothBiomes && face >= 0 && RenderBlocksUtils.isAmbientOcclusionEnabled() && block.getLightValue() == 0; } private static boolean setupBiomeSmoothing(RenderBlocks renderBlocks, Block block, IBlockAccess blockAccess, int x, int y, int z, int face, boolean useAO, float topLeft, float bottomLeft, float bottomRight, float topRight) { if (!setupBlockSmoothing(block, blockAccess, x, y, z, face)) { return false; } if (useAO) { float aoBase = RenderBlocksUtils.AO_BASE[face % 6]; topLeft *= aoBase; bottomLeft *= aoBase; bottomRight *= aoBase; topRight *= aoBase; } renderBlocks.colorRedTopLeft = topLeft * colorRedTopLeft; renderBlocks.colorGreenTopLeft = topLeft * colorGreenTopLeft; renderBlocks.colorBlueTopLeft = topLeft * colorBlueTopLeft; renderBlocks.colorRedBottomLeft = bottomLeft * colorRedBottomLeft; renderBlocks.colorGreenBottomLeft = bottomLeft * colorGreenBottomLeft; renderBlocks.colorBlueBottomLeft = bottomLeft * colorBlueBottomLeft; renderBlocks.colorRedBottomRight = bottomRight * colorRedBottomRight; renderBlocks.colorGreenBottomRight = bottomRight * colorGreenBottomRight; renderBlocks.colorBlueBottomRight = bottomRight * colorBlueBottomRight; renderBlocks.colorRedTopRight = topRight * colorRedTopRight; renderBlocks.colorGreenTopRight = topRight * colorGreenTopRight; renderBlocks.colorBlueTopRight = topRight * colorBlueTopRight; return true; } public static void setupBlockSmoothing(Block block, IBlockAccess blockAccess, int x, int y, int z, int face, float r, float g, float b) { if (!setupBlockSmoothing(block, blockAccess, x, y, z, face)) { setVertexColors(r, g, b); } } private static boolean setupBlockSmoothing(Block block, IBlockAccess blockAccess, int x, int y, int z, int face) { if (!checkBiomeSmoothing(block, face)) { return false; } IColorMap colorMap = findColorMap(block, blockAccess, x, y, z); if (colorMap == null) { return false; } int[][] offsets = FACE_VERTICES[face]; float[] color; color = getVertexColor(blockAccess, colorMap, x, y, z, offsets[0]); colorRedTopLeft = color[0]; colorGreenTopLeft = color[1]; colorBlueTopLeft = color[2]; color = getVertexColor(blockAccess, colorMap, x, y, z, offsets[1]); colorRedBottomLeft = color[0]; colorGreenBottomLeft = color[1]; colorBlueBottomLeft = color[2]; color = getVertexColor(blockAccess, colorMap, x, y, z, offsets[2]); colorRedBottomRight = color[0]; colorGreenBottomRight = color[1]; colorBlueBottomRight = color[2]; color = getVertexColor(blockAccess, colorMap, x, y, z, offsets[3]); colorRedTopRight = color[0]; colorGreenTopRight = color[1]; colorBlueTopRight = color[2]; return true; } private static void resetVertexColors() { setVertexColors(1.0f, 1.0f, 1.0f); } private static void setVertexColors(float r, float g, float b) { colorRedTopLeft = colorRedBottomLeft = colorRedBottomRight = colorRedTopRight = r; colorGreenTopLeft = colorGreenBottomLeft = colorGreenBottomRight = colorGreenTopRight = g; colorBlueTopLeft = colorBlueBottomLeft = colorBlueBottomRight = colorBlueTopRight = b; } }
Angelica
src\main\java\com\prupe\mcpatcher\cc\ColorizeEntity.java
package com.prupe.mcpatcher.cc; import java.util.Arrays; import java.util.Random; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.biome.BiomeAPI; import com.prupe.mcpatcher.mal.biome.ColorUtils; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; public class ColorizeEntity { private static final ResourceLocation LAVA_DROP_COLORS = TexturePackAPI .newMCPatcherResourceLocation("colormap/lavadrop.png"); private static final ResourceLocation MYCELIUM_COLORS = TexturePackAPI .newMCPatcherResourceLocation("colormap/myceliumparticle.png"); private static final ResourceLocation XPORB_COLORS = TexturePackAPI .newMCPatcherResourceLocation("colormap/xporb.png"); static float[] waterBaseColor; // particle.water private static float[] lavaDropColors; // misc/lavadropcolor.png public static float[] portalColor = new float[] { 1.0f, 0.3f, 0.9f }; private static final Random random = new Random(); private static int[] myceliumColors; private static int[] xpOrbColors; public static int xpOrbRed; public static int xpOrbGreen; public static int xpOrbBlue; private static final String[] colorNames = new String[] { "white", "orange", "magenta", "lightBlue", "yellow", "lime", "pink", "gray", "silver", "cyan", "purple", "blue", "brown", "green", "red", "black", }; private static final Integer[] dyeColors = new Integer[colorNames.length]; // dye.* private static final float[][] fleeceColors = new float[colorNames.length][]; // sheep.* private static final float[][] collarColors = new float[colorNames.length][]; // collar.* private static final float[][] armorColors = new float[colorNames.length][]; // armor.* public static int undyedLeatherColor; // armor.default static { try { reset(); } catch (Exception e) { e.printStackTrace(); } } static void reset() { waterBaseColor = new float[] { 0.2f, 0.3f, 1.0f }; portalColor = new float[] { 1.0f, 0.3f, 0.9f }; lavaDropColors = null; Arrays.fill(dyeColors, null); Arrays.fill(fleeceColors, null); Arrays.fill(collarColors, null); Arrays.fill(armorColors, null); undyedLeatherColor = 0xa06540; myceliumColors = null; xpOrbColors = null; } static void reloadParticleColors(PropertiesFile properties) { Colorizer.loadFloatColor("drop.water", waterBaseColor); Colorizer.loadFloatColor("particle.water", waterBaseColor); Colorizer.loadFloatColor("particle.portal", portalColor); int[] rgb = MCPatcherUtils.getImageRGB(TexturePackAPI.getImage(LAVA_DROP_COLORS)); if (rgb != null) { lavaDropColors = new float[3 * rgb.length]; for (int i = 0; i < rgb.length; i++) { ColorUtils.intToFloat3(rgb[i], lavaDropColors, 3 * i); } } myceliumColors = MCPatcherUtils.getImageRGB(TexturePackAPI.getImage(MYCELIUM_COLORS)); } static void reloadDyeColors(PropertiesFile properties) { for (int i = 0; i < colorNames.length; i++) { dyeColors[i] = Colorizer.loadIntegerColor("dye." + Colorizer.getStringKey(colorNames, i)); } for (int i = 0; i < colorNames.length; i++) { String key = Colorizer.getStringKey(colorNames, i); fleeceColors[i] = Colorizer.loadFloatColor("sheep." + key); collarColors[i] = Colorizer.loadFloatColor("collar." + key); armorColors[i] = Colorizer.loadFloatColor("armor." + key); } undyedLeatherColor = Colorizer.loadIntColor("armor.default", undyedLeatherColor); } static void reloadXPOrbColors(PropertiesFile properties) { xpOrbColors = MCPatcherUtils.getImageRGB(TexturePackAPI.getImage(XPORB_COLORS)); } public static int colorizeXPOrb(int origColor, float timer) { if (xpOrbColors == null || xpOrbColors.length == 0) { return origColor; } else { return xpOrbColors[(int) ((Math.sin(timer / 4.0) + 1.0) * (xpOrbColors.length - 1) / 2.0)]; } } public static int colorizeXPOrb(int origRed, int origBlue, float timer) { int color = colorizeXPOrb((origRed << 16) | 255 | origBlue, timer); xpOrbRed = (color >> 16) & 0xff; xpOrbGreen = (color >> 8) & 0xff; xpOrbBlue = color & 0xff; return xpOrbRed; } public static boolean computeLavaDropColor(int age) { if (lavaDropColors == null) { return false; } else { int offset = 3 * Math.max(Math.min(lavaDropColors.length / 3 - 1, age - 20), 0); System.arraycopy(lavaDropColors, offset, Colorizer.setColor, 0, 3); return true; } } public static boolean computeMyceliumParticleColor() { if (myceliumColors == null) { return false; } else { Colorizer.setColorF(myceliumColors[random.nextInt(myceliumColors.length)]); return true; } } public static void computeSuspendColor(int defaultColor, int i, int j, int k) { if (ColorizeWorld.underwaterColor != null) { defaultColor = ColorizeWorld.underwaterColor.getColorMultiplier(BiomeAPI.getWorld(), i, j, k); } Colorizer.setColorF(defaultColor); } public static float[] getWolfCollarColor(float[] rgb, int index) { return getArrayColor(collarColors, rgb, index); } public static float[] getArmorDyeColor(float[] rgb, int index) { return getArrayColor(armorColors, rgb, index); } private static float[] getArrayColor(float[][] array, float[] rgb, int index) { float[] newRGB = array[index]; return newRGB == null ? rgb : newRGB; } }
Angelica
src\main\java\com\prupe\mcpatcher\cc\ColorizeItem.java
package com.prupe.mcpatcher.cc; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.block.material.MapColor; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionHelper; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import jss.notfine.util.MapColorExpansion; import jss.notfine.util.PotionExpansion; public class ColorizeItem { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CUSTOM_COLORS); private static final Map<Integer, String> entityNamesByID = new HashMap<>(); private static final Map<Integer, Integer> spawnerEggShellColors = new HashMap<>(); // egg.shell.* private static final Map<Integer, Integer> spawnerEggSpotColors = new HashMap<>(); // egg.spots.* private static int waterBottleColor; // potion.water private static final List<Potion> potions = new ArrayList<>(); // potion.* private static boolean potionsInitialized; private static final String[] MAP_MATERIALS = new String[] { "air", "grass", "sand", "cloth", "tnt", "ice", "iron", "foliage", "snow", "clay", "dirt", "stone", "water", "wood", "quartz", "adobe", "magenta", "lightBlue", "yellow", "lime", "pink", "gray", "silver", "cyan", "purple", "blue", "brown", "green", "red", "black", "gold", "diamond", "lapis", "emerald", "obsidian", "netherrack", }; static { try { reset(); } catch (Exception e) { e.printStackTrace(); } } static void reset() { spawnerEggShellColors.clear(); spawnerEggSpotColors.clear(); // 1.5+btw: Calling PotionHelper on startup runs the static initializer which crashes because Potion class // hasn't finished initializing yet. if (potionsInitialized) { if (PotionHelper.field_77925_n != null) { PotionHelper.field_77925_n.clear(); } } potionsInitialized = true; waterBottleColor = 0x385dc6; for (Potion potion : potions) { potion.liquidColor = ((PotionExpansion) potion).getOrigColor(); } for (MapColor mapColor : MapColor.mapColorArray) { if (mapColor != null) { mapColor.colorValue = ((MapColorExpansion) mapColor).getOriginalColorValue(); } } } static void reloadPotionColors(PropertiesFile properties) { for (Potion potion : potions) { Colorizer.loadIntColor(potion.getName(), potion); } int[] temp = new int[] { waterBottleColor }; Colorizer.loadIntColor("potion.water", temp, 0); waterBottleColor = temp[0]; } static void reloadMapColors(PropertiesFile properties) { for (int i = 0; i < MapColor.mapColorArray.length; i++) { if (MapColor.mapColorArray[i] != null) { int[] rgb = new int[] { ((MapColorExpansion) MapColor.mapColorArray[i]).getOriginalColorValue() }; Colorizer.loadIntColor("map." + Colorizer.getStringKey(MAP_MATERIALS, i), rgb, 0); MapColor.mapColorArray[i].colorValue = rgb[0]; } } } public static void setupSpawnerEgg(String entityName, int entityID, int defaultShellColor, int defaultSpotColor) { logger.config("egg.shell.%s=%06x", entityName, defaultShellColor); logger.config("egg.spots.%s=%06x", entityName, defaultSpotColor); entityNamesByID.put(entityID, entityName); } public static void setupPotion(Potion potion) { ((PotionExpansion) potion).setOrigColor(potion.getLiquidColor()); potions.add(potion); } public static int colorizeSpawnerEgg(int defaultColor, int entityID, int spots) { if (!Colorizer.useEggColors) { return defaultColor; } Integer value = null; Map<Integer, Integer> eggMap = (spots == 0 ? spawnerEggShellColors : spawnerEggSpotColors); if (eggMap.containsKey(entityID)) { value = eggMap.get(entityID); } else if (entityNamesByID.containsKey(entityID)) { String name = entityNamesByID.get(entityID); if (name != null) { int[] tmp = new int[] { defaultColor }; Colorizer.loadIntColor((spots == 0 ? "egg.shell." : "egg.spots.") + name, tmp, 0); eggMap.put(entityID, tmp[0]); value = tmp[0]; } } return value == null ? defaultColor : value; } public static int getWaterBottleColor() { return waterBottleColor; } }
Angelica
src\main\java\com\prupe\mcpatcher\cc\Colorizer.java
package com.prupe.mcpatcher.cc; import net.minecraft.potion.Potion; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.biome.ColorMap; import com.prupe.mcpatcher.mal.biome.ColorUtils; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.resource.TexturePackChangeHandler; import jss.notfine.config.MCPatcherForgeConfig; public class Colorizer { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CUSTOM_COLORS); static final ResourceLocation COLOR_PROPERTIES = TexturePackAPI.newMCPatcherResourceLocation("color.properties"); private static PropertiesFile properties; static final boolean usePotionColors = MCPatcherForgeConfig.CustomColors.potion; static final boolean useParticleColors = MCPatcherForgeConfig.CustomColors.particle; static final boolean useFogColors = MCPatcherForgeConfig.CustomColors.fog; static final boolean useCloudType = MCPatcherForgeConfig.CustomColors.clouds; static final boolean useMapColors = MCPatcherForgeConfig.CustomColors.map; static final boolean useDyeColors = MCPatcherForgeConfig.CustomColors.dye; static final boolean useTextColors = MCPatcherForgeConfig.CustomColors.text; static final boolean useXPOrbColors = MCPatcherForgeConfig.CustomColors.xporb; static final boolean useEggColors = MCPatcherForgeConfig.CustomColors.egg; public static final float[] setColor = new float[3]; static { try { reset(); } catch (Exception e) { e.printStackTrace(); } TexturePackChangeHandler.register(new TexturePackChangeHandler(MCPatcherUtils.CUSTOM_COLORS, 2) { @Override public void beforeChange() { reset(); } @Override public void afterChange() { reloadColorProperties(); ColorMap.reloadColorMapSettings(properties); if (useParticleColors) { ColorizeEntity.reloadParticleColors(properties); } ColorizeBlock.reloadAll(properties); if (useFogColors) { ColorizeWorld.reloadFogColors(properties); } if (usePotionColors) { ColorizeItem.reloadPotionColors(properties); } if (useCloudType) { ColorizeWorld.reloadCloudType(properties); } if (useMapColors) { ColorizeItem.reloadMapColors(properties); } if (useDyeColors) { ColorizeEntity.reloadDyeColors(properties); } if (useTextColors) { ColorizeWorld.reloadTextColors(properties); } if (useXPOrbColors) { ColorizeEntity.reloadXPOrbColors(properties); } } }); } public static void setColorF(int color) { ColorUtils.intToFloat3(color, setColor); } static void setColorF(float[] color) { setColor[0] = color[0]; setColor[1] = color[1]; setColor[2] = color[2]; } public static void init() {} private static void reset() { properties = new PropertiesFile(logger, COLOR_PROPERTIES); ColorMap.reset(); ColorizeBlock.reset(); Lightmap.reset(); ColorizeItem.reset(); ColorizeWorld.reset(); ColorizeEntity.reset(); } private static void reloadColorProperties() { properties = PropertiesFile.getNonNull(logger, COLOR_PROPERTIES); logger.finer("reloading %s", properties); } static String getStringKey(String[] keys, int index) { if (keys != null && index >= 0 && index < keys.length && keys[index] != null) { return keys[index]; } else { return "" + index; } } static void loadIntColor(String key, Potion potion) { potion.liquidColor = loadIntColor(key, potion.getLiquidColor()); } static boolean loadIntColor(String key, int[] color, int index) { logger.config("%s=%06x", key, color[index]); String value = properties.getString(key, ""); if (!value.isEmpty()) { try { color[index] = Integer.parseInt(value, 16); return true; } catch (NumberFormatException e) {} } return false; } static int loadIntColor(String key, int color) { logger.config("%s=%06x", key, color); return properties.getHex(key, color); } static void loadFloatColor(String key, float[] color) { int intColor = ColorUtils.float3ToInt(color); ColorUtils.intToFloat3(loadIntColor(key, intColor), color); } static Integer loadIntegerColor(String key) { int[] tmp = new int[1]; if (loadIntColor(key, tmp, 0)) { return tmp[0]; } else { return null; } } static float[] loadFloatColor(String key) { Integer color = loadIntegerColor(key); if (color == null) { return null; } else { float[] rgb = new float[3]; ColorUtils.intToFloat3(color, rgb); return rgb; } } }
Angelica
src\main\java\com\prupe\mcpatcher\cc\ColorizeWorld.java
package com.prupe.mcpatcher.cc; import static com.prupe.mcpatcher.cc.Colorizer.loadFloatColor; import static com.prupe.mcpatcher.cc.Colorizer.loadIntColor; import static com.prupe.mcpatcher.cc.Colorizer.setColor; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.WorldProvider; import com.prupe.mcpatcher.mal.biome.BiomeAPI; import com.prupe.mcpatcher.mal.biome.ColorMap; import com.prupe.mcpatcher.mal.biome.ColorMapBase; import com.prupe.mcpatcher.mal.biome.ColorUtils; import com.prupe.mcpatcher.mal.biome.IColorMap; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import jss.notfine.config.MCPatcherForgeConfig; public class ColorizeWorld { private static final int fogBlendRadius = MCPatcherForgeConfig.CustomColors.fogBlendRadius; private static final ResourceLocation UNDERWATERCOLOR = TexturePackAPI .newMCPatcherResourceLocation("colormap/underwater.png"); private static final ResourceLocation UNDERLAVACOLOR = TexturePackAPI .newMCPatcherResourceLocation("colormap/underlava.png"); private static final ResourceLocation FOGCOLOR0 = TexturePackAPI.newMCPatcherResourceLocation("colormap/fog0.png"); private static final ResourceLocation SKYCOLOR0 = TexturePackAPI.newMCPatcherResourceLocation("colormap/sky0.png"); private static final String TEXT_KEY = "text."; private static final String TEXT_CODE_KEY = TEXT_KEY + "code."; private static final int CLOUDS_DEFAULT = -1; private static final int CLOUDS_NONE = 0; private static final int CLOUDS_FAST = 1; private static final int CLOUDS_FANCY = 2; private static int cloudType = CLOUDS_DEFAULT; private static Entity fogCamera; private static final Map<Integer, Integer> textColorMap = new HashMap<>(); // text.* private static final int[] textCodeColors = new int[32]; // text.code.* private static final boolean[] textCodeColorSet = new boolean[32]; private static int signTextColor; // text.sign static IColorMap underwaterColor; private static IColorMap underlavaColor; private static IColorMap fogColorMap; private static IColorMap skyColorMap; public static float[] netherFogColor; public static float[] endFogColor; public static int endSkyColor; static { try { reset(); } catch (Exception e) { e.printStackTrace(); } } static void reset() { underwaterColor = null; underlavaColor = null; fogColorMap = null; skyColorMap = null; netherFogColor = new float[] { 0.2f, 0.03f, 0.03f }; endFogColor = new float[] { 0.075f, 0.075f, 0.094f }; endSkyColor = 0x181818; cloudType = CLOUDS_DEFAULT; textColorMap.clear(); Arrays.fill(textCodeColorSet, false); signTextColor = 0; } static void reloadFogColors(PropertiesFile properties) { underwaterColor = wrapFogMap(ColorMap.loadFixedColorMap(Colorizer.useFogColors, UNDERWATERCOLOR)); underlavaColor = wrapFogMap(ColorMap.loadFixedColorMap(Colorizer.useFogColors, UNDERLAVACOLOR)); fogColorMap = wrapFogMap(ColorMap.loadFixedColorMap(Colorizer.useFogColors, FOGCOLOR0)); skyColorMap = wrapFogMap(ColorMap.loadFixedColorMap(Colorizer.useFogColors, SKYCOLOR0)); loadFloatColor("fog.nether", netherFogColor); loadFloatColor("fog.end", endFogColor); endSkyColor = loadIntColor("sky.end", endSkyColor); } static IColorMap wrapFogMap(IColorMap map) { if (map == null) { return null; } else { if (fogBlendRadius > 0) { map = new ColorMapBase.Blended(map, fogBlendRadius); } map = new ColorMapBase.Cached(map); map = new ColorMapBase.Smoothed(map, 3000.0f); map = new ColorMapBase.Outer(map); return map; } } static void reloadCloudType(PropertiesFile properties) { String value = properties.getString("clouds", "") .toLowerCase(); switch (value) { case "fast" -> cloudType = CLOUDS_FAST; case "fancy" -> cloudType = CLOUDS_FANCY; case "none" -> cloudType = CLOUDS_NONE; } } static void reloadTextColors(PropertiesFile properties) { for (int i = 0; i < textCodeColors.length; i++) { textCodeColorSet[i] = loadIntColor(TEXT_CODE_KEY + i, textCodeColors, i); if (textCodeColorSet[i] && i + 16 < textCodeColors.length) { textCodeColors[i + 16] = (textCodeColors[i] & 0xfcfcfc) >> 2; textCodeColorSet[i + 16] = true; } } for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (!key.startsWith(TEXT_KEY) || key.startsWith(TEXT_CODE_KEY)) { continue; } key = key.substring(TEXT_KEY.length()) .trim(); try { int newColor; int oldColor; if (key.equals("xpbar")) { oldColor = 0x80ff20; } else if (key.equals("boss")) { oldColor = 0xff00ff; } else { oldColor = Integer.parseInt(key, 16); } newColor = Integer.parseInt(value, 16); textColorMap.put(oldColor, newColor); } catch (NumberFormatException e) {} } signTextColor = loadIntColor("text.sign", 0); } public static void setupForFog(Entity entity) { fogCamera = entity; } private static boolean computeFogColor(IBlockAccess blockAccess, IColorMap colorMap) { if (colorMap == null || fogCamera == null) { return false; } else { int i = (int) fogCamera.posX; int j = (int) fogCamera.posY; int k = (int) fogCamera.posZ; Colorizer.setColorF(colorMap.getColorMultiplierF(blockAccess, i, j, k)); return true; } } public static boolean computeFogColor(WorldProvider worldProvider, float f) { return worldProvider.dimensionId == 0 && computeFogColor(worldProvider.worldObj, fogColorMap); } public static boolean computeSkyColor(World world, float f) { if (world.provider.dimensionId == 0 && computeFogColor(world, skyColorMap)) { computeLightningFlash(world, f); return true; } else { return false; } } public static boolean computeUnderwaterColor() { return computeFogColor(BiomeAPI.getWorld(), underwaterColor); } public static boolean computeUnderlavaColor() { return computeFogColor(BiomeAPI.getWorld(), underlavaColor); } private static void computeLightningFlash(World world, float f) { if (world.lastLightningBolt > 0) { f = 0.45f * ColorUtils.clamp(world.lastLightningBolt - f); setColor[0] = setColor[0] * (1.0f - f) + 0.8f * f; setColor[1] = setColor[1] * (1.0f - f) + 0.8f * f; setColor[2] = setColor[2] * (1.0f - f) + 0.8f * f; } } public static boolean drawFancyClouds(boolean fancyGraphics) { return switch (cloudType) { case CLOUDS_NONE, CLOUDS_FAST -> false; case CLOUDS_FANCY -> true; default -> fancyGraphics; }; } public static int colorizeText(int defaultColor) { int high = defaultColor & 0xff000000; defaultColor &= 0xffffff; Integer newColor = textColorMap.get(defaultColor); if (newColor == null) { return high | defaultColor; } else { return high | newColor; } } public static int colorizeText(int defaultColor, int index) { if (index < 0 || index >= textCodeColors.length || !textCodeColorSet[index]) { return defaultColor; } else { return (defaultColor & 0xff000000) | textCodeColors[index]; } } public static int colorizeSignText() { return signTextColor; } }
Angelica
src\main\java\com\prupe\mcpatcher\cc\Lightmap.java
package com.prupe.mcpatcher.cc; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.potion.Potion; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.mal.biome.ColorUtils; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import jss.notfine.config.MCPatcherForgeConfig; public final class Lightmap { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CUSTOM_COLORS); private static final String LIGHTMAP_FORMAT = "lightmap/world%d.png"; private static final int LIGHTMAP_SIZE = 16; private static final int HEIGHT_WITHOUT_NIGHTVISION = 2 * LIGHTMAP_SIZE; private static final int HEIGHT_WITH_NIGHTVISION = 4 * LIGHTMAP_SIZE; private static final boolean useLightmaps = MCPatcherForgeConfig.CustomColors.lightmaps; private static final Map<Integer, Lightmap> lightmaps = new HashMap<>(); private final int width; private final boolean customNightvision; private final int[] origMap; private final boolean valid; private final float[] sunrgb = new float[3 * LIGHTMAP_SIZE]; private final float[] torchrgb = new float[3 * LIGHTMAP_SIZE]; private final float[] sunrgbnv = new float[3 * LIGHTMAP_SIZE]; private final float[] torchrgbnv = new float[3 * LIGHTMAP_SIZE]; private final float[] rgb = new float[3]; static void reset() { lightmaps.clear(); } public static boolean computeLightmap(EntityRenderer renderer, World world, int[] mapRGB, float partialTick) { if (world == null || !useLightmaps) { return false; } Lightmap lightmap = null; int worldType = world.provider.dimensionId; if (lightmaps.containsKey(worldType)) { lightmap = lightmaps.get(worldType); } else { ResourceLocation resource = TexturePackAPI .newMCPatcherResourceLocation(String.format(LIGHTMAP_FORMAT, worldType)); BufferedImage image = TexturePackAPI.getImage(resource); if (image != null) { lightmap = new Lightmap(resource, image); if (!lightmap.valid) { lightmap = null; } } lightmaps.put(worldType, lightmap); } return lightmap != null && lightmap.compute(renderer, world, mapRGB, partialTick); } private Lightmap(ResourceLocation resource, BufferedImage image) { width = image.getWidth(); int height = image.getHeight(); customNightvision = (height == HEIGHT_WITH_NIGHTVISION); origMap = new int[width * height]; image.getRGB(0, 0, width, height, origMap, 0, width); valid = (height == HEIGHT_WITHOUT_NIGHTVISION || height == HEIGHT_WITH_NIGHTVISION); if (!valid) { logger.error( "%s must be exactly %d or %d pixels high", resource, HEIGHT_WITHOUT_NIGHTVISION, HEIGHT_WITH_NIGHTVISION); } } private float getNightVisionStrength(EntityRenderer renderer, float n) { if (Minecraft.getMinecraft().thePlayer.isPotionActive(Potion.nightVision)) { return ((EntityRendererAccessor) renderer).invokeGetNightVisionBrightness(Minecraft.getMinecraft().thePlayer, n); } return 0.0f; } private boolean compute(EntityRenderer renderer, World world, int[] mapRGB, float partialTick) { float sun = ColorUtils.clamp( world.lastLightningBolt > 0 ? 1.0f : 7.0f / 6.0f * (world.getSunBrightness(1.0f) - 0.2f)) * (width - 1); float torch = ColorUtils.clamp(renderer.torchFlickerX + 0.5f) * (width - 1); float nightVisionStrength = getNightVisionStrength(renderer, partialTick); float gamma = ColorUtils.clamp(Minecraft.getMinecraft().gameSettings.gammaSetting); for (int i = 0; i < LIGHTMAP_SIZE; i++) { interpolate(origMap, i * width, sun, sunrgb, 3 * i); interpolate(origMap, (i + LIGHTMAP_SIZE) * width, torch, torchrgb, 3 * i); if (customNightvision && nightVisionStrength > 0.0f) { interpolate(origMap, (i + 2 * LIGHTMAP_SIZE) * width, sun, sunrgbnv, 3 * i); interpolate(origMap, (i + 3 * LIGHTMAP_SIZE) * width, torch, torchrgbnv, 3 * i); } } for (int s = 0; s < LIGHTMAP_SIZE; s++) { for (int t = 0; t < LIGHTMAP_SIZE; t++) { for (int k = 0; k < 3; k++) { rgb[k] = ColorUtils.clamp(sunrgb[3 * s + k] + torchrgb[3 * t + k]); } if (nightVisionStrength > 0.0f) { if (customNightvision) { for (int k = 0; k < 3; k++) { rgb[k] = ColorUtils.clamp( (1.0f - nightVisionStrength) * rgb[k] + nightVisionStrength * (sunrgbnv[3 * s + k] + torchrgbnv[3 * t + k])); } } else { float nightVisionMultiplier = Math.max(Math.max(rgb[0], rgb[1]), rgb[2]); if (nightVisionMultiplier > 0.0f) { nightVisionMultiplier = (1.0f - nightVisionStrength) + nightVisionStrength / nightVisionMultiplier; for (int k = 0; k < 3; k++) { rgb[k] = ColorUtils.clamp(rgb[k] * nightVisionMultiplier); } } } } if (gamma != 0.0f) { for (int k = 0; k < 3; k++) { float tmp = 1.0f - rgb[k]; tmp = 1.0f - tmp * tmp * tmp * tmp; rgb[k] = gamma * tmp + (1.0f - gamma) * rgb[k]; } } mapRGB[s * LIGHTMAP_SIZE + t] = 0xff000000 | ColorUtils.float3ToInt(rgb); } } return true; } private static void interpolate(int[] map, int offset1, float x, float[] rgb, int offset2) { int x0 = (int) Math.floor(x); int x1 = (int) Math.ceil(x); if (x0 == x1) { ColorUtils.intToFloat3(map[offset1 + x0], rgb, offset2); } else { float xf = x - x0; float xg = 1.0f - xf; float[] rgb0 = new float[3]; float[] rgb1 = new float[3]; ColorUtils.intToFloat3(map[offset1 + x0], rgb0); ColorUtils.intToFloat3(map[offset1 + x1], rgb1); for (int i = 0; i < 3; i++) { rgb[offset2 + i] = xg * rgb0[i] + xf * rgb1[i]; } } } }
Angelica
src\main\java\com\prupe\mcpatcher\cit\ArmorOverride.java
package com.prupe.mcpatcher.cit; import java.util.HashMap; import java.util.Map; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; final class ArmorOverride extends OverrideBase { private final Map<ResourceLocation, ResourceLocation> armorMap; ArmorOverride(PropertiesFile properties) { super(properties); if (items == null) { properties.error("no matching items specified"); } if (textureName == null && alternateTextures == null) { properties.error("no replacement textures specified"); } if (alternateTextures == null) { armorMap = null; } else { armorMap = new HashMap<>(); for (Map.Entry<String, ResourceLocation> entry : alternateTextures.entrySet()) { String key = entry.getKey(); ResourceLocation value = entry.getValue(); armorMap.put(TexturePackAPI.parseResourceLocation(CITUtils.FIXED_ARMOR_RESOURCE, key), value); } } } @Override String getType() { return "armor"; } ResourceLocation getReplacementTexture(ResourceLocation origResource) { if (armorMap != null) { ResourceLocation newResource = armorMap.get(origResource); if (newResource != null) { return newResource; } } return textureName; } @Override String preprocessAltTextureKey(String name) { if (!name.endsWith(".png")) { name += ".png"; } if (!name.contains("/")) { name = "./" + name; } return TexturePackAPI.parseResourceLocation(CITUtils.FIXED_ARMOR_RESOURCE, name) .toString(); } }
Angelica
src\main\java\com\prupe\mcpatcher\cit\CITUtils.java
package com.prupe.mcpatcher.cit; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.projectile.EntityPotion; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.item.ItemAPI; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.ResourceList; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.resource.TexturePackChangeHandler; import com.prupe.mcpatcher.mal.tile.TileLoader; import jss.notfine.config.MCPatcherForgeConfig; import jss.notfine.util.NBTTagListExpansion; public class CITUtils { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CUSTOM_ITEM_TEXTURES, "CIT"); static final String CIT_PROPERTIES = "cit.properties"; private static final ResourceLocation CIT_PROPERTIES1 = TexturePackAPI.newMCPatcherResourceLocation(CIT_PROPERTIES); private static final ResourceLocation CIT_PROPERTIES2 = TexturePackAPI .newMCPatcherResourceLocation("cit/" + CIT_PROPERTIES); static final ResourceLocation FIXED_ARMOR_RESOURCE = new ResourceLocation("textures/models/armor/iron_layer_1.png"); static final int MAX_ENCHANTMENTS = 256; private static Item itemEnchantedBook; static Item itemCompass; static Item itemClock; static final boolean enableItems = MCPatcherForgeConfig.CustomItemTextures.items; static final boolean enableEnchantments = MCPatcherForgeConfig.CustomItemTextures.enchantments; static final boolean enableArmor = MCPatcherForgeConfig.CustomItemTextures.armor; private static TileLoader tileLoader; private static final Map<Item, List<ItemOverride>> items = new IdentityHashMap<>(); private static final Map<Item, List<Enchantment>> enchantments = new IdentityHashMap<>(); private static final List<Enchantment> allItemEnchantments = new ArrayList<>(); private static final Map<Item, List<ArmorOverride>> armors = new IdentityHashMap<>(); static boolean useGlint; private static EnchantmentList armorMatches; private static int armorMatchIndex; private static ItemStack lastItemStack; private static int lastRenderPass; static IIcon lastOrigIcon; private static IIcon lastIcon; public static void init() { TexturePackChangeHandler.register(new TexturePackChangeHandler(MCPatcherUtils.CUSTOM_ITEM_TEXTURES, 3) { @Override public void beforeChange() { itemEnchantedBook = ItemAPI.getFixedItem("minecraft:enchanted_book"); itemCompass = ItemAPI.getFixedItem("minecraft:compass"); itemClock = ItemAPI.getFixedItem("minecraft:clock"); tileLoader = new TileLoader("textures/items", logger); items.clear(); enchantments.clear(); allItemEnchantments.clear(); armors.clear(); lastOrigIcon = null; lastIcon = null; BufferedImage image = TexturePackAPI.getImage(FIXED_ARMOR_RESOURCE); if (image == null) { Enchantment.baseArmorWidth = 64.0f; Enchantment.baseArmorHeight = 32.0f; } else { Enchantment.baseArmorWidth = image.getWidth(); Enchantment.baseArmorHeight = image.getHeight(); } PropertiesFile properties = PropertiesFile.get(logger, CIT_PROPERTIES1); if (properties == null) { properties = PropertiesFile.getNonNull(logger, CIT_PROPERTIES2); } useGlint = properties.getBoolean("useGlint", true); EnchantmentList.setProperties(properties); if (enableItems || enableEnchantments || enableArmor) { for (ResourceLocation resource : ResourceList.getInstance() .listResources(TexturePackAPI.MCPATCHER_SUBDIR + "cit", ".properties", true)) { registerOverride(OverrideBase.create(resource)); } if (enableItems) { PotionReplacer replacer = new PotionReplacer(); for (ItemOverride override : replacer.overrides) { registerOverride(override); } } } } @Override public void afterChange() { for (List<ItemOverride> list : items.values()) { for (ItemOverride override : list) { override.registerIcon(tileLoader); } Collections.sort(list); } for (List<Enchantment> list : enchantments.values()) { list.addAll(allItemEnchantments); Collections.sort(list); } Collections.sort(allItemEnchantments); for (List<ArmorOverride> list : armors.values()) { Collections.sort(list); } } @SuppressWarnings("unchecked") private void registerOverride(OverrideBase override) { if (override != null && override.properties.valid()) { Map<?, ?> map; if (override instanceof ItemOverride) { ((ItemOverride) override).preload(tileLoader); map = items; } else if (override instanceof Enchantment) { map = enchantments; } else if (override instanceof ArmorOverride) { map = armors; } else { logger.severe( "unknown ItemOverride type %d", override.getClass() .getName()); return; } if (override.items == null) { if (override instanceof Enchantment) { logger.fine("registered %s to all items", override); allItemEnchantments.add((Enchantment) override); } } else { int i = 0; for (Item item : override.items) { registerOverride((Map<Item, List<OverrideBase>>) map, item, override); if (i < 10) { logger.fine("registered %s to item %s", override, ItemAPI.getItemName(item)); } else if (i == 10) { logger.fine("... %d total", override.items.size()); } i++; } } } } private void registerOverride(Map<Item, List<OverrideBase>> map, Item item, OverrideBase override) { List<OverrideBase> list = map.computeIfAbsent(item, k -> new ArrayList<>()); list.add(override); } }); } public static IIcon getIcon(IIcon icon, ItemStack itemStack, int renderPass) { if (icon == lastIcon && itemStack == lastItemStack && renderPass == lastRenderPass) { return icon; } lastOrigIcon = lastIcon = icon; lastItemStack = itemStack; lastRenderPass = renderPass; if (enableItems) { ItemOverride override = findItemOverride(itemStack); if (override != null) { IIcon newIcon = override.getReplacementIcon(icon); if (newIcon != null) { lastIcon = newIcon; } } } return lastIcon; } public static IIcon getEntityIcon(IIcon icon, Entity entity) { if (entity instanceof EntityPotion potion) { return getIcon(icon, potion.potionDamage, 1); } return icon; } public static ResourceLocation getArmorTexture(ResourceLocation texture, EntityLivingBase entity, ItemStack itemStack) { if (enableArmor) { ArmorOverride override = findArmorOverride(itemStack); if (override != null) { ResourceLocation newTexture = override.getReplacementTexture(texture); if (newTexture != null) { return newTexture; } } } return texture; } private static <T extends OverrideBase> T findMatch(Map<Item, List<T>> overrides, ItemStack itemStack) { Item item = itemStack.getItem(); List<T> list = overrides.get(item); if (list != null) { int[] enchantmentLevels = getEnchantmentLevels(item, itemStack.getTagCompound()); boolean hasEffect = itemStack.hasEffect(0); for (T override : list) { if (override.match(itemStack, enchantmentLevels, hasEffect)) { return override; } } } return null; } static ItemOverride findItemOverride(ItemStack itemStack) { return findMatch(items, itemStack); } static ArmorOverride findArmorOverride(ItemStack itemStack) { return findMatch(armors, itemStack); } static EnchantmentList findEnchantments(ItemStack itemStack) { return new EnchantmentList(enchantments, allItemEnchantments, itemStack); } public static boolean renderEnchantmentHeld(ItemStack itemStack, int renderPass) { if (itemStack == null || renderPass != 0) { return true; } if (!enableEnchantments) { return false; } EnchantmentList matches = findEnchantments(itemStack); if (matches.isEmpty()) { return !useGlint; } int width; int height; if (lastIcon == null) { width = height = 256; } else { width = lastIcon.getIconWidth(); height = lastIcon.getIconHeight(); } Enchantment.beginOuter3D(); for (int i = 0; i < matches.size(); i++) { matches.getEnchantment(i) .render3D(matches.getIntensity(i), width, height); } Enchantment.endOuter3D(); return !useGlint; } public static boolean renderEnchantmentDropped(ItemStack itemStack) { return renderEnchantmentHeld(itemStack, lastRenderPass); } public static boolean renderEnchantmentGUI(ItemStack itemStack, int x, int y, float z) { if (!enableEnchantments || itemStack == null) { return false; } EnchantmentList matches = findEnchantments(itemStack); if (matches.isEmpty()) { return !useGlint; } Enchantment.beginOuter2D(); for (int i = 0; i < matches.size(); i++) { matches.getEnchantment(i) .render2D(matches.getIntensity(i), x, y, x + 16, y + 16, z); } Enchantment.endOuter2D(); return !useGlint; } public static boolean setupArmorEnchantments(EntityLivingBase entity, int pass) { return setupArmorEnchantments(entity.getEquipmentInSlot(4 - pass)); } public static boolean setupArmorEnchantments(ItemStack itemStack) { armorMatches = null; armorMatchIndex = 0; if (enableEnchantments && itemStack != null) { EnchantmentList tmpList = findEnchantments(itemStack); if (!tmpList.isEmpty()) { armorMatches = tmpList; } } return isArmorEnchantmentActive() || !useGlint; } public static boolean preRenderArmorEnchantment() { if (isArmorEnchantmentActive()) { Enchantment enchantment = armorMatches.getEnchantment(armorMatchIndex); if (enchantment.bindTexture(lastOrigIcon)) { enchantment.beginArmor(armorMatches.getIntensity(armorMatchIndex)); return true; } else { return false; } } else { armorMatches = null; armorMatchIndex = 0; return false; } } public static boolean isArmorEnchantmentActive() { return armorMatches != null && armorMatchIndex < armorMatches.size(); } public static void postRenderArmorEnchantment() { armorMatches.getEnchantment(armorMatchIndex) .endArmor(); armorMatchIndex++; } static int[] getEnchantmentLevels(Item item, NBTTagCompound nbt) { int[] levels = null; if (nbt != null) { NBTBase base; if (item == itemEnchantedBook) { base = nbt.getTag("StoredEnchantments"); } else { base = nbt.getTag("ench"); } if (base instanceof NBTTagList list) { for (int i = 0; i < list.tagCount(); i++) { base = ((NBTTagListExpansion) list).tagAt(i); if (base instanceof NBTTagCompound) { short id = ((NBTTagCompound) base).getShort("id"); short level = ((NBTTagCompound) base).getShort("lvl"); if (id >= 0 && id < MAX_ENCHANTMENTS && level > 0) { if (levels == null) { levels = new int[MAX_ENCHANTMENTS]; } levels[id] += level; } } } } } return levels; } }
Angelica
src\main\java\com\prupe\mcpatcher\cit\Enchantment.java
package com.prupe.mcpatcher.cit; import java.awt.image.BufferedImage; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import com.prupe.mcpatcher.mal.resource.BlendMethod; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; final class Enchantment extends OverrideBase { private static final float ITEM_2D_THICKNESS = 0.0625f; static float baseArmorWidth; static float baseArmorHeight; private static boolean lightingWasEnabled; final int layer; final BlendMethod blendMethod; private final float rotation; private final double speed; final float duration; private boolean armorScaleSet; private float armorScaleX; private float armorScaleY; static void beginOuter2D() { GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glAlphaFunc(GL11.GL_GREATER, 0.01f); GL11.glEnable(GL11.GL_BLEND); GL11.glDepthFunc(GL11.GL_EQUAL); GL11.glDepthMask(false); GL11.glDisable(GL11.GL_LIGHTING); GL11.glMatrixMode(GL11.GL_TEXTURE); } static void endOuter2D() { GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GL11.glDisable(GL11.GL_BLEND); GL11.glDepthFunc(GL11.GL_LEQUAL); GL11.glDepthMask(true); GL11.glEnable(GL11.GL_LIGHTING); GL11.glMatrixMode(GL11.GL_MODELVIEW); } static void beginOuter3D() { GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glAlphaFunc(GL11.GL_GREATER, 0.01f); GL11.glEnable(GL11.GL_BLEND); GL11.glDepthFunc(GL11.GL_EQUAL); lightingWasEnabled = GL11.glGetBoolean(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_LIGHTING); GL11.glMatrixMode(GL11.GL_TEXTURE); } static void endOuter3D() { GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GL11.glDisable(GL11.GL_BLEND); GL11.glDepthFunc(GL11.GL_LEQUAL); if (lightingWasEnabled) { GL11.glEnable(GL11.GL_LIGHTING); } GL11.glMatrixMode(GL11.GL_MODELVIEW); } Enchantment(PropertiesFile properties) { super(properties); if (properties.valid() && textureName == null && alternateTextures == null) { properties.error("no source texture specified"); } layer = properties.getInt("layer", 0); String value = properties.getString("blend", "add"); blendMethod = BlendMethod.parse(value); if (blendMethod == null) { properties.error("unknown blend type %s", value); } rotation = properties.getFloat("rotation", 0.0f); speed = properties.getDouble("speed", 0.0); duration = properties.getFloat("duration", 1.0f); String valueX = properties.getString("armorScaleX", ""); String valueY = properties.getString("armorScaleY", ""); if (!valueX.isEmpty() && !valueY.isEmpty()) { try { armorScaleX = Float.parseFloat(valueX); armorScaleY = Float.parseFloat(valueY); armorScaleSet = true; } catch (NumberFormatException e) { e.printStackTrace(); } } } @Override String getType() { return "enchantment"; } void render2D(float intensity, float x0, float y0, float x1, float y1, float z) { if (intensity <= 0.0f) { return; } if (intensity > 1.0f) { intensity = 1.0f; } if (!bindTexture(CITUtils.lastOrigIcon)) { return; } begin(intensity); final Tessellator tess = Tessellator.instance; tess.startDrawingQuads(); tess.addVertexWithUV(x0, y0, z, 0.0f, 0.0f); tess.addVertexWithUV(x0, y1, z, 0.0f, 1.0f); tess.addVertexWithUV(x1, y1, z, 1.0f, 1.0f); tess.addVertexWithUV(x1, y0, z, 1.0f, 0.0f); tess.draw(); end(); } void render3D(float intensity, int width, int height) { if (intensity <= 0.0f) { return; } if (intensity > 1.0f) { intensity = 1.0f; } if (!bindTexture(CITUtils.lastOrigIcon)) { return; } begin(intensity); ItemRenderer.renderItemIn2D(Tessellator.instance, 1.0f, 0.0f, 0.0f, 1.0f, width, height, ITEM_2D_THICKNESS); end(); } boolean bindTexture(IIcon icon) { ResourceLocation texture; if (alternateTextures != null && icon != null) { texture = alternateTextures.get(icon.getIconName()); if (texture == null) { texture = textureName; } } else { texture = textureName; } if (texture == null) { return false; } else { TexturePackAPI.bindTexture(texture); return true; } } void beginArmor(float intensity) { GL11.glEnable(GL11.GL_BLEND); GL11.glDepthFunc(GL11.GL_EQUAL); GL11.glDepthMask(false); GL11.glDisable(GL11.GL_LIGHTING); GL11.glMatrixMode(GL11.GL_TEXTURE); begin(intensity); if (!armorScaleSet) { setArmorScale(); } GL11.glScalef(armorScaleX, armorScaleY, 1.0f); GL11.glMatrixMode(GL11.GL_MODELVIEW); } void endArmor() { GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GL11.glDisable(GL11.GL_BLEND); GL11.glDepthFunc(GL11.GL_LEQUAL); GL11.glDepthMask(true); GL11.glEnable(GL11.GL_LIGHTING); GL11.glMatrixMode(GL11.GL_TEXTURE); end(); GL11.glLoadIdentity(); GL11.glMatrixMode(GL11.GL_MODELVIEW); } void begin(float intensity) { blendMethod.applyBlending(); blendMethod.applyDepthFunc(); blendMethod.applyFade(intensity); GL11.glPushMatrix(); if (speed != 0.0) { double offset = ((double) System.currentTimeMillis() * speed) / 3000.0; offset -= Math.floor(offset); GL11.glTranslatef((float) offset * 8.0f, 0.0f, 0.0f); } GL11.glRotatef(rotation, 0.0f, 0.0f, 1.0f); } void end() { GL11.glPopMatrix(); } private void setArmorScale() { armorScaleSet = true; armorScaleX = 1.0f; armorScaleY = 0.5f; BufferedImage overlayImage = TexturePackAPI.getImage(textureName); if (overlayImage != null) { if (overlayImage.getWidth() < baseArmorWidth) { armorScaleX *= baseArmorWidth / (float) overlayImage.getWidth(); } if (overlayImage.getHeight() < baseArmorHeight) { armorScaleY *= baseArmorHeight / (float) overlayImage.getHeight(); } } logger.finer("%s: scaling by %.3fx%.3f for armor model", this, armorScaleX, armorScaleY); } }
Angelica
src\main\java\com\prupe\mcpatcher\cit\EnchantmentList.java
package com.prupe.mcpatcher.cit; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.mal.resource.PropertiesFile; final class EnchantmentList { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CUSTOM_ITEM_TEXTURES, "CIT"); private static final float PI = (float) Math.PI; private static LayerMethod applyMethod; private static int limit; private static float fade; private final List<Layer> layers = new ArrayList<>(); static void setProperties(PropertiesFile properties) { applyMethod = new Average(); limit = 99; fade = 0.5f; if (properties != null) { String value = properties.getString("method", "average") .toLowerCase(); if (value.equals("layered")) { applyMethod = new Layered(); } else if (value.equals("cycle")) { applyMethod = new Cycle(); } else if (!value.equals("average")) { logger.warning("%s: unknown enchantment layering method '%s'", CITUtils.CIT_PROPERTIES, value); } limit = Math.max(properties.getInt("cap", limit), 0); fade = Math.max(properties.getFloat("fade", fade), 0.0f); } } EnchantmentList(Map<Item, List<Enchantment>> enchantments, List<Enchantment> allItemEnchantments, ItemStack itemStack) { BitSet layersPresent = new BitSet(); Map<Integer, Layer> tmpLayers = new HashMap<>(); Item item = itemStack.getItem(); int[] enchantmentLevels = CITUtils.getEnchantmentLevels(item, itemStack.getTagCompound()); boolean hasEffect = itemStack.hasEffect(0); List<Enchantment> list = enchantments.get(item); if (list == null) { list = allItemEnchantments; } for (Enchantment enchantment : list) { if (enchantment.match(itemStack, enchantmentLevels, hasEffect)) { int level = Math.max(enchantment.lastEnchantmentLevel, 1); int layer = enchantment.layer; if (!layersPresent.get(layer)) { Layer newLayer = new Layer(enchantment, level); tmpLayers.put(layer, newLayer); layersPresent.set(layer); } } } if (layersPresent.isEmpty()) { return; } while (layersPresent.cardinality() > limit) { int layer = layersPresent.nextSetBit(0); layersPresent.clear(layer); tmpLayers.remove(layer); } for (int i = layersPresent.nextSetBit(0); i >= 0; i = layersPresent.nextSetBit(i + 1)) { layers.add(tmpLayers.get(i)); } applyMethod.computeIntensities(this); } boolean isEmpty() { return layers.isEmpty(); } int size() { return layers.size(); } Enchantment getEnchantment(int index) { return layers.get(index).enchantment; } float getIntensity(int index) { return layers.get(index).intensity; } private static final class Layer { final Enchantment enchantment; final int level; float intensity; Layer(Enchantment enchantment, int level) { this.enchantment = enchantment; this.level = level; } float getEffectiveDuration() { return enchantment.duration + 2.0f * fade; } } abstract private static class LayerMethod { abstract void computeIntensities(EnchantmentList enchantments); protected void scaleIntensities(EnchantmentList enchantments, int denominator) { if (denominator > 0) { for (Layer layer : enchantments.layers) { if (layer.enchantment.blendMethod.canFade()) { layer.intensity = (float) layer.level / (float) denominator; } else { layer.intensity = layer.level > 0 ? 1.0f : 0.0f; } } } else { for (Layer layer : enchantments.layers) { layer.intensity = layer.level > 0 ? 1.0f : 0.0f; } } } } private static final class Average extends LayerMethod { @Override void computeIntensities(EnchantmentList enchantments) { int total = 0; for (Layer layer : enchantments.layers) { if (layer.enchantment.blendMethod.canFade()) { total += layer.level; } } scaleIntensities(enchantments, total); } } private static final class Layered extends LayerMethod { @Override void computeIntensities(EnchantmentList enchantments) { int max = 0; for (Layer layer : enchantments.layers) { if (layer.enchantment.blendMethod.canFade()) { // TODO: check if this is meant, there was no assignment here for some reason max = Math.max(max, layer.level); } } scaleIntensities(enchantments, max); } } private static final class Cycle extends LayerMethod { @Override void computeIntensities(EnchantmentList enchantments) { float total = 0.0f; for (Layer layer : enchantments.layers) { if (layer.enchantment.blendMethod.canFade()) { total += layer.getEffectiveDuration(); } } float timestamp = (float) ((System.currentTimeMillis() / 1000.0) % total); for (Layer layer : enchantments.layers) { if (!layer.enchantment.blendMethod.canFade()) { layer.intensity = layer.level > 0 ? 1.0f : 0.0f; continue; } if (timestamp <= 0.0f) { break; } float duration = layer.getEffectiveDuration(); if (timestamp < duration) { float denominator = (float) Math.sin(PI * fade / duration); layer.intensity = (float) (Math.sin(PI * timestamp / duration) / (denominator == 0.0f ? 1.0f : denominator)); } timestamp -= duration; } } } }
Angelica
src\main\java\com\prupe\mcpatcher\cit\ItemOverride.java
package com.prupe.mcpatcher.cit; import java.util.HashMap; import java.util.Map; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.tile.TileLoader; final class ItemOverride extends OverrideBase { private IIcon icon; private final Map<IIcon, IIcon> iconMap; ItemOverride(PropertiesFile properties) { super(properties); if (items == null) { properties.error("no matching items specified"); } iconMap = alternateTextures == null ? null : new HashMap<>(); } @Override String getType() { return "item"; } IIcon getReplacementIcon(IIcon origIcon) { if (iconMap != null) { IIcon newIcon = iconMap.get(origIcon); if (newIcon != null) { return newIcon; } } return icon; } void preload(TileLoader tileLoader) { String special = null; if (items != null) { if (items.contains(CITUtils.itemCompass)) { special = "compass"; } else if (items.contains(CITUtils.itemClock)) { special = "clock"; } } if (textureName != null) { tileLoader.preloadTile(textureName, false, special); } if (alternateTextures != null) { for (Map.Entry<String, ResourceLocation> entry : alternateTextures.entrySet()) { tileLoader.preloadTile(entry.getValue(), false, special); } } } void registerIcon(TileLoader tileLoader) { if (textureName != null) { icon = tileLoader.getIcon(textureName); } if (alternateTextures != null) { for (Map.Entry<String, ResourceLocation> entry : alternateTextures.entrySet()) { IIcon from = tileLoader.getIcon(entry.getKey()); IIcon to = tileLoader.getIcon(entry.getValue()); if (from != null && to != null) { iconMap.put(from, to); } } } } @Override String preprocessAltTextureKey(String name) { if (name.startsWith("textures/items/")) { name = name.substring(15); if (name.endsWith(".png")) { name = name.substring(0, name.length() - 4); } } return name; } }
Angelica
src\main\java\com\prupe\mcpatcher\cit\OverrideBase.java
package com.prupe.mcpatcher.cit; import java.io.File; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.item.ItemAPI; import com.prupe.mcpatcher.mal.nbt.NBTRule; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.tile.TileLoader; abstract class OverrideBase implements Comparable<OverrideBase> { static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CUSTOM_ITEM_TEXTURES, "CIT"); private static final int MAX_DAMAGE = 65535; private static final int MAX_STACK_SIZE = 65535; final PropertiesFile properties; final ResourceLocation textureName; final Map<String, ResourceLocation> alternateTextures; final int weight; final Set<Item> items; final BitSet damagePercent; final BitSet damage; final int damageMask; final BitSet stackSize; final BitSet enchantmentIDs; final BitSet enchantmentLevels; private final List<NBTRule> nbtRules = new ArrayList<>(); int lastEnchantmentLevel; static OverrideBase create(ResourceLocation filename) { if (new File(filename.getResourcePath()).getName() .equals("cit.properties")) { return null; } PropertiesFile properties = PropertiesFile.get(logger, filename); if (properties == null) { return null; } String type = properties.getString("type", "item") .toLowerCase(); OverrideBase override; switch (type) { case "item" -> { if (!CITUtils.enableItems) { return null; } override = new ItemOverride(properties); } case "enchantment", "overlay" -> { if (!CITUtils.enableEnchantments) { return null; } override = new Enchantment(properties); } case "armor" -> { if (!CITUtils.enableArmor) { return null; } override = new ArmorOverride(properties); } default -> { logger.error("%s: unknown type '%s'", filename, type); return null; } } return override.properties.valid() ? override : null; } OverrideBase(PropertiesFile properties) { this.properties = properties; alternateTextures = getAlternateTextures(); String value = properties.getString("source", ""); ResourceLocation resource = null; if (value.isEmpty()) { value = properties.getString("texture", ""); } if (value.isEmpty()) { value = properties.getString("tile", ""); } if (value.isEmpty()) { if (MCPatcherUtils.isNullOrEmpty(alternateTextures)) { resource = TileLoader.getDefaultAddress(properties.getResource()); if (!TexturePackAPI.hasResource(resource)) { resource = null; } } } else { resource = TileLoader.parseTileAddress(properties.getResource(), value); if (!TexturePackAPI.hasResource(resource)) { properties.error("source texture %s not found", value); resource = null; } } textureName = resource; weight = properties.getInt("weight", 0); value = properties.getString("items", ""); if (value.isEmpty()) { value = properties.getString("matchItems", ""); } if (value.isEmpty()) { items = null; } else { items = new HashSet<>(); for (String s : value.split("\\s+")) { Item item = ItemAPI.parseItemName(s); if (item != null) { items.add(item); } } } value = properties.getString("damage", ""); if (value.isEmpty()) { damage = null; damagePercent = null; } else if (value.contains("%")) { damage = null; damagePercent = parseBitSet(value.replace("%", ""), 0, 100); } else { damage = parseBitSet(value, 0, MAX_DAMAGE); damagePercent = null; } damageMask = properties.getInt("damageMask", MAX_DAMAGE); stackSize = parseBitSet(properties, "stackSize", 0, MAX_STACK_SIZE); enchantmentIDs = parseBitSet(properties, "enchantmentIDs", 0, CITUtils.MAX_ENCHANTMENTS - 1); enchantmentLevels = parseBitSet(properties, "enchantmentLevels", 0, CITUtils.MAX_ENCHANTMENTS - 1); for (Map.Entry<String, String> entry : properties.entrySet()) { String name = entry.getKey(); if (name.startsWith(NBTRule.NBT_RULE_PREFIX)) { value = entry.getValue(); NBTRule rule = NBTRule.create(name, value); if (rule == null) { properties.error("invalid nbt rule: %s", value); } else { nbtRules.add(rule); } } } } public int compareTo(OverrideBase o) { int result = o.weight - weight; if (result != 0) { return result; } return properties.getResource() .toString() .compareTo( o.properties.getResource() .toString()); } boolean match(ItemStack itemStack, int[] itemEnchantmentLevels, boolean hasEffect) { return matchDamage(itemStack) && matchDamagePercent(itemStack) && matchStackSize(itemStack) && matchEnchantment(itemEnchantmentLevels, hasEffect) && matchNBT(itemStack); } String preprocessAltTextureKey(String name) { return name; } private Map<String, ResourceLocation> getAlternateTextures() { Map<String, ResourceLocation> tmpMap = new HashMap<>(); for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); String name; if (key.startsWith("source.")) { name = key.substring(7); } else if (key.startsWith("texture.")) { name = key.substring(8); } else if (key.startsWith("tile.")) { name = key.substring(5); } else { continue; } name = preprocessAltTextureKey(name); if (MCPatcherUtils.isNullOrEmpty(name)) { continue; } ResourceLocation resource = TileLoader.parseTileAddress(properties.getResource(), value); if (resource != null) { tmpMap.put(name, resource); } } return tmpMap.isEmpty() ? null : tmpMap; } private boolean matchDamage(ItemStack itemStack) { return damage == null || damage.get(itemStack.getItemDamage() & damageMask); } private boolean matchDamagePercent(ItemStack itemStack) { if (damagePercent == null) { return true; } int maxDamage = itemStack.getMaxDamage(); if (maxDamage == 0) { return false; } int percent = (100 * itemStack.getItemDamage()) / maxDamage; if (percent < 0) { percent = 0; } else if (percent > 100) { percent = 100; } return damagePercent.get(percent); } private boolean matchStackSize(ItemStack itemStack) { return stackSize == null || stackSize.get(itemStack.stackSize); } private boolean matchEnchantment(int[] itemEnchantmentLevels, boolean hasEffect) { if (enchantmentLevels == null && enchantmentIDs == null) { return true; } else if (itemEnchantmentLevels == null) { return (lastEnchantmentLevel = getEnchantmentLevelMatch(hasEffect)) >= 0; } else { return (lastEnchantmentLevel = getEnchantmentLevelMatch(itemEnchantmentLevels)) >= 0; } } private int getEnchantmentLevelMatch(boolean hasEffect) { if (hasEffect && enchantmentIDs == null && enchantmentLevels.get(1)) { return 1; } else { return -1; } } private int getEnchantmentLevelMatch(int[] itemEnchantmentLevels) { int matchLevel = -1; if (enchantmentIDs == null) { int sum = 0; for (int level : itemEnchantmentLevels) { sum += level; } if (enchantmentLevels.get(sum)) { return sum; } } else if (enchantmentLevels == null) { for (int id = enchantmentIDs.nextSetBit(0); id >= 0; id = enchantmentIDs.nextSetBit(id + 1)) { if (itemEnchantmentLevels[id] > 0) { matchLevel = Math.max(matchLevel, itemEnchantmentLevels[id]); } } } else { for (int id = enchantmentIDs.nextSetBit(0); id >= 0; id = enchantmentIDs.nextSetBit(id + 1)) { if (enchantmentLevels.get(itemEnchantmentLevels[id])) { matchLevel = Math.max(matchLevel, itemEnchantmentLevels[id]); } } } return matchLevel; } private boolean matchNBT(ItemStack itemStack) { for (NBTRule rule : nbtRules) { if (!rule.match(itemStack.getTagCompound())) { return false; } } return true; } abstract String getType(); @Override public String toString() { return String.format("ItemOverride{%s, %s, %s}", getType(), properties, textureName); } private static BitSet parseBitSet(PropertiesFile properties, String tag, int min, int max) { String value = properties.getString(tag, ""); return parseBitSet(value, min, max); } private static BitSet parseBitSet(String value, int min, int max) { if (value.isEmpty()) { return null; } BitSet bits = new BitSet(); for (int i : MCPatcherUtils.parseIntegerList(value, min, max)) { bits.set(i); } return bits; } }
Angelica
src\main\java\com\prupe\mcpatcher\cit\PotionReplacer.java
package com.prupe.mcpatcher.cit; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionHelper; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; class PotionReplacer { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CUSTOM_ITEM_TEXTURES, "CIT"); private static final String ITEM_ID_POTION = "minecraft:potion"; private static final String ITEM_ID_GLASS_BOTTLE = "minecraft:glass_bottle"; private static final String LAYER_POTION_CONTENTS = "potion_overlay"; private static final String LAYER_POTION_DRINKABLE = "potion_bottle_drinkable"; private static final String LAYER_POTION_SPLASH = "potion_bottle_splash"; private static final String LAYER_EMPTY_BOTTLE = "potion_bottle_empty"; private static final int SPLASH_BIT = 0x4000; private static final int EFFECT_BITS = 0x400f; private static final int MUNDANE_BITS = 0x403f; private static final int WATER_BITS = 0xffff; private static final int[] POTION_EFFECTS = new int[] { -1, // 0: none 2, // 1: moveSpeed 10, // 2: moveSlowdown -1, // 3: digSpeed -1, // 4: digSlowDown 9, // 5: damageBoost 5, // 6: heal 12, // 7: harm -1, // 8: jump -1, // 9: confusion 1, // 10: regeneration -1, // 11: resistance 3, // 12: fireResistance -1, // 13: waterBreathing 14, // 14: invisibility -1, // 15: blindness 6, // 16: nightVision -1, // 17: hunger 8, // 18: weakness 4, // 19: poison -1, // 20: wither }; private static final Map<String, Integer> mundanePotionMap = new HashMap<>(); private static int weight = -2; final List<ItemOverride> overrides = new ArrayList<>(); static { try { for (int i : new int[] { 0, 7, 11, 13, 15, 16, 23, 27, 29, 31, 32, 39, 43, 45, 47, 48, 55, 59, 61, 63 }) { String name = PotionHelper.func_77905_c(i) // getMundaneName .replaceFirst("^potion\\.prefix\\.", ""); mundanePotionMap.put(name, i); logger.fine("%s potion -> damage value %d", name, i); } for (int i = 0; i < Potion.potionTypes.length; i++) { Potion potion = Potion.potionTypes[i]; if (potion != null) { logger.fine( "%s potion -> effect %d", potion.getName() .replaceFirst("^potion\\.", ""), i); } } } catch (Exception e) { e.printStackTrace(); } } PotionReplacer() { ResourceLocation path = getPotionPath("water", false); if (TexturePackAPI.hasResource(path)) { weight++; registerVanillaPotion(path, 0, WATER_BITS, false); weight--; } path = getPotionPath("empty", false); if (TexturePackAPI.hasResource(path)) { registerEmptyBottle(path); } registerPotionsByEffect(false); registerPotionsByEffect(true); registerMundanePotions(false); registerMundanePotions(true); registerOtherPotions(false); registerOtherPotions(true); } private static ResourceLocation getPotionPath(String name, boolean splash) { String path = "cit/potion/" + (splash ? "splash/" : "normal/") + name + ".png"; return TexturePackAPI.newMCPatcherResourceLocation(path); } private static Properties newProperties(ResourceLocation path, String itemID, String layer) { Properties properties = new Properties(); properties.setProperty("type", "item"); properties.setProperty("items", itemID); properties.setProperty("texture." + layer, path.toString()); properties.setProperty("texture." + LAYER_POTION_CONTENTS, "blank"); properties.setProperty("weight", String.valueOf(weight)); return properties; } private static Properties newProperties(ResourceLocation path, String itemID, boolean splash) { String layer = splash ? LAYER_POTION_SPLASH : LAYER_POTION_DRINKABLE; return newProperties(path, itemID, layer); } private void registerPotionsByEffect(boolean splash) { for (int effect = 0; effect < Potion.potionTypes.length; effect++) { if (Potion.potionTypes[effect] == null) { continue; } ResourceLocation path = getPotionPath( Potion.potionTypes[effect].getName() .replaceFirst("^potion\\.", ""), splash); if (TexturePackAPI.hasResource(path)) { if (effect < POTION_EFFECTS.length && POTION_EFFECTS[effect] >= 0) { int damage = POTION_EFFECTS[effect]; if (splash) { damage |= SPLASH_BIT; } registerVanillaPotion(path, damage, EFFECT_BITS, splash); } if (!splash) { registerCustomPotion(path, effect, splash); } } } } private void registerMundanePotions(boolean splash) { for (Map.Entry<String, Integer> entry : mundanePotionMap.entrySet()) { int damage = entry.getValue(); if (splash) { damage |= SPLASH_BIT; } registerMundanePotion(entry.getKey(), damage, splash); } } private void registerMundanePotion(String name, int damage, boolean splash) { ResourceLocation path = getPotionPath(name, splash); if (TexturePackAPI.hasResource(path)) { registerVanillaPotion(path, damage, MUNDANE_BITS, splash); } } private void registerOtherPotions(boolean splash) { ResourceLocation path = getPotionPath("other", splash); if (TexturePackAPI.hasResource(path)) { Properties properties = newProperties(path, ITEM_ID_POTION, splash); StringBuilder sb = new StringBuilder(); for (int i : mundanePotionMap.values()) { if (splash) { i |= SPLASH_BIT; } sb.append(' ') .append(i); } properties.setProperty( "damage", sb.toString() .trim()); properties.setProperty("damageMask", String.valueOf(MUNDANE_BITS)); addOverride(path, properties); } } private void registerVanillaPotion(ResourceLocation path, int damage, int mask, boolean splash) { Properties properties = newProperties(path, ITEM_ID_POTION, splash); properties.setProperty("damage", String.valueOf(damage)); properties.setProperty("damageMask", String.valueOf(mask)); addOverride(path, properties); } private void registerCustomPotion(ResourceLocation path, int effect, boolean splash) { Properties properties = newProperties(path, ITEM_ID_POTION, splash); properties.setProperty("nbt.CustomPotionEffects.0.Id", String.valueOf(effect)); addOverride(path, properties); } private void registerEmptyBottle(ResourceLocation path) { Properties properties = newProperties(path, ITEM_ID_GLASS_BOTTLE, LAYER_EMPTY_BOTTLE); addOverride(path, properties); } private void addOverride(ResourceLocation path, Properties properties) { ResourceLocation propertiesName = TexturePackAPI.transformResourceLocation(path, ".png", ".properties"); ItemOverride override = new ItemOverride(new PropertiesFile(logger, propertiesName, properties)); if (override.properties.valid()) { overrides.add(override); } } }
Angelica
src\main\java\com\prupe\mcpatcher\ctm\BlockFaceMatcher.java
package com.prupe.mcpatcher.ctm; import static com.prupe.mcpatcher.ctm.RenderBlockState.BOTTOM_FACE; import static com.prupe.mcpatcher.ctm.RenderBlockState.EAST_FACE; import static com.prupe.mcpatcher.ctm.RenderBlockState.NORTH_FACE; import static com.prupe.mcpatcher.ctm.RenderBlockState.SOUTH_FACE; import static com.prupe.mcpatcher.ctm.RenderBlockState.TOP_FACE; import static com.prupe.mcpatcher.ctm.RenderBlockState.WEST_FACE; import com.prupe.mcpatcher.MCPatcherUtils; public class BlockFaceMatcher { private final int faces; protected BlockFaceMatcher(String[] values) { int flags = 0; for (String face : values) { switch (face) { case "bottom", "down" -> flags |= (1 << BOTTOM_FACE); case "top", "up" -> flags |= (1 << TOP_FACE); case "north" -> flags |= (1 << NORTH_FACE); case "south" -> flags |= (1 << SOUTH_FACE); case "east" -> flags |= (1 << EAST_FACE); case "west" -> flags |= (1 << WEST_FACE); case "side", "sides" -> flags |= (1 << NORTH_FACE) | (1 << SOUTH_FACE) | (1 << EAST_FACE) | (1 << WEST_FACE); case "all" -> flags = -1; } } faces = flags; } public boolean match(RenderBlockState renderBlockState) { int face = renderBlockState.getTextureFace(); return face >= 0 && (faces & (1 << face)) != 0; } protected boolean isAll() { return faces == -1; } public static BlockFaceMatcher create(String propertyValue) { if (!MCPatcherUtils.isNullOrEmpty(propertyValue)) { String[] values = propertyValue.toLowerCase() .split("\\s+"); try { BlockFaceMatcher matcher = new BlockFaceMatcher(values); if (!matcher.isAll()) { return matcher; } } catch (Exception e) { e.printStackTrace(); } } return null; } }
Angelica
src\main\java\com\prupe\mcpatcher\ctm\BlockOrientation.java
package com.prupe.mcpatcher.ctm; import net.minecraft.block.Block; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import com.prupe.mcpatcher.mal.block.BlockStateMatcher; final class BlockOrientation extends RenderBlockState { // NEIGHBOR_OFFSETS[a][b][c] = offset from starting block // a: face 0-5 // b: neighbor 0-7 // 7 6 5 // 0 * 4 // 1 2 3 // c: coordinate (x,y,z) 0-2 private static final int[][][] NEIGHBOR_OFFSET = new int[][][] { makeNeighborOffset(WEST_FACE, SOUTH_FACE, EAST_FACE, NORTH_FACE), // BOTTOM_FACE makeNeighborOffset(WEST_FACE, SOUTH_FACE, EAST_FACE, NORTH_FACE), // TOP_FACE makeNeighborOffset(EAST_FACE, BOTTOM_FACE, WEST_FACE, TOP_FACE), // NORTH_FACE makeNeighborOffset(WEST_FACE, BOTTOM_FACE, EAST_FACE, TOP_FACE), // SOUTH_FACE makeNeighborOffset(NORTH_FACE, BOTTOM_FACE, SOUTH_FACE, TOP_FACE), // WEST_FACE makeNeighborOffset(SOUTH_FACE, BOTTOM_FACE, NORTH_FACE, TOP_FACE), // EAST_FACE }; private static final int[][] ROTATE_UV_MAP = new int[][] { { WEST_FACE, EAST_FACE, NORTH_FACE, SOUTH_FACE, TOP_FACE, BOTTOM_FACE, 2, -2, 2, -2, 0, 0 }, { NORTH_FACE, SOUTH_FACE, TOP_FACE, BOTTOM_FACE, WEST_FACE, EAST_FACE, 0, 0, 0, 0, -2, 2 }, { WEST_FACE, EAST_FACE, NORTH_FACE, SOUTH_FACE, TOP_FACE, BOTTOM_FACE, 2, -2, -2, -2, 0, 0 }, { NORTH_FACE, SOUTH_FACE, TOP_FACE, BOTTOM_FACE, WEST_FACE, EAST_FACE, 0, 0, 0, 0, -2, -2 }, }; private int x, y, z; private int metadata; private int altMetadata; private int metadataBits; private int renderType; private int blockFace; private int textureFace; private int textureFaceOrig; private int rotateUV; @Override public void clear() { super.clear(); x = y = z = 0; renderType = -1; metadata = 0; blockFace = textureFace = 0; rotateUV = 0; offsetsComputed = false; haveOffsets = false; dx = dy = dz = 0; } @Override public int getX() { return x; } @Override public int getY() { return y; } @Override public int getZ() { return z; } @Override public int getBlockFace() { return blockFace; } @Override public int getTextureFace() { return textureFace; } @Override public int getTextureFaceOrig() { return textureFaceOrig; } @Override public int getFaceForHV() { return blockFace; } @Override public boolean match(BlockStateMatcher matcher) { return isInWorld() ? matcher.match(blockAccess, x, y, z) : matcher.match(block, metadata); } @Override public int[] getOffset(int blockFace, int relativeDirection) { return NEIGHBOR_OFFSET[blockFace][rotateUV(relativeDirection)]; } @Override public boolean setCoordOffsetsForRenderType() { if (offsetsComputed) { return haveOffsets; } offsetsComputed = true; haveOffsets = false; dx = dy = dz = 0; switch (renderType) { case 1 -> { // renderCrossedSquares while (y + dy > 0 && block == blockAccess.getBlock(x, y + dy - 1, z)) { dy--; haveOffsets = true; } } // renderBlockDoor case 7, 40 -> { // renderBlockDoublePlant if ((metadata & 0x8) != 0 && block == blockAccess.getBlock(x, y - 1, z)) { dy--; haveOffsets = true; } } case 14 -> { // renderBlockBed metadata = blockAccess.getBlockMetadata(x, y, z); switch (metadata) { case 0, 4 -> dz = 1; // head is one block south case 1, 5 -> dx = -1; // head is one block west case 2, 6 -> dz = -1; // head is one block north case 3, 7 -> dx = 1; // head is one block east default -> { return false; // head itself, no offset } } haveOffsets = block == blockAccess.getBlock(x + dx, y, z + dz); } default -> { } } return haveOffsets; } @Override public boolean shouldConnectByBlock(Block neighbor, int neighborX, int neighborY, int neighborZ) { return block == neighbor && (metadataBits & (1 << blockAccess.getBlockMetadata(neighborX, neighborY, neighborZ))) != 0; } @Override public boolean shouldConnectByTile(Block neighbor, IIcon origIcon, int neighborX, int neighborY, int neighborZ) { return origIcon == neighbor.getIcon(blockAccess, neighborX, neighborY, neighborZ, getTextureFaceOrig()); } void setBlock(Block block, IBlockAccess blockAccess, int x, int y, int z) { this.block = block; this.blockAccess = blockAccess; inWorld = true; this.x = x; this.y = y; this.z = z; renderType = block.getRenderType(); metadata = altMetadata = blockAccess.getBlockMetadata(x, y, z); offsetsComputed = false; } void setFace(int face) { blockFace = getBlockFaceByRenderType(face); textureFaceOrig = face; rotateUV = 0; textureFace = blockFaceToTextureFace(blockFace); metadataBits = (1 << metadata) | (1 << altMetadata); } void setBlockMetadata(Block block, int metadata, int face) { this.block = block; blockAccess = null; inWorld = false; x = y = z = 0; renderType = block.getRenderType(); blockFace = textureFace = textureFaceOrig = face; this.metadata = metadata; metadataBits = 1 << metadata; dx = dy = dz = 0; rotateUV = 0; } private int getBlockFaceByRenderType(int face) { switch (renderType) { case 1 -> { // renderCrossedSquares return NORTH_FACE; } case 8 -> { // renderBlockLadder switch (metadata) { case 2, 3, 4, 5 -> { return metadata; } } } case 20 -> { // renderBlockVine switch (metadata) { case 1 -> { return NORTH_FACE; } case 2 -> { return EAST_FACE; } case 4 -> { return SOUTH_FACE; } case 8 -> { return WEST_FACE; } } } } return face; } private int blockFaceToTextureFace(int face) { switch (renderType) { case 31 -> { // renderBlockLog (also applies to hay) switch (metadata & 0xc) { case 4 -> { // west-east altMetadata &= ~0xc; rotateUV = ROTATE_UV_MAP[0][face + 6]; return ROTATE_UV_MAP[0][face]; } case 8 -> { // north-south altMetadata &= ~0xc; rotateUV = ROTATE_UV_MAP[1][face + 6]; return ROTATE_UV_MAP[1][face]; } } } case 39 -> { // renderBlockQuartz switch (metadata) { case 3 -> { // north-south altMetadata = 2; rotateUV = ROTATE_UV_MAP[2][face + 6]; return ROTATE_UV_MAP[2][face]; } case 4 -> { // west-east altMetadata = 2; rotateUV = ROTATE_UV_MAP[3][face + 6]; return ROTATE_UV_MAP[3][face]; } } } } return face; } private int rotateUV(int neighbor) { return (neighbor + rotateUV) & 7; } }
Angelica
src\main\java\com\prupe\mcpatcher\ctm\CTMUtils.java
package com.prupe.mcpatcher.ctm; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.block.BlockAPI; import com.prupe.mcpatcher.mal.block.BlockStateMatcher; import com.prupe.mcpatcher.mal.block.RenderBlocksUtils; import com.prupe.mcpatcher.mal.block.RenderPassAPI; import com.prupe.mcpatcher.mal.resource.BlendMethod; import com.prupe.mcpatcher.mal.resource.ResourceList; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.resource.TexturePackChangeHandler; import com.prupe.mcpatcher.mal.tile.TileLoader; import jss.notfine.config.MCPatcherForgeConfig; public class CTMUtils { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CONNECTED_TEXTURES, "CTM"); private static final List<TileOverride> allOverrides = new ArrayList<>(); private static final Map<Block, List<BlockStateMatcher>> blockOverrides = new IdentityHashMap<>(); private static final Map<String, List<TileOverride>> tileOverrides = new HashMap<>(); private static TileLoader tileLoader; private static TileOverride lastOverride; private static final TileOverrideIterator.IJK ijkIterator = newIJKIterator(); private static final TileOverrideIterator.Metadata metadataIterator = newMetadataIterator(); private static boolean haveBlockFace; private static final BlockOrientation renderBlockState = new BlockOrientation(); static { try { Class.forName(MCPatcherUtils.RENDER_PASS_CLASS) .getMethod("finish") .invoke(null); } catch (Exception ignore) {} TexturePackChangeHandler.register(new TexturePackChangeHandler(MCPatcherUtils.CONNECTED_TEXTURES, 3) { @Override public void initialize() {} @Override public void beforeChange() { RenderPassAPI.instance.clear(); try { GlassPaneRenderer.clear(); } catch (Exception e) { e.printStackTrace(); } renderBlockState.clear(); ijkIterator.clear(); metadataIterator.clear(); allOverrides.clear(); blockOverrides.clear(); tileOverrides.clear(); lastOverride = null; RenderBlocksUtils.blankIcon = null; tileLoader = new TileLoader("textures/blocks", logger); RenderPassAPI.instance.refreshBlendingOptions(); if (MCPatcherForgeConfig.ConnectedTextures.standard || MCPatcherForgeConfig.ConnectedTextures.nonStandard) { for (ResourceLocation resource : ResourceList.getInstance() .listResources(TexturePackAPI.MCPATCHER_SUBDIR + "ctm", ".properties", true)) { registerOverride(TileOverride.create(resource, tileLoader)); } } for (ResourceLocation resource : BlendMethod.getAllBlankResources()) { tileLoader.preloadTile(resource, false); } } @Override public void afterChange() { for (TileOverride override : allOverrides) { override.registerIcons(); } for (Map.Entry<Block, List<BlockStateMatcher>> entry : blockOverrides.entrySet()) { for (BlockStateMatcher matcher : entry.getValue()) { TileOverride override = (TileOverride) matcher.getData(); if (override.getRenderPass() >= 0) { RenderPassAPI.instance.setRenderPassForBlock(entry.getKey(), override.getRenderPass()); } } } for (List<BlockStateMatcher> overrides : blockOverrides.values()) { overrides.sort((m1, m2) -> { TileOverride o1 = (TileOverride) m1.getData(); TileOverride o2 = (TileOverride) m2.getData(); return o1.compareTo(o2); }); } for (List<TileOverride> overrides : tileOverrides.values()) { Collections.sort(overrides); } setBlankResource(); } }); } private static void clearBlockFace() { haveBlockFace = false; } public static synchronized IIcon getBlockIcon(IIcon icon, Block block, IBlockAccess blockAccess, int x, int y, int z, int face) { lastOverride = null; if (blockAccess != null && checkFace(face)) { if (!haveBlockFace) { renderBlockState.setBlock(block, blockAccess, x, y, z); renderBlockState.setFace(face); } lastOverride = ijkIterator.go(renderBlockState, icon); if (lastOverride != null) { icon = ijkIterator.getIcon(); } } clearBlockFace(); return lastOverride == null && skipDefaultRendering(block) ? RenderBlocksUtils.blankIcon : icon; } public static synchronized IIcon getBlockIcon(IIcon icon, Block block, int face, int metadata) { lastOverride = null; if (checkFace(face) && checkRenderType(block)) { renderBlockState.setBlockMetadata(block, metadata, face); lastOverride = metadataIterator.go(renderBlockState, icon); if (lastOverride != null) { icon = metadataIterator.getIcon(); } } return icon; } public static IIcon getBlockIcon(IIcon icon, Block block, int face) { return getBlockIcon(icon, block, face, 0); } public static void reset() {} private static boolean checkFace(int face) { return face < 0 ? MCPatcherForgeConfig.ConnectedTextures.nonStandard : MCPatcherForgeConfig.ConnectedTextures.standard; } private static boolean checkRenderType(Block block) { return switch (block.getRenderType()) { case 11, 21 -> // fence, fence gate false; default -> true; }; } private static synchronized boolean skipDefaultRendering(Block block) { return RenderPassAPI.instance.skipDefaultRendering(block); } private static synchronized void registerOverride(TileOverride override) { if (override != null && !override.isDisabled()) { boolean registered = false; List<BlockStateMatcher> matchingBlocks = override.getMatchingBlocks(); if (!MCPatcherUtils.isNullOrEmpty(matchingBlocks)) { for (BlockStateMatcher matcher : matchingBlocks) { if (matcher == null) { continue; } Block block = matcher.getBlock(); List<BlockStateMatcher> list = blockOverrides.computeIfAbsent(block, k -> new ArrayList<>()); list.add(matcher); logger.fine("using %s for block %s", override, BlockAPI.getBlockName(block)); registered = true; } } Set<String> matchingTiles = override.getMatchingTiles(); if (!MCPatcherUtils.isNullOrEmpty(matchingTiles)) { for (String name : matchingTiles) { List<TileOverride> list = tileOverrides.computeIfAbsent(name, k -> new ArrayList<>()); list.add(override); logger.fine("using %s for tile %s", override, name); registered = true; } } if (registered) { allOverrides.add(override); } } } public static synchronized void setBlankResource() { RenderBlocksUtils.blankIcon = tileLoader.getIcon(RenderPassAPI.instance.getBlankResource()); } public static TileOverrideIterator.IJK newIJKIterator() { return new TileOverrideIterator.IJK(blockOverrides, tileOverrides); } public static TileOverrideIterator.Metadata newMetadataIterator() { return new TileOverrideIterator.Metadata(blockOverrides, tileOverrides); } }
Angelica
src\main\java\com\prupe\mcpatcher\ctm\GlassPaneRenderer.java
package com.prupe.mcpatcher.ctm; import java.util.Arrays; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import jss.notfine.config.MCPatcherForgeConfig; public class GlassPaneRenderer { public static boolean skipPaneRendering; public static boolean skipTopEdgeRendering; public static boolean skipBottomEdgeRendering; private static final IIcon[] icons = new IIcon[6]; private static double uLeft; // left edge private static double uLeftThin; // 7/16 point private static double uRightThin; // 9/16 point private static double uRight; // right edge private static double vTop; // top edge private static double vBottom; // bottom edge private static double u1Scaled; private static double u2Scaled; public static void renderThin(RenderBlocks renderBlocks, Block blockPane, IIcon origIcon, int x, int y, int z, boolean connectNorth, boolean connectSouth, boolean connectWest, boolean connectEast) { if (setupIcons(renderBlocks, blockPane, origIcon, x, y, z)) { render(x, y, z, connectNorth, connectSouth, connectWest, connectEast, 0.0, 0.0, 0.0, false); } } public static void renderThick(RenderBlocks renderBlocks, Block blockPane, IIcon origIcon, int x, int y, int z, boolean connectNorth, boolean connectSouth, boolean connectWest, boolean connectEast) { if (setupIcons(renderBlocks, blockPane, origIcon, x, y, z)) { setupPaneEdges(renderBlocks.blockAccess, blockPane, x, y, z); render(x, y, z, connectNorth, connectSouth, connectWest, connectEast, 0.0625, 1.0, 0.001, true); } } private static boolean setupIcons(RenderBlocks renderBlocks, Block blockPane, IIcon origIcon, int x, int y, int z) { skipPaneRendering = skipBottomEdgeRendering = skipTopEdgeRendering = false; if (!MCPatcherForgeConfig.ConnectedTextures.glassPane) { return false; } for (int face = BlockOrientation.NORTH_FACE; face <= BlockOrientation.EAST_FACE; face++) { icons[face] = CTMUtils .getBlockIcon(origIcon, blockPane, renderBlocks.blockAccess, x, y, z, face); if (icons[face] == null) { skipPaneRendering = false; return false; } else if (icons[face] != origIcon) { skipPaneRendering = true; } } return skipPaneRendering; } private static void setupPaneEdges(IBlockAccess blockAccess, Block blockPane, int x, int y, int z) { int metadata = blockAccess.getBlockMetadata(x, y, z); skipBottomEdgeRendering = blockAccess.getBlock(x, y - 1, z) == blockPane && blockAccess.getBlockMetadata(x, y - 1, z) == metadata; skipTopEdgeRendering = blockAccess.getBlock(x, y + 1, z) == blockPane && blockAccess.getBlockMetadata(x, y + 1, z) == metadata; } private static void render(int x, int y, int z, boolean connectNorth, boolean connectSouth, boolean connectWest, boolean connectEast, double thickness, double uOffset, double yOffset, boolean edges) { final double west = x; final double westThin = x + 0.5 - thickness; final double eastThin = x + 0.5 + thickness; final double east = x + 1.0; final double down = y + yOffset; final double up = y + 1.0 - yOffset; final double north = z; final double northThin = z + 0.5 - thickness; final double southThin = z + 0.5 + thickness; final double south = z + 1.0; u1Scaled = 8.0 - uOffset; u2Scaled = 8.0 + uOffset; if (!connectNorth && !connectSouth && !connectWest && !connectEast) { connectNorth = connectSouth = connectWest = connectEast = true; if (edges) { // east pane edge: 1/8 wide setupTileCoords(BlockOrientation.EAST_FACE); drawFace(east, up, southThin, uLeftThin, vTop, east, down, northThin, uRightThin, vBottom); // west pane edge: 1/8 wide setupTileCoords(BlockOrientation.WEST_FACE); drawFace(west, up, northThin, uLeftThin, vTop, west, down, southThin, uRightThin, vBottom); // south pane edge: 1/8 wide setupTileCoords(BlockOrientation.SOUTH_FACE); drawFace(westThin, up, south, uLeftThin, vTop, eastThin, down, south, uRightThin, vBottom); // north pane edge: 1/8 wide setupTileCoords(BlockOrientation.NORTH_FACE); drawFace(eastThin, up, north, uLeftThin, vTop, westThin, down, north, uRightThin, vBottom); } } if (connectEast && connectWest) { // full west-east pane setupTileCoords(BlockOrientation.SOUTH_FACE); drawFace(west, up, southThin, uLeft, vTop, east, down, southThin, uRight, vBottom); setupTileCoords(BlockOrientation.NORTH_FACE); drawFace(east, up, northThin, uLeft, vTop, west, down, northThin, uRight, vBottom); } else if (connectWest) { // west half-pane setupTileCoords(BlockOrientation.SOUTH_FACE); if (connectSouth) { // inner corner: 7/16 wide drawFace(west, up, southThin, uRightThin, vTop, westThin, down, southThin, uRight, vBottom); } else { // outer corner: 9/16 wide drawFace(west, up, southThin, uLeftThin, vTop, eastThin, down, southThin, uRight, vBottom); } setupTileCoords(BlockOrientation.NORTH_FACE); if (connectNorth) { // inner corner: 7/16 wide drawFace(westThin, up, northThin, uLeft, vTop, west, down, northThin, uLeftThin, vBottom); } else { // outer corner: 9/16 wide drawFace(eastThin, up, northThin, uLeft, vTop, west, down, northThin, uRightThin, vBottom); } if (edges && !connectNorth && !connectSouth) { // pane edge: 1/8 wide setupTileCoords(BlockOrientation.EAST_FACE); drawFace(eastThin, up, southThin, uLeftThin, vTop, eastThin, down, northThin, uRightThin, vBottom); } } else if (connectEast) { // east half-pane setupTileCoords(BlockOrientation.SOUTH_FACE); if (connectSouth) { // inner corner: 7/16 wide drawFace(eastThin, up, southThin, uLeft, vTop, east, down, southThin, uLeftThin, vBottom); } else { // outer corner: 9/16 wide drawFace(westThin, up, southThin, uLeft, vTop, east, down, southThin, uRightThin, vBottom); } setupTileCoords(BlockOrientation.NORTH_FACE); if (connectNorth) { // inner corner: 7/16 wide drawFace(east, up, northThin, uRightThin, vTop, eastThin, down, northThin, uRight, vBottom); } else { // outer corner: 9/16 wide drawFace(east, up, northThin, uLeftThin, vTop, westThin, down, northThin, uRight, vBottom); } if (edges && !connectNorth && !connectSouth) { // pane edge: 1/8 wide setupTileCoords(BlockOrientation.WEST_FACE); drawFace(westThin, up, northThin, uLeftThin, vTop, westThin, down, southThin, uRightThin, vBottom); } } if (connectNorth && connectSouth) { // full north-south pane setupTileCoords(BlockOrientation.WEST_FACE); drawFace(westThin, up, north, uLeft, vTop, westThin, down, south, uRight, vBottom); setupTileCoords(BlockOrientation.EAST_FACE); drawFace(eastThin, up, south, uLeft, vTop, eastThin, down, north, uRight, vBottom); } else if (connectNorth) { // north half-pane setupTileCoords(BlockOrientation.WEST_FACE); if (connectWest) { // inner corner: 7/16 wide drawFace(westThin, up, north, uRightThin, vTop, westThin, down, northThin, uRight, vBottom); } else { // outer corner: 9/16 wide drawFace(westThin, up, north, uLeftThin, vTop, westThin, down, southThin, uRight, vBottom); } setupTileCoords(BlockOrientation.EAST_FACE); if (connectEast) { // inner corner: 7/16 wide drawFace(eastThin, up, northThin, uLeft, vTop, eastThin, down, north, uLeftThin, vBottom); } else { // outer corner: 9/16 wide drawFace(eastThin, up, southThin, uLeft, vTop, eastThin, down, north, uRightThin, vBottom); } if (edges && !connectWest && !connectEast) { // pane edge: 1/8 wide setupTileCoords(BlockOrientation.SOUTH_FACE); drawFace(westThin, up, southThin, uLeftThin, vTop, eastThin, down, southThin, uRightThin, vBottom); } } else if (connectSouth) { // south half-pane setupTileCoords(BlockOrientation.WEST_FACE); if (connectWest) { // inner corner: 7/16 wide drawFace(westThin, up, southThin, uLeft, vTop, westThin, down, south, uLeftThin, vBottom); } else { // outer corner: 9/16 wide drawFace(westThin, up, northThin, uLeft, vTop, westThin, down, south, uRightThin, vBottom); } setupTileCoords(BlockOrientation.EAST_FACE); if (connectEast) { // inner corner: 7/16 wide drawFace(eastThin, up, south, uRightThin, vTop, eastThin, down, southThin, uRight, vBottom); } else { // outer corner: 9/16 wide drawFace(eastThin, up, south, uLeftThin, vTop, eastThin, down, northThin, uRight, vBottom); } if (edges && !connectWest && !connectEast) { // pane edge: 1/8 wide setupTileCoords(BlockOrientation.NORTH_FACE); drawFace(eastThin, up, northThin, uLeftThin, vTop, westThin, down, northThin, uRightThin, vBottom); } } } private static void setupTileCoords(int face) { final IIcon icon = icons[face]; uLeft = icon.getMinU(); uLeftThin = icon.getInterpolatedU(u1Scaled); uRightThin = icon.getInterpolatedU(u2Scaled); uRight = icon.getMaxU(); vTop = icon.getMinV(); vBottom = icon.getMaxV(); } private static void drawFace(double x0, double y0, double z0, double u0, double v0, // top left double x1, double y1, double z1, double u1, double v1) { // lower right Tessellator tessellator = Tessellator.instance; tessellator.addVertexWithUV(x0, y0, z0, u0, v0); tessellator.addVertexWithUV(x0, y1, z0, u0, v1); tessellator.addVertexWithUV(x1, y1, z1, u1, v1); tessellator.addVertexWithUV(x1, y0, z1, u1, v0); } protected static void clear() { Arrays.fill(icons, null); skipPaneRendering = false; } }
Angelica
src\main\java\com\prupe\mcpatcher\ctm\RenderBlockState.java
package com.prupe.mcpatcher.ctm; import net.minecraft.block.Block; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import com.prupe.mcpatcher.mal.block.BlockStateMatcher; abstract public class RenderBlockState { public static final int BOTTOM_FACE = 0; // 0, -1, 0 public static final int TOP_FACE = 1; // 0, 1, 0 public static final int NORTH_FACE = 2; // 0, 0, -1 public static final int SOUTH_FACE = 3; // 0, 0, 1 public static final int WEST_FACE = 4; // -1, 0, 0 public static final int EAST_FACE = 5; // 1, 0, 0 public static final int[] GO_DOWN = new int[] { 0, -1, 0 }; public static final int[] GO_UP = new int[] { 0, 1, 0 }; public static final int[] GO_NORTH = new int[] { 0, 0, -1 }; public static final int[] GO_SOUTH = new int[] { 0, 0, 1 }; public static final int[] GO_WEST = new int[] { -1, 0, 0 }; public static final int[] GO_EAST = new int[] { 1, 0, 0 }; public static final int[][] NORMALS = new int[][] { GO_DOWN, GO_UP, GO_NORTH, GO_SOUTH, GO_WEST, GO_EAST, }; public static final int REL_L = 0; public static final int REL_DL = 1; public static final int REL_D = 2; public static final int REL_DR = 3; public static final int REL_R = 4; public static final int REL_UR = 5; public static final int REL_U = 6; public static final int REL_UL = 7; public static final int CONNECT_BY_BLOCK = 0; public static final int CONNECT_BY_TILE = 1; public static final int CONNECT_BY_MATERIAL = 2; protected static int[] add(int[] a, int[] b) { if (a.length != b.length) { throw new RuntimeException("arrays to add are not same length"); } int[] c = new int[a.length]; for (int i = 0; i < c.length; i++) { c[i] = a[i] + b[i]; } return c; } protected static int[][] makeNeighborOffset(int left, int down, int right, int up) { int[] l = NORMALS[left]; int[] d = NORMALS[down]; int[] r = NORMALS[right]; int[] u = NORMALS[up]; return new int[][] { l, add(l, d), d, add(d, r), r, add(r, u), u, add(u, l), }; } protected IBlockAccess blockAccess; protected Block block; protected boolean useAO; protected boolean inWorld; protected BlockStateMatcher matcher; protected boolean offsetsComputed; protected boolean haveOffsets; protected int dx; protected int dy; protected int dz; final public IBlockAccess getBlockAccess() { return blockAccess; } final public Block getBlock() { return block; } final public boolean useAO() { return useAO; } final public boolean isInWorld() { return inWorld; } final public void setFilter(BlockStateMatcher matcher) { this.matcher = matcher; } final public BlockStateMatcher getFilter() { return matcher; } public void clear() { blockAccess = null; block = null; useAO = false; inWorld = false; offsetsComputed = false; haveOffsets = false; dx = dy = dz = 0; setFilter(null); } abstract public int getX(); abstract public int getY(); abstract public int getZ(); abstract public int getBlockFace(); abstract public int getTextureFace(); abstract public int getTextureFaceOrig(); abstract public int getFaceForHV(); abstract public boolean match(BlockStateMatcher matcher); abstract public int[] getOffset(int blockFace, int relativeDirection); abstract public boolean setCoordOffsetsForRenderType(); final public int getDX() { return dx; } final public int getDY() { return dy; } final public int getDZ() { return dz; } abstract public boolean shouldConnectByBlock(Block neighbor, int neighborX, int neighborY, int neighborZ); abstract public boolean shouldConnectByTile(Block neighbor, IIcon origIcon, int neighborX, int neighborY, int neighborZ); }
Angelica
src\main\java\com\prupe\mcpatcher\ctm\TileOverride.java
package com.prupe.mcpatcher.ctm; import static com.prupe.mcpatcher.ctm.RenderBlockState.CONNECT_BY_BLOCK; import static com.prupe.mcpatcher.ctm.RenderBlockState.CONNECT_BY_MATERIAL; import static com.prupe.mcpatcher.ctm.RenderBlockState.CONNECT_BY_TILE; import static com.prupe.mcpatcher.ctm.RenderBlockState.NORMALS; import java.util.ArrayList; import java.util.BitSet; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.minecraft.block.Block; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.biome.BiomeAPI; import com.prupe.mcpatcher.mal.block.BlockAPI; import com.prupe.mcpatcher.mal.block.BlockStateMatcher; import com.prupe.mcpatcher.mal.block.RenderPassAPI; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.tile.TileLoader; abstract class TileOverride implements Comparable<TileOverride> { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CONNECTED_TEXTURES, "CTM"); private final PropertiesFile properties; private final String baseFilename; private final TileLoader tileLoader; private final int renderPass; private final int weight; private final List<BlockStateMatcher> matchBlocks; private final Set<String> matchTiles; private final BlockFaceMatcher faceMatcher; private final int connectType; private final boolean innerSeams; private final BitSet biomes; private final BitSet height; private final List<ResourceLocation> tileNames = new ArrayList<>(); protected IIcon[] icons; static TileOverride create(ResourceLocation propertiesFile, TileLoader tileLoader) { if (propertiesFile == null) { return null; } PropertiesFile properties = PropertiesFile.get(logger, propertiesFile); if (properties == null) { return null; } String method = properties.getString("method", "default") .toLowerCase(); TileOverride override = null; switch (method) { case "default", "glass", "ctm" -> override = new TileOverrideImpl.CTM(properties, tileLoader); case "random" -> { override = new TileOverrideImpl.Random1(properties, tileLoader); if (override.getNumberOfTiles() == 1) { override = new TileOverrideImpl.Fixed(properties, tileLoader); } } case "fixed", "static" -> override = new TileOverrideImpl.Fixed(properties, tileLoader); case "bookshelf", "horizontal" -> override = new TileOverrideImpl.Horizontal(properties, tileLoader); case "horizontal+vertical", "h+v" -> override = new TileOverrideImpl.HorizontalVertical( properties, tileLoader); case "vertical" -> override = new TileOverrideImpl.Vertical(properties, tileLoader); case "vertical+horizontal", "v+h" -> override = new TileOverrideImpl.VerticalHorizontal( properties, tileLoader); case "sandstone", "top" -> override = new TileOverrideImpl.Top(properties, tileLoader); case "repeat", "pattern" -> override = new TileOverrideImpl.Repeat(properties, tileLoader); default -> properties.error("unknown method \"%s\"", method); } if (override != null && !properties.valid()) { String status = override.checkTileMap(); if (status != null) { override.properties.error("invalid %s tile map: %s", override.getMethod(), status); } } return override == null || override.isDisabled() ? null : override; } protected TileOverride(PropertiesFile properties, TileLoader tileLoader) { this.properties = properties; String texturesDirectory = properties.getResource() .getResourcePath() .replaceFirst("/[^/]*$", ""); baseFilename = properties.getResource() .getResourcePath() .replaceFirst(".*/", "") .replaceFirst("\\.properties$", ""); this.tileLoader = tileLoader; String renderPassStr = properties.getString("renderPass", ""); renderPass = RenderPassAPI.instance.parseRenderPass(renderPassStr); if (renderPassStr.matches("\\d+") && renderPass >= 0 && renderPass <= RenderPassAPI.MAX_EXTRA_RENDER_PASS) { properties.warning( "renderPass=%s is deprecated, use renderPass=%s instead", renderPassStr, RenderPassAPI.instance.getRenderPassName(renderPass)); } loadIcons(); if (tileNames.isEmpty()) { properties.error("no images found in %s/", texturesDirectory); } String value; if (baseFilename.matches("block\\d+.*")) { value = baseFilename.replaceFirst("block(\\d+).*", "$1"); } else { value = ""; } matchBlocks = getBlockList(properties.getString("matchBlocks", value), properties.getString("metadata", "")); matchTiles = getTileList("matchTiles"); if (matchBlocks.isEmpty() && matchTiles.isEmpty()) { matchTiles.add(baseFilename); } faceMatcher = BlockFaceMatcher.create(properties.getString("faces", "")); String connectType1 = properties.getString("connect", "") .toLowerCase(); switch (connectType1) { case "" -> connectType = matchTiles.isEmpty() ? CONNECT_BY_BLOCK : CONNECT_BY_TILE; case "block" -> connectType = CONNECT_BY_BLOCK; case "tile" -> connectType = CONNECT_BY_TILE; case "material" -> connectType = CONNECT_BY_MATERIAL; default -> { properties.error("invalid connect type %s", connectType1); connectType = CONNECT_BY_BLOCK; } } innerSeams = properties.getBoolean("innerSeams", false); String biomeList = properties.getString("biomes", ""); if (biomeList.isEmpty()) { biomes = null; } else { biomes = new BitSet(); BiomeAPI.parseBiomeList(biomeList, biomes); } height = BiomeAPI.getHeightListProperty(properties, ""); if (renderPass > RenderPassAPI.MAX_EXTRA_RENDER_PASS) { properties.error("invalid renderPass %s", renderPassStr); } else if (renderPass >= 0 && !matchTiles.isEmpty()) { properties.error( "renderPass=%s must be block-based not tile-based", RenderPassAPI.instance.getRenderPassName(renderPass)); } weight = properties.getInt("weight", 0); } private boolean addIcon(ResourceLocation resource) { tileNames.add(resource); return tileLoader.preloadTile(resource, renderPass > RenderPassAPI.MAX_BASE_RENDER_PASS); } private void loadIcons() { tileNames.clear(); String tileList = properties.getString("tiles", ""); ResourceLocation blankResource = RenderPassAPI.instance.getBlankResource(renderPass); if (tileList.isEmpty()) { for (int i = 0;; i++) { ResourceLocation resource = TileLoader .parseTileAddress(properties.getResource(), String.valueOf(i), blankResource); if (!TexturePackAPI.hasResource(resource)) { break; } if (!addIcon(resource)) { break; } } } else { Pattern range = Pattern.compile("(\\d+)-(\\d+)"); for (String token : tileList.split("\\s+")) { Matcher matcher = range.matcher(token); if (token.isEmpty()) { // nothing } else if (matcher.matches()) { try { int from = Integer.parseInt(matcher.group(1)); int to = Integer.parseInt(matcher.group(2)); for (int i = from; i <= to; i++) { ResourceLocation resource = TileLoader .parseTileAddress(properties.getResource(), String.valueOf(i), blankResource); if (TexturePackAPI.hasResource(resource)) { addIcon(resource); } else { properties.warning("could not find image %s", resource); tileNames.add(null); } } } catch (NumberFormatException e) { e.printStackTrace(); } } else { ResourceLocation resource = TileLoader .parseTileAddress(properties.getResource(), token, blankResource); if (resource == null) { tileNames.add(null); } else if (TexturePackAPI.hasResource(resource)) { addIcon(resource); } else { properties.warning("could not find image %s", resource); tileNames.add(null); } } } } } private List<BlockStateMatcher> getBlockList(String property, String defaultMetadata) { List<BlockStateMatcher> blocks = new ArrayList<>(); if (!MCPatcherUtils.isNullOrEmpty(defaultMetadata)) { defaultMetadata = ':' + defaultMetadata; } for (String token : property.split("\\s+")) { if (token.isEmpty()) { // nothing } else if (token.matches("\\d+-\\d+")) { for (int id : MCPatcherUtils.parseIntegerList(token, 0, 65535)) { BlockStateMatcher matcher = BlockAPI.createMatcher(properties, id + defaultMetadata); if (matcher == null) { properties.warning("unknown block id %d", id); } else { blocks.add(matcher); } } } else { BlockStateMatcher matcher = BlockAPI.createMatcher(properties, token + defaultMetadata); if (matcher == null) { properties.warning("unknown block %s", token); } else { blocks.add(matcher); } } } for (BlockStateMatcher matcher : blocks) { matcher.setData(this); } return blocks; } private Set<String> getTileList(String key) { Set<String> list = new HashSet<>(); String property = properties.getString(key, ""); for (String token : property.split("\\s+")) { if (token.isEmpty()) { // nothing } else if (token.contains("/")) { if (!token.endsWith(".png")) { token += ".png"; } ResourceLocation resource = TexturePackAPI.parseResourceLocation(properties.getResource(), token); if (resource != null) { list.add(resource.toString()); } } else { list.add(token); } } return list; } protected int getNumberOfTiles() { return tileNames.size(); } String checkTileMap() { return null; } boolean requiresFace() { return false; } @Override public String toString() { return String.format("%s[%s] (%d tiles)", getMethod(), properties, getNumberOfTiles()); } public final void registerIcons() { icons = new IIcon[tileNames.size()]; for (int i = 0; i < icons.length; i++) { icons[i] = tileLoader.getIcon(tileNames.get(i)); } } final public boolean isDisabled() { return !properties.valid(); } final public List<BlockStateMatcher> getMatchingBlocks() { return matchBlocks; } final public Set<String> getMatchingTiles() { if (MCPatcherUtils.isNullOrEmpty(matchTiles)) { return null; } else { return new HashSet<>(matchTiles); } } final public int getRenderPass() { return renderPass; } final public int getWeight() { return weight; } @Override public int compareTo(TileOverride o) { int result = o.getWeight() - getWeight(); if (result != 0) { return result; } if (o instanceof TileOverride) { return baseFilename.compareTo(((TileOverride) o).baseFilename); } else { return -1; } } final boolean shouldConnect(RenderBlockState renderBlockState, IIcon icon, int relativeDirection) { return shouldConnect( renderBlockState, icon, renderBlockState.getOffset(renderBlockState.getBlockFace(), relativeDirection)); } final boolean shouldConnect(RenderBlockState renderBlockState, IIcon icon, int blockFace, int relativeDirection) { return shouldConnect(renderBlockState, icon, renderBlockState.getOffset(blockFace, relativeDirection)); } private boolean shouldConnect(RenderBlockState renderBlockState, IIcon icon, int[] offset) { IBlockAccess blockAccess = renderBlockState.getBlockAccess(); Block block = renderBlockState.getBlock(); int x = renderBlockState.getX(); int y = renderBlockState.getY(); int z = renderBlockState.getZ(); x += offset[0]; y += offset[1]; z += offset[2]; Block neighbor = blockAccess.getBlock(x, y, z); if (neighbor == null) { return false; } if (block == neighbor) { BlockStateMatcher filter = renderBlockState.getFilter(); if (filter != null && !filter.match(blockAccess, x, y, z)) { return false; } } if (innerSeams) { int blockFace = renderBlockState.getBlockFace(); if (blockFace >= 0) { int[] normal = NORMALS[blockFace]; if (!neighbor.shouldSideBeRendered( blockAccess, x + normal[0], y + normal[1], z + normal[2], blockFace)) { return false; } } } return switch (connectType) { case CONNECT_BY_TILE -> renderBlockState.shouldConnectByTile(neighbor, icon, x, y, z); case CONNECT_BY_BLOCK -> renderBlockState.shouldConnectByBlock(neighbor, x, y, z); case CONNECT_BY_MATERIAL -> block.blockMaterial == neighbor.blockMaterial; default -> false; }; } public final IIcon getTileWorld(RenderBlockState renderBlockState, IIcon origIcon) { if (icons == null) { properties.error("no images loaded, disabling"); return null; } IBlockAccess blockAccess = renderBlockState.getBlockAccess(); Block block = renderBlockState.getBlock(); int x = renderBlockState.getX(); int y = renderBlockState.getY(); int z = renderBlockState.getZ(); if (renderBlockState.getBlockFace() < 0 && requiresFace()) { properties.warning( "method=%s is not supported for non-standard block %s:%d @ %d %d %d", getMethod(), BlockAPI.getBlockName(block), blockAccess.getBlockMetadata(x, y, z), x, y, z); return null; } if (block == null || RenderPassAPI.instance.skipThisRenderPass(block, renderPass)) { return null; } BlockStateMatcher filter = renderBlockState.getFilter(); if (filter != null && !filter.match(blockAccess, x, y, z)) { return null; } if (faceMatcher != null && !faceMatcher.match(renderBlockState)) { return null; } if (height != null && !height.get(y)) { return null; } if (biomes != null && !biomes.get(BiomeAPI.getBiomeIDAt(blockAccess, x, y, z))) { return null; } return getTileWorld_Impl(renderBlockState, origIcon); } public final IIcon getTileHeld(RenderBlockState renderBlockState, IIcon origIcon) { if (icons == null) { properties.error("no images loaded, disabling"); return null; } Block block = renderBlockState.getBlock(); if (block == null || RenderPassAPI.instance.skipThisRenderPass(block, renderPass)) { return null; } int face = renderBlockState.getTextureFace(); if (face < 0 && requiresFace()) { properties.warning("method=%s is not supported for non-standard block %s", getMethod(), renderBlockState); return null; } if (height != null || biomes != null) { return null; } if (faceMatcher != null && !faceMatcher.match(renderBlockState)) { return null; } return getTileHeld_Impl(renderBlockState, origIcon); } abstract String getMethod(); abstract IIcon getTileWorld_Impl(RenderBlockState renderBlockState, IIcon origIcon); abstract IIcon getTileHeld_Impl(RenderBlockState renderBlockState, IIcon origIcon); }
Angelica
src\main\java\com\prupe\mcpatcher\ctm\TileOverrideImpl.java
package com.prupe.mcpatcher.ctm; import static com.prupe.mcpatcher.ctm.RenderBlockState.EAST_FACE; import static com.prupe.mcpatcher.ctm.RenderBlockState.NORTH_FACE; import static com.prupe.mcpatcher.ctm.RenderBlockState.REL_D; import static com.prupe.mcpatcher.ctm.RenderBlockState.REL_DL; import static com.prupe.mcpatcher.ctm.RenderBlockState.REL_DR; import static com.prupe.mcpatcher.ctm.RenderBlockState.REL_L; import static com.prupe.mcpatcher.ctm.RenderBlockState.REL_R; import static com.prupe.mcpatcher.ctm.RenderBlockState.REL_U; import static com.prupe.mcpatcher.ctm.RenderBlockState.REL_UL; import static com.prupe.mcpatcher.ctm.RenderBlockState.REL_UR; import static com.prupe.mcpatcher.ctm.RenderBlockState.TOP_FACE; import net.minecraft.util.IIcon; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.tile.TileLoader; import com.prupe.mcpatcher.mal.util.WeightedIndex; class TileOverrideImpl { final static class CTM extends TileOverride { // Index into this array is formed from these bit values: // 128 64 32 // 1 * 16 // 2 4 8 private static final int[] neighborMap = new int[] { 0, 3, 0, 3, 12, 5, 12, 15, 0, 3, 0, 3, 12, 5, 12, 15, 1, 2, 1, 2, 4, 7, 4, 29, 1, 2, 1, 2, 13, 31, 13, 14, 0, 3, 0, 3, 12, 5, 12, 15, 0, 3, 0, 3, 12, 5, 12, 15, 1, 2, 1, 2, 4, 7, 4, 29, 1, 2, 1, 2, 13, 31, 13, 14, 36, 17, 36, 17, 24, 19, 24, 43, 36, 17, 36, 17, 24, 19, 24, 43, 16, 18, 16, 18, 6, 46, 6, 21, 16, 18, 16, 18, 28, 9, 28, 22, 36, 17, 36, 17, 24, 19, 24, 43, 36, 17, 36, 17, 24, 19, 24, 43, 37, 40, 37, 40, 30, 8, 30, 34, 37, 40, 37, 40, 25, 23, 25, 45, 0, 3, 0, 3, 12, 5, 12, 15, 0, 3, 0, 3, 12, 5, 12, 15, 1, 2, 1, 2, 4, 7, 4, 29, 1, 2, 1, 2, 13, 31, 13, 14, 0, 3, 0, 3, 12, 5, 12, 15, 0, 3, 0, 3, 12, 5, 12, 15, 1, 2, 1, 2, 4, 7, 4, 29, 1, 2, 1, 2, 13, 31, 13, 14, 36, 39, 36, 39, 24, 41, 24, 27, 36, 39, 36, 39, 24, 41, 24, 27, 16, 42, 16, 42, 6, 20, 6, 10, 16, 42, 16, 42, 28, 35, 28, 44, 36, 39, 36, 39, 24, 41, 24, 27, 36, 39, 36, 39, 24, 41, 24, 27, 37, 38, 37, 38, 30, 11, 30, 32, 37, 38, 37, 38, 25, 33, 25, 26, }; CTM(PropertiesFile properties, TileLoader tileLoader) { super(properties, tileLoader); } @Override String getMethod() { return "ctm"; } @Override String checkTileMap() { if (getNumberOfTiles() >= 47) { return null; } else { return "requires at least 47 tiles"; } } @Override boolean requiresFace() { return true; } @Override IIcon getTileWorld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { int neighborBits = 0; for (int bit = 0; bit < 8; bit++) { if (shouldConnect(renderBlockState, origIcon, bit)) { neighborBits |= (1 << bit); } } return icons[neighborMap[neighborBits]]; } @Override IIcon getTileHeld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { return icons[0]; } } static class Horizontal extends TileOverride { // Index into this array is formed from these bit values: // 1 * 2 private static final int[] neighborMap = new int[] { 3, 2, 0, 1, }; Horizontal(PropertiesFile properties, TileLoader tileLoader) { super(properties, tileLoader); } @Override String getMethod() { return "horizontal"; } @Override String checkTileMap() { if (getNumberOfTiles() == 4) { return null; } else { return "requires exactly 4 tiles"; } } @Override IIcon getTileWorld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { int face = renderBlockState.getFaceForHV(); if (face < 0) { return null; } int neighborBits = 0; if (shouldConnect(renderBlockState, origIcon, REL_L)) { neighborBits |= 1; } if (shouldConnect(renderBlockState, origIcon, REL_R)) { neighborBits |= 2; } return icons[neighborMap[neighborBits]]; } @Override IIcon getTileHeld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { return icons[3]; } } final static class HorizontalVertical extends Horizontal { // Index into this array is formed from these bit values: // 32 16 8 // * // 1 2 4 private static final int[] neighborMap = new int[] { 3, 3, 6, 3, 3, 3, 3, 3, 3, 3, 6, 3, 3, 3, 3, 3, 4, 4, 5, 4, 4, 4, 4, 4, 3, 3, 6, 3, 3, 3, 3, 3, 3, 3, 6, 3, 3, 3, 3, 3, 3, 3, 6, 3, 3, 3, 3, 3, 3, 3, 6, 3, 3, 3, 3, 3, 3, 3, 6, 3, 3, 3, 3, 3, }; HorizontalVertical(PropertiesFile properties, TileLoader tileLoader) { super(properties, tileLoader); } @Override String getMethod() { return "horizontal+vertical"; } @Override String checkTileMap() { if (getNumberOfTiles() == 7) { return null; } else { return "requires exactly 7 tiles"; } } @Override IIcon getTileWorld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { IIcon icon = super.getTileWorld_Impl(renderBlockState, origIcon); if (icon != icons[3]) { return icon; } int neighborBits = 0; if (shouldConnect(renderBlockState, origIcon, REL_DL)) { neighborBits |= 1; } if (shouldConnect(renderBlockState, origIcon, REL_D)) { neighborBits |= 2; } if (shouldConnect(renderBlockState, origIcon, REL_DR)) { neighborBits |= 4; } if (shouldConnect(renderBlockState, origIcon, REL_UR)) { neighborBits |= 8; } if (shouldConnect(renderBlockState, origIcon, REL_U)) { neighborBits |= 16; } if (shouldConnect(renderBlockState, origIcon, REL_UL)) { neighborBits |= 32; } return icons[neighborMap[neighborBits]]; } } static class Vertical extends TileOverride { // Index into this array is formed from these bit values: // 2 // * // 1 private static final int[] neighborMap = new int[] { 3, 2, 0, 1, }; Vertical(PropertiesFile properties, TileLoader tileLoader) { super(properties, tileLoader); } @Override String getMethod() { return "vertical"; } @Override String checkTileMap() { if (getNumberOfTiles() == 4) { return null; } else { return "requires exactly 4 tiles"; } } @Override IIcon getTileWorld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { int face = renderBlockState.getFaceForHV(); if (face < 0) { return null; } int neighborBits = 0; if (shouldConnect(renderBlockState, origIcon, REL_D)) { neighborBits |= 1; } if (shouldConnect(renderBlockState, origIcon, REL_U)) { neighborBits |= 2; } return icons[neighborMap[neighborBits]]; } @Override IIcon getTileHeld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { return icons[3]; } } final static class VerticalHorizontal extends Vertical { // Index into this array is formed from these bit values: // 32 16 // 1 * 8 // 2 4 private static final int[] neighborMap = new int[] { 3, 6, 3, 3, 3, 6, 3, 3, 4, 5, 4, 4, 3, 6, 3, 3, 3, 6, 3, 3, 3, 6, 3, 3, 3, 6, 3, 3, 3, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, }; VerticalHorizontal(PropertiesFile properties, TileLoader tileLoader) { super(properties, tileLoader); } @Override String getMethod() { return "vertical+horizontal"; } @Override String checkTileMap() { if (getNumberOfTiles() == 7) { return null; } else { return "requires exactly 7 tiles"; } } @Override IIcon getTileWorld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { IIcon icon = super.getTileWorld_Impl(renderBlockState, origIcon); if (icon != icons[3]) { return icon; } int neighborBits = 0; if (shouldConnect(renderBlockState, origIcon, REL_L)) { neighborBits |= 1; } if (shouldConnect(renderBlockState, origIcon, REL_DL)) { neighborBits |= 2; } if (shouldConnect(renderBlockState, origIcon, REL_DR)) { neighborBits |= 4; } if (shouldConnect(renderBlockState, origIcon, REL_R)) { neighborBits |= 8; } if (shouldConnect(renderBlockState, origIcon, REL_UR)) { neighborBits |= 16; } if (shouldConnect(renderBlockState, origIcon, REL_UL)) { neighborBits |= 32; } return icons[neighborMap[neighborBits]]; } } final static class Top extends TileOverride { Top(PropertiesFile properties, TileLoader tileLoader) { super(properties, tileLoader); } @Override String getMethod() { return "top"; } @Override String checkTileMap() { if (getNumberOfTiles() == 1) { return null; } else { return "requires exactly 1 tile"; } } @Override IIcon getTileWorld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { int face = renderBlockState.getBlockFace(); if (face < 0) { face = NORTH_FACE; } else if (face <= TOP_FACE) { return null; } if (shouldConnect(renderBlockState, origIcon, face, REL_U)) { return icons[0]; } return null; } @Override IIcon getTileHeld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { return null; } } final static class Random1 extends TileOverride { private final int symmetry; private final boolean linked; private final WeightedIndex chooser; Random1(PropertiesFile properties, TileLoader tileLoader) { super(properties, tileLoader); String sym = properties.getString("symmetry", "none"); if (sym.equals("all")) { symmetry = 6; } else if (sym.equals("opposite")) { symmetry = 2; } else { symmetry = 1; } linked = properties.getBoolean("linked", false); chooser = WeightedIndex.create(getNumberOfTiles(), properties.getString("weights", "")); if (chooser == null) { properties.error("invalid weights"); } } @Override String getMethod() { return "random"; } @Override IIcon getTileWorld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { int face = renderBlockState.getBlockFace(); if (face < 0) { face = 0; } int x = renderBlockState.getX(); int y = renderBlockState.getY(); int z = renderBlockState.getZ(); if (linked && renderBlockState.setCoordOffsetsForRenderType()) { x += renderBlockState.getDX(); y += renderBlockState.getDY(); z += renderBlockState.getDZ(); } long hash = WeightedIndex.hash128To64(x, y, z, face / symmetry); int index = chooser.choose(hash); return icons[index]; } @Override IIcon getTileHeld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { return icons[0]; } } final static class Repeat extends TileOverride { private final int width; private final int height; private final int symmetry; Repeat(PropertiesFile properties, TileLoader tileLoader) { super(properties, tileLoader); width = properties.getInt("width", 0); height = properties.getInt("height", 0); if (width <= 0 || height <= 0) { properties.error("invalid width and height (%dx%d)", width, height); } String sym = properties.getString("symmetry", "none"); if (sym.equals("opposite")) { symmetry = ~1; } else { symmetry = -1; } } @Override String getMethod() { return "repeat"; } @Override String checkTileMap() { if (getNumberOfTiles() == width * height) { return null; } else { return String.format("requires exactly %dx%d tiles", width, height); } } @Override IIcon getTileWorld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { int face = renderBlockState.getBlockFace(); if (face < 0) { face = 0; } face &= symmetry; int x = renderBlockState.getX(); int y = renderBlockState.getY(); int z = renderBlockState.getZ(); int[] xOffset = renderBlockState.getOffset(face, REL_R); int[] yOffset = renderBlockState.getOffset(face, REL_D); int offsetX = x * xOffset[0] + y * xOffset[1] + z * xOffset[2]; int offsetY = x * yOffset[0] + y * yOffset[1] + z * yOffset[2]; if (face == NORTH_FACE || face == EAST_FACE) { offsetX--; } offsetX %= width; if (offsetX < 0) { offsetX += width; } offsetY %= height; if (offsetY < 0) { offsetY += height; } return icons[width * offsetY + offsetX]; } @Override IIcon getTileHeld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { return icons[0]; } } final static class Fixed extends TileOverride { Fixed(PropertiesFile properties, TileLoader tileLoader) { super(properties, tileLoader); } @Override String getMethod() { return "fixed"; } @Override String checkTileMap() { if (getNumberOfTiles() == 1) { return null; } else { return "requires exactly 1 tile"; } } @Override IIcon getTileWorld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { return icons[0]; } @Override IIcon getTileHeld_Impl(RenderBlockState renderBlockState, IIcon origIcon) { return icons[0]; } } }
Angelica
src\main\java\com\prupe\mcpatcher\ctm\TileOverrideIterator.java
package com.prupe.mcpatcher.ctm; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.util.IIcon; import com.prupe.mcpatcher.mal.block.BlockStateMatcher; import jss.notfine.config.MCPatcherForgeConfig; abstract public class TileOverrideIterator implements Iterator<TileOverride> { private final Map<Block, List<BlockStateMatcher>> allBlockOverrides; private final Map<String, List<TileOverride>> allTileOverrides; protected IIcon currentIcon; private List<BlockStateMatcher> blockOverrides; private List<TileOverride> tileOverrides; private final Set<TileOverride> skipOverrides = new HashSet<>(); private RenderBlockState renderBlockState; private int blockPos; private int iconPos; private boolean foundNext; private TileOverride nextOverride; private TileOverride lastMatchedOverride; protected TileOverrideIterator(Map<Block, List<BlockStateMatcher>> allBlockOverrides, Map<String, List<TileOverride>> allTileOverrides) { this.allBlockOverrides = allBlockOverrides; this.allTileOverrides = allTileOverrides; } synchronized void clear() { currentIcon = null; blockOverrides = null; tileOverrides = null; nextOverride = null; lastMatchedOverride = null; skipOverrides.clear(); } private synchronized void resetForNextPass() { blockOverrides = null; tileOverrides = allTileOverrides.get(currentIcon.getIconName()); blockPos = 0; iconPos = 0; foundNext = false; } @Override public synchronized boolean hasNext() { if (foundNext) { return true; } if (tileOverrides != null) { while (iconPos < tileOverrides.size()) { if (checkOverride(tileOverrides.get(iconPos++))) { renderBlockState.setFilter(null); return true; } } } if (blockOverrides != null) { while (blockPos < blockOverrides.size()) { BlockStateMatcher matcher = blockOverrides.get(blockPos++); if (renderBlockState.match(matcher) && checkOverride((TileOverride) matcher.getData())) { renderBlockState.setFilter(matcher); return true; } } } return false; } @Override public synchronized TileOverride next() { if (!foundNext) { throw new IllegalStateException("next called before hasNext() == true"); } foundNext = false; return nextOverride; } @Override public synchronized void remove() { throw new UnsupportedOperationException("remove not supported"); } private synchronized boolean checkOverride(TileOverride override) { if (override != null && !override.isDisabled() && !skipOverrides.contains(override)) { foundNext = true; nextOverride = override; return true; } else { return false; } } public synchronized TileOverride go(RenderBlockState renderBlockState, IIcon origIcon) { this.renderBlockState = renderBlockState; renderBlockState.setFilter(null); currentIcon = origIcon; blockOverrides = allBlockOverrides.get(renderBlockState.getBlock()); tileOverrides = allTileOverrides.get(origIcon.getIconName()); blockPos = 0; iconPos = 0; foundNext = false; nextOverride = null; lastMatchedOverride = null; skipOverrides.clear(); pass: for (int pass = 0; pass < MCPatcherForgeConfig.ConnectedTextures.maxRecursion; pass++) { while (hasNext()) { TileOverride override = next(); IIcon newIcon = getTile(override, renderBlockState, origIcon); if (newIcon != null) { lastMatchedOverride = override; skipOverrides.add(override); currentIcon = newIcon; resetForNextPass(); continue pass; } } break; } return lastMatchedOverride; } public synchronized IIcon getIcon() { return currentIcon; } abstract protected IIcon getTile(TileOverride override, RenderBlockState renderBlockState, IIcon origIcon); public static final class IJK extends TileOverrideIterator { IJK(Map<Block, List<BlockStateMatcher>> blockOverrides, Map<String, List<TileOverride>> tileOverrides) { super(blockOverrides, tileOverrides); } @Override protected synchronized IIcon getTile(TileOverride override, RenderBlockState renderBlockState, IIcon origIcon) { return override.getTileWorld(renderBlockState, origIcon); } } public static final class Metadata extends TileOverrideIterator { Metadata(Map<Block, List<BlockStateMatcher>> blockOverrides, Map<String, List<TileOverride>> tileOverrides) { super(blockOverrides, tileOverrides); } @Override protected synchronized IIcon getTile(TileOverride override, RenderBlockState renderBlockState, IIcon origIcon) { return override.getTileHeld(renderBlockState, origIcon); } } }
Angelica
src\main\java\com\prupe\mcpatcher\hd\CustomAnimation.java
package com.prupe.mcpatcher.hd; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import org.lwjgl.util.glu.GLU; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.resource.GLAPI; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.ResourceList; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.resource.TexturePackChangeHandler; import jss.notfine.config.MCPatcherForgeConfig; public class CustomAnimation implements Comparable<CustomAnimation> { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.EXTENDED_HD, "Animation"); private static final boolean enable = MCPatcherForgeConfig.ExtendedHD.animations; private static final Set<PropertiesFile> pending = new HashSet<>(); private static final List<CustomAnimation> animations = new ArrayList<>(); private final PropertiesFile properties; private final ResourceLocation dstName; private final ResourceLocation srcName; private final int mipmapLevel; private final ByteBuffer imageData; private final int x; private final int y; private final int w; private final int h; private int currentFrame; private int currentDelay; private int numFrames; private int[] tileOrder; private int[] tileDelay; private final int numTiles; private boolean error; static { TexturePackChangeHandler.register(new TexturePackChangeHandler(MCPatcherUtils.EXTENDED_HD, 1) { @Override public void beforeChange() { if (!pending.isEmpty()) { logger.fine("%d animations were never registered:", pending.size()); for (PropertiesFile properties : pending) { logger.fine(" %s", properties); } pending.clear(); } animations.clear(); MipmapHelper.reset(); FancyDial.clearAll(); } @Override public void afterChange() { if (enable) { for (ResourceLocation resource : ResourceList.getInstance() .listResources(TexturePackAPI.MCPATCHER_SUBDIR + "anim", ".properties", false)) { PropertiesFile properties = PropertiesFile.get(logger, resource); if (properties != null) { pending.add(properties); } } } FancyDial.registerAnimations(); } }); } public static void updateAll() { if (!pending.isEmpty()) { try { checkPendingAnimations(); } catch (Exception e) { e.printStackTrace(); logger.error("%d remaining animations cleared", pending.size()); pending.clear(); } } for (CustomAnimation animation : animations) { animation.update(); } } private static void checkPendingAnimations() { List<PropertiesFile> done = new ArrayList<>(); for (PropertiesFile properties : pending) { ResourceLocation textureName = properties.getResourceLocation("to", ""); if (TexturePackAPI.isTextureLoaded(textureName)) { addStrip(properties); done.add(properties); } } if (!done.isEmpty()) { for (PropertiesFile name : done) { pending.remove(name); } Collections.sort(animations); } } private static void addStrip(PropertiesFile properties) { ResourceLocation dstName = properties.getResourceLocation("to", ""); if (dstName == null) { properties.error("missing to= property"); return; } ResourceLocation srcName = properties.getResourceLocation("from", ""); if (srcName == null) { properties.error("missing from= property"); return; } BufferedImage srcImage = TexturePackAPI.getImage(srcName); if (srcImage == null) { properties.error("image %s not found in texture pack", srcName); return; } int x = properties.getInt("x", 0); int y = properties.getInt("y", 0); int w = properties.getInt("w", 0); int h = properties.getInt("h", 0); if (dstName.toString() .startsWith("minecraft:textures/atlas/")) { properties.error("animations cannot have a target of %s", dstName); return; } if (x < 0 || y < 0 || w <= 0 || h <= 0) { properties.error("%s has invalid dimensions x=%d,y=%d,w=%d,h=%d", srcName, x, y, w, h); return; } TexturePackAPI.bindTexture(dstName); int dstWidth = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); int dstHeight = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); int levels = MipmapHelper.getMipmapLevelsForCurrentTexture(); if (x + w > dstWidth || y + h > dstHeight) { properties.error( "%s dimensions x=%d,y=%d,w=%d,h=%d exceed %s size %dx%d", srcName, x, y, w, h, dstName, dstWidth, dstHeight); return; } int width = srcImage.getWidth(); int height = srcImage.getHeight(); if (width != w) { srcImage = resizeImage(srcImage, w); width = srcImage.getWidth(); height = srcImage.getHeight(); } if (width != w || height < h) { properties.error("%s dimensions %dx%d do not match %dx%d", srcName, width, height, w, h); return; } ByteBuffer imageData = ByteBuffer.allocateDirect(4 * width * height); int[] argb = new int[width * height]; byte[] rgba = new byte[4 * width * height]; srcImage.getRGB(0, 0, width, height, argb, 0, width); ARGBtoRGBA(argb, rgba); imageData.put(rgba) .flip(); for (int mipmapLevel = 0; mipmapLevel <= levels; mipmapLevel++) { add(new CustomAnimation(properties, srcName, dstName, mipmapLevel, x, y, w, h, imageData, height / h)); if (((x | y | w | h) & 0x1) != 0 || w <= 0 || h <= 0) { break; } ByteBuffer newImage = ByteBuffer.allocateDirect(width * height); MipmapHelper.scaleHalf(imageData.asIntBuffer(), width, height, newImage.asIntBuffer(), 0); imageData = newImage; width >>= 1; height >>= 1; x >>= 1; y >>= 1; w >>= 1; h >>= 1; } } private static void add(CustomAnimation animation) { if (animation != null) { animations.add(animation); if (animation.mipmapLevel == 0) { logger.fine("new %s", animation); } } } private CustomAnimation(PropertiesFile properties, ResourceLocation srcName, ResourceLocation dstName, int mipmapLevel, int x, int y, int w, int h, ByteBuffer imageData, int numFrames) { this.properties = properties; this.srcName = srcName; this.dstName = dstName; this.mipmapLevel = mipmapLevel; this.x = x; this.y = y; this.w = w; this.h = h; this.imageData = imageData; this.numFrames = numFrames; currentFrame = -1; numTiles = numFrames; loadProperties(properties); } void update() { if (error) { return; } int texture = TexturePackAPI.getTextureIfLoaded(dstName); if (texture < 0) { return; } if (--currentDelay > 0) { return; } if (++currentFrame >= numFrames) { currentFrame = 0; } GLAPI.glBindTexture(texture); update(texture, 0, 0); int glError = GL11.glGetError(); if (glError != 0) { logger.severe("%s: %s", this, GLU.gluErrorString(glError)); error = true; return; } currentDelay = getDelay(); } public int compareTo(CustomAnimation o) { return dstName.toString() .compareTo(o.dstName.toString()); } @Override public String toString() { return String.format( "CustomAnimation{%s %s %dx%d -> %s%s @ %d,%d (%d frames)}", properties, srcName, w, h, dstName, (mipmapLevel > 0 ? "#" + mipmapLevel : ""), x, y, numFrames); } private static void ARGBtoRGBA(int[] src, byte[] dest) { for (int i = 0; i < src.length; i++) { int v = src[i]; dest[(i * 4) + 3] = (byte) ((v >> 24) & 0xff); dest[(i * 4) + 0] = (byte) ((v >> 16) & 0xff); dest[(i * 4) + 1] = (byte) ((v >> 8) & 0xff); dest[(i * 4) + 2] = (byte) ((v >> 0) & 0xff); } } private static BufferedImage resizeImage(BufferedImage image, int width) { if (width == image.getWidth()) { return image; } int height = image.getHeight() * width / image.getWidth(); logger.finer("resizing to %dx%d", width, height); BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics2D = newImage.createGraphics(); graphics2D.drawImage(image, 0, 0, width, height, null); return newImage; } private void loadProperties(PropertiesFile properties) { loadTileOrder(properties); if (tileOrder == null) { tileOrder = new int[numFrames]; for (int i = 0; i < numFrames; i++) { tileOrder[i] = i % numTiles; } } tileDelay = new int[numFrames]; loadTileDelay(properties); for (int i = 0; i < numFrames; i++) { tileDelay[i] = Math.max(tileDelay[i], 1); } } private void loadTileOrder(PropertiesFile properties) { if (properties == null) { return; } int i = 0; for (; getIntValue(properties, "tile.", i) != null; i++) {} if (i > 0) { numFrames = i; tileOrder = new int[numFrames]; for (i = 0; i < numFrames; i++) { tileOrder[i] = Math.abs(getIntValue(properties, "tile.", i)) % numTiles; } } } private void loadTileDelay(PropertiesFile properties) { if (properties == null) { return; } Integer defaultValue = getIntValue(properties, "duration"); for (int i = 0; i < numFrames; i++) { Integer value = getIntValue(properties, "duration.", i); if (value != null) { tileDelay[i] = value; } else if (defaultValue != null) { tileDelay[i] = defaultValue; } } } private static Integer getIntValue(PropertiesFile properties, String key) { try { String value = properties.getString(key, ""); if (value != null && value.matches("^\\d+$")) { return Integer.parseInt(value); } } catch (NumberFormatException ignore) {} return null; } private static Integer getIntValue(PropertiesFile properties, String prefix, int index) { return getIntValue(properties, prefix + index); } // Without the cast the code won't compile @SuppressWarnings("RedundantCast") private void update(int texture, int dx, int dy) { GL11.glTexSubImage2D( GL11.GL_TEXTURE_2D, mipmapLevel, x + dx, y + dy, w, h, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) imageData.position(4 * w * h * tileOrder[currentFrame])); } private int getDelay() { return tileDelay[currentFrame]; } }
Angelica
src\main\java\com\prupe\mcpatcher\hd\FancyDial.java
package com.prupe.mcpatcher.hd; import java.awt.image.BufferedImage; import java.io.File; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.imageio.ImageIO; import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureClock; import net.minecraft.client.renderer.texture.TextureCompass; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.EXTFramebufferObject; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GLContext; import org.lwjgl.util.glu.GLU; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.resource.BlendMethod; import com.prupe.mcpatcher.mal.resource.GLAPI; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.util.InputHandler; import jss.notfine.config.MCPatcherForgeConfig; public class FancyDial { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.EXTENDED_HD, "Animation"); private static final double ANGLE_UNSET = Double.MAX_VALUE; private static final int NUM_SCRATCH_TEXTURES = 3; private static final boolean fboSupported = GLContext.getCapabilities().GL_EXT_framebuffer_object; private static final boolean gl13Supported = GLContext.getCapabilities().OpenGL13; private static final boolean enableCompass = MCPatcherForgeConfig.ExtendedHD.fancyCompass; private static final boolean enableClock = MCPatcherForgeConfig.ExtendedHD.fancyClock; private static final boolean useGL13 = gl13Supported && MCPatcherForgeConfig.ExtendedHD.useGL13; private static final boolean useScratchTexture = MCPatcherForgeConfig.ExtendedHD.useScratchTexture; private static final int glAttributes; private static boolean initialized; private static boolean active; private static final int drawList = GL11.glGenLists(1); private static final Map<TextureAtlasSprite, ResourceLocation> setupInfo = new IdentityHashMap<>(); private static final Map<TextureAtlasSprite, FancyDial> instances = new IdentityHashMap<>(); private static int warnCount; private final TextureAtlasSprite icon; private final String name; private final int x0; private final int y0; private final int width; private final int height; private final ByteBuffer scratchBuffer; private final FBO[] scratchFBO = new FBO[NUM_SCRATCH_TEXTURES]; private FBO itemsFBO; private int scratchIndex; private Map<Double, ByteBuffer> itemFrames = new TreeMap<>(); private int outputFrames; private boolean ok; private double lastAngle = ANGLE_UNSET; private boolean lastItemFrameRenderer; private final List<Layer> layers = new ArrayList<>(); private InputHandler keyboard; private static final float STEP = 0.01f; private float scaleXDelta; private float scaleYDelta; private float offsetXDelta; private float offsetYDelta; static { logger.config("fbo: supported=%s", fboSupported); logger.config("GL13: supported=%s, enabled=%s", gl13Supported, useGL13); int bits = GL11.GL_VIEWPORT_BIT | GL11.GL_SCISSOR_BIT | GL11.GL_DEPTH_BITS | GL11.GL_LIGHTING_BIT; if (useGL13) { bits |= GL13.GL_MULTISAMPLE_BIT; } glAttributes = bits; GL11.glNewList(drawList, GL11.GL_COMPILE); drawBox(); GL11.glEndList(); } public static void setup(TextureAtlasSprite icon) { if (!fboSupported) { return; } String name = icon.getIconName() .replaceFirst("^minecraft:items/", ""); if ("compass".equals(name)) { if (!enableCompass) { return; } } else if ("clock".equals(name)) { if (!enableClock) { return; } } else { logger.warning("ignoring custom animation for %s not compass or clock", name); return; } ResourceLocation resource = TexturePackAPI.newMCPatcherResourceLocation("dial/" + name + ".properties"); if (TexturePackAPI.hasResource(resource)) { logger.fine("found custom %s (%s)", name, resource); setupInfo.put(icon, resource); active = true; } } public static boolean update(TextureAtlasSprite icon, boolean itemFrameRenderer) { if (!initialized) { logger.finer("deferring %s update until initialization finishes", icon.getIconName()); return false; } if (!active) { return false; } int oldFB = GL11.glGetInteger(EXTFramebufferObject.GL_FRAMEBUFFER_BINDING_EXT); if (oldFB != 0 && warnCount < 10) { logger.finer("rendering %s while non-default framebuffer %d is active", icon.getIconName(), oldFB); warnCount++; } int oldTexture = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); try { FancyDial instance = getInstance(icon); return instance != null && instance.render(itemFrameRenderer); } finally { EXTFramebufferObject.glBindFramebufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, oldFB); GLAPI.glBindTexture(oldTexture); } } static void clearAll() { logger.finer("FancyDial.clearAll"); if (initialized) { active = false; setupInfo.clear(); } for (FancyDial instance : instances.values()) { if (instance != null) { instance.finish(); } } instances.clear(); initialized = true; } static void registerAnimations() { ITextureObject texture = TexturePackAPI.getTextureObject(TexturePackAPI.ITEMS_PNG); if (texture instanceof TextureMap map) { @SuppressWarnings("unchecked") List<TextureAtlasSprite> animations = map.listAnimatedSprites; for (FancyDial instance : instances.values()) { instance.registerAnimation(animations); } } } void registerAnimation(List<TextureAtlasSprite> animations) { if (animations.contains(icon)) { return; } animations.add(icon); if (icon.framesTextureData == null) { icon.framesTextureData = new ArrayList<>(); } if (icon.framesTextureData.isEmpty()) { /* * TODO: figure out how to handle the code assuming int[][] <-> int[] due to 1.6 -> 1.7 * int[] dummyRGB = new int[width * height]; * Arrays.fill(dummyRGB, 0xffff00ff); */ int[][] dummyRGB = new int[width * height][]; Arrays.fill(dummyRGB[0], 0xffff00ff); icon.framesTextureData.add(dummyRGB); } logger.fine("registered %s animation", name); } private static FancyDial getInstance(TextureAtlasSprite icon) { if (instances.containsKey(icon)) { return instances.get(icon); } ResourceLocation resource = setupInfo.remove(icon); instances.put(icon, null); if (resource == null) { return null; } PropertiesFile properties = PropertiesFile.get(logger, resource); if (properties == null) { return null; } try { FancyDial instance = new FancyDial(icon, properties); if (instance.ok) { instances.put(icon, instance); return instance; } instance.finish(); } catch (Exception e) { e.printStackTrace(); } return null; } private FancyDial(TextureAtlasSprite icon, PropertiesFile properties) { this.icon = icon; name = icon.getIconName(); x0 = icon.getOriginX(); y0 = icon.getOriginY(); width = icon.getIconWidth(); height = icon.getIconHeight(); scratchBuffer = ByteBuffer.allocateDirect(4 * width * height); int itemsTexture = TexturePackAPI.getTextureIfLoaded(TexturePackAPI.ITEMS_PNG); if (itemsTexture < 0) { logger.severe("could not get items texture"); return; } itemsFBO = new FBO(itemsTexture, x0, y0, width, height); if (useScratchTexture) { logger.fine("rendering %s to %dx%d scratch texture", name, width, height); for (int i = 0; i < scratchFBO.length; i++) { scratchFBO[i] = new FBO(width, height); } } else { logger.fine("rendering %s directly to atlas", name); } boolean debug = false; for (int i = 0;; i++) { Layer layer = newLayer(properties, "." + i); if (layer == null) { if (i > 0) { break; } continue; } layers.add(layer); debug |= layer.debug; logger.fine(" new %s", layer); } keyboard = new InputHandler(name, debug); if (layers.size() < 2) { logger.error("custom %s needs at least two layers defined", name); return; } outputFrames = properties.getInt("outputFrames", 0); int glError = GL11.glGetError(); if (glError != 0) { logger.severe("%s during %s setup", GLU.gluErrorString(glError), name); return; } ok = true; } private boolean render(boolean itemFrameRenderer) { if (!ok) { return false; } if (!itemFrameRenderer) { boolean changed = true; if (!keyboard.isEnabled()) { changed = false; } else if (keyboard.isKeyPressed(Keyboard.KEY_NUMPAD2)) { scaleYDelta -= STEP; } else if (keyboard.isKeyPressed(Keyboard.KEY_NUMPAD8)) { scaleYDelta += STEP; } else if (keyboard.isKeyPressed(Keyboard.KEY_NUMPAD4)) { scaleXDelta -= STEP; } else if (keyboard.isKeyPressed(Keyboard.KEY_NUMPAD6)) { scaleXDelta += STEP; } else if (keyboard.isKeyPressed(Keyboard.KEY_DOWN)) { offsetYDelta += STEP; } else if (keyboard.isKeyPressed(Keyboard.KEY_UP)) { offsetYDelta -= STEP; } else if (keyboard.isKeyPressed(Keyboard.KEY_LEFT)) { offsetXDelta -= STEP; } else if (keyboard.isKeyPressed(Keyboard.KEY_RIGHT)) { offsetXDelta += STEP; } else if (keyboard.isKeyPressed(Keyboard.KEY_MULTIPLY)) { scaleXDelta = scaleYDelta = offsetXDelta = offsetYDelta = 0.0f; } else { changed = false; } if (changed) { logger.info(""); logger.info("scaleX %+f", scaleXDelta); logger.info("scaleY %+f", scaleYDelta); logger.info("offsetX %+f", offsetXDelta); logger.info("offsetY %+f", offsetYDelta); lastAngle = ANGLE_UNSET; } if (outputFrames > 0) { writeCustomImage(); outputFrames = 0; } } double angle = getAngle(icon); if (!useScratchTexture) { // render directly to items.png if (angle != lastAngle) { renderToItems(angle); lastAngle = angle; } } else if (itemFrameRenderer) { // look in itemFrames cache first ByteBuffer buffer = itemFrames.get(angle); if (buffer == null) { logger.fine("rendering %s at angle %f for item frame", name, angle); buffer = ByteBuffer.allocateDirect(width * height * 4); renderToItems(angle); itemsFBO.read(buffer); itemFrames.put(angle, buffer); } else { itemsFBO.write(buffer); } lastItemFrameRenderer = true; } else if (lastAngle == ANGLE_UNSET) { // first time rendering - render all N copies for (FBO fbo : scratchFBO) { renderToFB(angle, fbo); } scratchFBO[0].read(scratchBuffer); itemsFBO.write(scratchBuffer); lastAngle = angle; scratchIndex = 0; } else if (lastItemFrameRenderer || angle != lastAngle) { // render to buffer i + 1 // update items.png from buffer i int nextIndex = (scratchIndex + 1) % NUM_SCRATCH_TEXTURES; if (angle != lastAngle) { renderToFB(angle, scratchFBO[nextIndex]); scratchFBO[scratchIndex].read(scratchBuffer); } itemsFBO.write(scratchBuffer); lastAngle = angle; scratchIndex = nextIndex; lastItemFrameRenderer = false; } int glError = GL11.glGetError(); if (glError != 0) { logger.severe("%s during %s update", GLU.gluErrorString(glError), name); ok = false; } return ok; } private void writeCustomImage() { try { BufferedImage image = new BufferedImage(width, outputFrames * height, BufferedImage.TYPE_INT_ARGB); IntBuffer intBuffer = scratchBuffer.asIntBuffer(); int[] argb = new int[width * height]; File path = MCPatcherUtils.getGamePath("custom_" + name + ".png"); logger.info("generating %d %s frames", outputFrames, name); for (int i = 0; i < outputFrames; i++) { renderToItems(i * (360.0 / outputFrames)); itemsFBO.read(scratchBuffer); intBuffer.position(0); for (int j = 0; j < argb.length; j++) { switch (MipmapHelper.TEX_FORMAT) { case GL12.GL_BGRA: int bgra = intBuffer.get(j); argb[j] = (bgra << 24) | ((bgra & 0xff00) << 8) | ((bgra & 0xff0000) >> 8) | (bgra >>> 24); break; default: if (i == 0 && j == 0) { logger.warning( "unhandled texture format %d, color channels may be incorrect", MipmapHelper.TEX_FORMAT); } // fall through case GL11.GL_RGBA: argb[j] = Integer.rotateRight(intBuffer.get(j), 8); break; } } image.setRGB(0, i * height, width, height, argb, 0, width); } ImageIO.write(image, "png", path); logger.info("wrote %dx%d %s", image.getWidth(), image.getHeight(), path.getPath()); } catch (Exception e) { e.printStackTrace(); } } private void renderToItems(double angle) { renderToFB(angle, itemsFBO); } private void renderToFB(double angle, FBO fbo) { if (fbo != null) { fbo.bind(); renderImpl(angle); fbo.unbind(); } } private void renderImpl(double angle) { for (Layer layer : layers) { layer.blendMethod.applyBlending(); GL11.glPushMatrix(); TexturePackAPI.bindTexture(layer.textureName); float offsetX = layer.offsetX; float offsetY = layer.offsetY; float scaleX = layer.scaleX; float scaleY = layer.scaleY; if (layer.debug) { offsetX += offsetXDelta; offsetY += offsetYDelta; scaleX += scaleXDelta; scaleY += scaleYDelta; } GL11.glTranslatef(offsetX, offsetY, 0.0f); GL11.glScalef(scaleX, scaleY, 1.0f); float layerAngle = (float) (angle * layer.rotationMultiplier + layer.rotationOffset); GL11.glRotatef(layerAngle, 0.0f, 0.0f, 1.0f); GL11.glCallList(drawList); GL11.glPopMatrix(); } } private static void drawBox() { GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2f(0.0f, 0.0f); GL11.glVertex3f(-1.0f, -1.0f, 0.0f); GL11.glTexCoord2f(1.0f, 0.0f); GL11.glVertex3f(1.0f, -1.0f, 0.0f); GL11.glTexCoord2f(1.0f, 1.0f); GL11.glVertex3f(1.0f, 1.0f, 0.0f); GL11.glTexCoord2f(0.0f, 1.0f); GL11.glVertex3f(-1.0f, 1.0f, 0.0f); GL11.glEnd(); } private void finish() { for (int i = 0; i < scratchFBO.length; i++) { if (scratchFBO[i] != null) { scratchFBO[i].delete(); scratchFBO[i] = null; } } if (itemsFBO != null) { itemsFBO.delete(); itemsFBO = null; } itemFrames.clear(); layers.clear(); ok = false; } @Override public String toString() { return String.format("FancyDial{%s, %dx%d @ %d,%d}", name, width, height, x0, y0); } @Override protected void finalize() throws Throwable { finish(); super.finalize(); } private static double getAngle(IIcon icon) { if (icon instanceof TextureCompass) { return ((TextureCompass) icon).currentAngle * 180.0 / Math.PI; } else if (icon instanceof TextureClock) { return ((TextureClock) icon).field_94239_h * 360.0; // currentAngle } else { return 0.0; } } Layer newLayer(PropertiesFile properties, String suffix) { ResourceLocation textureResource = properties.getResourceLocation("source" + suffix, ""); if (textureResource == null) { return null; } if (!TexturePackAPI.hasResource(textureResource)) { properties.error("could not read %s", textureResource); return null; } float scaleX = properties.getFloat("scaleX" + suffix, 1.0f); float scaleY = properties.getFloat("scaleY" + suffix, 1.0f); float offsetX = properties.getFloat("offsetX" + suffix, 0.0f); float offsetY = properties.getFloat("offsetY" + suffix, 0.0f); float angleMultiplier = properties.getFloat("rotationSpeed" + suffix, 0.0f); float angleOffset = properties.getFloat("rotationOffset" + suffix, 0.0f); String blend = properties.getString("blend" + suffix, "alpha"); BlendMethod blendMethod = BlendMethod.parse(blend); if (blendMethod == null) { properties.error("unknown blend method %s", blend); return null; } boolean debug = properties.getBoolean("debug" + suffix, false); return new Layer( textureResource, scaleX, scaleY, offsetX, offsetY, angleMultiplier, angleOffset, blendMethod, debug); } private class Layer { final ResourceLocation textureName; final float scaleX; final float scaleY; final float offsetX; final float offsetY; final float rotationMultiplier; final float rotationOffset; final BlendMethod blendMethod; final boolean debug; Layer(ResourceLocation textureName, float scaleX, float scaleY, float offsetX, float offsetY, float rotationMultiplier, float rotationOffset, BlendMethod blendMethod, boolean debug) { this.textureName = textureName; this.scaleX = scaleX; this.scaleY = scaleY; this.offsetX = offsetX; this.offsetY = offsetY; this.rotationMultiplier = rotationMultiplier; this.rotationOffset = rotationOffset; this.blendMethod = blendMethod; this.debug = debug; } @Override public String toString() { return String.format( "Layer{%s %f %f %+f %+f x%f}", textureName, scaleX, scaleY, offsetX, offsetY, rotationMultiplier); } } private static class FBO { private final int texture; private final boolean ownTexture; private final int x0; private final int y0; private final int width; private final int height; private final int frameBuffer; private boolean lightmapEnabled; private boolean deleted; FBO(int width, int height) { this(blankTexture(width, height), true, 0, 0, width, height); } FBO(int texture, int x0, int y0, int width, int height) { this(texture, false, x0, y0, width, height); } private FBO(int texture, boolean ownTexture, int x0, int y0, int width, int height) { this.texture = texture; this.ownTexture = ownTexture; this.x0 = x0; this.y0 = y0; this.width = width; this.height = height; frameBuffer = EXTFramebufferObject.glGenFramebuffersEXT(); if (frameBuffer < 0) { throw new RuntimeException("could not get framebuffer object"); } GLAPI.glBindTexture(texture); EXTFramebufferObject.glBindFramebufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, frameBuffer); EXTFramebufferObject.glFramebufferTexture2DEXT( EXTFramebufferObject.GL_FRAMEBUFFER_EXT, EXTFramebufferObject.GL_COLOR_ATTACHMENT0_EXT, GL11.GL_TEXTURE_2D, texture, 0); } void bind() { EXTFramebufferObject.glBindFramebufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, frameBuffer); GL11.glPushAttrib(glAttributes); GL11.glViewport(x0, y0, width, height); GL11.glEnable(GL11.GL_SCISSOR_TEST); GL11.glScissor(x0, y0, width, height); lightmapEnabled = false; if (gl13Supported) { GL13.glActiveTexture(GL13.GL_TEXTURE1); lightmapEnabled = GL11.glIsEnabled(GL11.GL_TEXTURE_2D); if (lightmapEnabled) { GL11.glDisable(GL11.GL_TEXTURE_2D); } GL13.glActiveTexture(GL13.GL_TEXTURE0); } GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glAlphaFunc(GL11.GL_GREATER, 0.01f); if (useGL13) { GL11.glDisable(GL13.GL_MULTISAMPLE); } GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPushMatrix(); GL11.glLoadIdentity(); GL11.glOrtho(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glLoadIdentity(); } void unbind() { GL11.glPopAttrib(); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPopMatrix(); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPopMatrix(); if (lightmapEnabled) { GL13.glActiveTexture(GL13.GL_TEXTURE1); GL11.glEnable(GL11.GL_TEXTURE_2D); GL13.glActiveTexture(GL13.GL_TEXTURE0); } GL11.glEnable(GL11.GL_BLEND); GLAPI.glBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); EXTFramebufferObject.glBindFramebufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, 0); } void read(ByteBuffer buffer) { EXTFramebufferObject.glBindFramebufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, frameBuffer); buffer.position(0); GL11.glReadPixels(x0, y0, width, height, MipmapHelper.TEX_FORMAT, MipmapHelper.TEX_DATA_TYPE, buffer); } void write(ByteBuffer buffer) { GLAPI.glBindTexture(texture); buffer.position(0); GL11.glTexSubImage2D( GL11.GL_TEXTURE_2D, 0, x0, y0, width, height, MipmapHelper.TEX_FORMAT, MipmapHelper.TEX_DATA_TYPE, buffer); } void delete() { if (!deleted) { deleted = true; if (ownTexture) { GL11.glDeleteTextures(texture); } EXTFramebufferObject.glDeleteFramebuffersEXT(frameBuffer); } } @Override protected void finalize() throws Throwable { delete(); super.finalize(); } private static int blankTexture(int width, int height) { int texture = GL11.glGenTextures(); MipmapHelper.setupTexture(texture, width, height, "scratch"); return texture; } } }
Angelica
src\main\java\com\prupe\mcpatcher\hd\FontUtils.java
package com.prupe.mcpatcher.hd; import java.awt.image.BufferedImage; import java.util.HashSet; import java.util.Map; import java.util.Set; import net.minecraft.client.gui.FontRenderer; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.resource.TexturePackChangeHandler; import jss.notfine.config.MCPatcherForgeConfig; import jss.notfine.util.FontRendererExpansion; public class FontUtils { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.EXTENDED_HD); private static final boolean enable = MCPatcherForgeConfig.ExtendedHD.hdFont; private static final boolean enableNonHD = MCPatcherForgeConfig.ExtendedHD.nonHDFontWidth; private static final int ROWS = 16; private static final int COLS = 16; public static final char[] AVERAGE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123467890" .toCharArray(); public static final int[] SPACERS = new int[] { 0x02028bfe, 0x02808080, 0x0dffffff }; private static final boolean showLines = false; private static final Set<FontRenderer> allRenderers = new HashSet<>(); static { TexturePackChangeHandler.register(new TexturePackChangeHandler(MCPatcherUtils.HD_FONT, 1) { @Override public void initialize() {} @Override public void beforeChange() {} @Override public void afterChange() { for (FontRenderer renderer : allRenderers) { renderer.readFontTexture(); } } }); } public static void init() {} public static ResourceLocation getFontName(FontRenderer fontRenderer, ResourceLocation font, float hdFontAdj) { FontRendererExpansion expansion = ((FontRendererExpansion) fontRenderer); if (expansion.getDefaultFont() == null) { expansion.setDefaultFont(font); } ResourceLocation defaultFont = expansion.getDefaultFont(); if (expansion.getHDFont() == null) { String namespace = defaultFont.getResourceDomain(); String name = defaultFont.getResourcePath() .replaceAll(".*/", ""); expansion.setHDFont(new ResourceLocation(namespace, TexturePackAPI.MCPATCHER_SUBDIR + "font/" + name)); } ResourceLocation hdFont = expansion.getHDFont(); ResourceLocation newFont; if (enable && TexturePackAPI.hasResource(hdFont)) { if (!hdFont.equals(defaultFont)) { logger.fine("using %s instead of %s", hdFont, defaultFont); } expansion.setIsHD(true); newFont = hdFont; } else { logger.fine("using default %s", defaultFont); expansion.setIsHD(enable && enableNonHD); newFont = defaultFont; } expansion.setFontAdj(expansion.getIsHD() ? hdFontAdj : 1.0f); return newFont; } public static float[] computeCharWidthsf(FontRenderer fontRenderer, ResourceLocation filename, BufferedImage image, int[] rgb, int[] charWidth) { float[] charWidthf = new float[charWidth.length]; if (!((FontRendererExpansion) fontRenderer).getIsHD()) { for (int i = 0; i < charWidth.length; i++) { charWidthf[i] = charWidth[i]; } charWidthf[32] = 4.0f; return charWidthf; } allRenderers.add(fontRenderer); int width = image.getWidth(); int height = image.getHeight(); int colWidth = width / COLS; int rowHeight = height / ROWS; for (int ch = 0; ch < charWidth.length; ch++) { int row = ch / COLS; int col = ch % COLS; outer: for (int colIdx = colWidth - 1; colIdx >= 0; colIdx--) { int x = col * colWidth + colIdx; for (int rowIdx = 0; rowIdx < rowHeight; rowIdx++) { int y = row * rowHeight + rowIdx; int pixel = rgb[x + y * width]; if (isOpaque(pixel)) { if (printThis(ch)) { logger.finer( "%d '%c' pixel (%d, %d) = %08x, colIdx = %d", ch, (char) ch, x, y, pixel, colIdx); } charWidthf[ch] = (128.0f * (float) (colIdx + 1)) / (float) width + 1.0f; if (showLines) { for (int i = 0; i < rowHeight; i++) { y = row * rowHeight + i; for (int j = 0; j < Math.max(colWidth / 16, 1); j++) { image.setRGB(x + j, y, (i == rowIdx ? 0xff0000ff : 0xffff0000)); image.setRGB(col * colWidth + j, y, 0xff00ff00); } } } break outer; } } } } for (int ch = 0; ch < charWidthf.length; ch++) { if (charWidthf[ch] <= 0.0f) { charWidthf[ch] = 2.0f; } else if (charWidthf[ch] >= 7.99f) { charWidthf[ch] = 7.99f; } } boolean[] isOverride = new boolean[charWidth.length]; try { getCharWidthOverrides(filename, charWidthf, isOverride); } catch (Exception e) { e.printStackTrace(); } if (!isOverride[32]) { charWidthf[32] = defaultSpaceWidth(charWidthf); } for (int ch = 0; ch < charWidth.length; ch++) { charWidth[ch] = Math.round(charWidthf[ch]); if (printThis(ch)) { logger.finer("charWidth[%d '%c'] = %f", ch, (char) ch, charWidthf[ch]); } } return charWidthf; } private static float getCharWidthf(FontRenderer fontRenderer, char ch) { float width = fontRenderer.getCharWidth(ch); if (width < 0 || ((FontRendererExpansion) fontRenderer).getCharWidthf() == null || ch >= ((FontRendererExpansion) fontRenderer).getCharWidthf().length) { return width; } else { return ((FontRendererExpansion) fontRenderer).getCharWidthf()[ch]; } } public static float getCharWidthf(FontRenderer fontRenderer, int[] charWidth, int ch) { return ((FontRendererExpansion) fontRenderer).getIsHD() ? ((FontRendererExpansion) fontRenderer).getCharWidthf()[ch] * fontRenderer.FONT_HEIGHT / 8.0f : (float) charWidth[ch]; } public static float getStringWidthf(FontRenderer fontRenderer, String s) { float totalWidth = 0.0f; if (s != null) { boolean isLink = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); float cWidth = getCharWidthf(fontRenderer, c); if (cWidth < 0.0f && i < s.length() - 1) { i++; c = s.charAt(i); if (c == 'l' || c == 'L') { isLink = true; } else if (c == 'r' || c == 'R') { isLink = false; } cWidth = 0.0f; } totalWidth += cWidth; if (isLink) { totalWidth++; } } } return totalWidth; } public static ResourceLocation getUnicodePage(ResourceLocation resource) { if (enable && resource != null) { ResourceLocation newResource = new ResourceLocation( resource.getResourceDomain(), resource.getResourcePath() .replaceFirst("^textures/", "mcpatcher/")); if (!newResource.equals(resource) && TexturePackAPI.hasResource(newResource)) { logger.fine("using %s instead of %s", newResource, resource); return newResource; } } return resource; } private static boolean isOpaque(int pixel) { for (int i : SPACERS) { if (pixel == i) { return false; } } return ((pixel >> 24) & 0xf0) > 0; } private static boolean printThis(int ch) { return "ABCDEF abcdef0123456789".indexOf(ch) >= 0; } private static float defaultSpaceWidth(float[] charWidthf) { if (TexturePackAPI.isDefaultTexturePack()) { return 4.0f; } float sum = 0.0f; int n = 0; for (char ch : AVERAGE_CHARS) { if (charWidthf[ch] > 0.0f) { sum += charWidthf[ch]; n++; } } if (n > 0) { return sum / (float) n * 7.0f / 12.0f; } else { return 4.0f; } } private static void getCharWidthOverrides(ResourceLocation font, float[] charWidthf, boolean[] isOverride) { ResourceLocation textFile = TexturePackAPI.transformResourceLocation(font, ".png", ".properties"); PropertiesFile props = PropertiesFile.get(logger, textFile); if (props == null) { return; } logger.fine("reading character widths from %s", textFile); for (Map.Entry<String, String> entry : props.entrySet()) { String key = entry.getKey() .trim(); String value = entry.getValue() .trim(); if (key.matches("^width\\.\\d+$") && !value.isEmpty()) { try { int ch = Integer.parseInt(key.substring(6)); float width = Float.parseFloat(value); if (ch >= 0 && ch < charWidthf.length) { logger.finer("setting charWidthf[%d '%c'] to %f", ch, (char) ch, width); charWidthf[ch] = width; isOverride[ch] = true; } } catch (NumberFormatException ignore) {} } } } }
Angelica
src\main\java\com\prupe\mcpatcher\hd\MipmapHelper.java
package com.prupe.mcpatcher.hd; import java.math.BigInteger; import java.nio.IntBuffer; import java.util.HashMap; import java.util.Map; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.EXTTextureFilterAnisotropic; import org.lwjgl.opengl.EXTTextureLODBias; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GLContext; import org.lwjgl.util.glu.GLU; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.mal.resource.GLAPI; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import jss.notfine.config.MCPatcherForgeConfig; public class MipmapHelper { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.EXTENDED_HD); private static final ResourceLocation MIPMAP_PROPERTIES = TexturePackAPI .newMCPatcherResourceLocation("mipmap.properties"); static final int TEX_FORMAT = GL12.GL_BGRA; static final int TEX_DATA_TYPE = GL12.GL_UNSIGNED_INT_8_8_8_8_REV; private static final boolean mipmapSupported; static final boolean mipmapEnabled = MCPatcherForgeConfig.ExtendedHD.mipmap; static final int maxMipmapLevel = MCPatcherForgeConfig.ExtendedHD.maxMipMapLevel; private static final boolean useMipmap; private static final boolean anisoSupported; static final int anisoLevel; private static final int anisoMax; private static final boolean lodSupported; private static final int lodBias; private static final Map<String, Boolean> mipmapType = new HashMap<>(); static { mipmapSupported = GLContext.getCapabilities().OpenGL12; useMipmap = mipmapSupported && mipmapEnabled && maxMipmapLevel > 0; anisoSupported = GLContext.getCapabilities().GL_EXT_texture_filter_anisotropic; if (anisoSupported) { anisoMax = (int) GL11.glGetFloat(EXTTextureFilterAnisotropic.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT); checkGLError("glGetFloat(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT)"); anisoLevel = Math.max(Math.min(MCPatcherForgeConfig.ExtendedHD.anisotropicFiltering, anisoMax), 1); } else { anisoMax = anisoLevel = 1; } lodSupported = GLContext.getCapabilities().GL_EXT_texture_lod_bias; if (lodSupported) { lodBias = MCPatcherForgeConfig.ExtendedHD.lodBias; } else { lodBias = 0; } logger.config("mipmap: supported=%s, enabled=%s, level=%d", mipmapSupported, mipmapEnabled, maxMipmapLevel); logger.config("anisotropic: supported=%s, level=%d, max=%d", anisoSupported, anisoLevel, anisoMax); logger.config("lod bias: supported=%s, bias=%d", lodSupported, lodBias); } static void setupTexture(int width, int height, boolean blur, boolean clamp, String textureName) { int mipmaps = useMipmapsForTexture(textureName) ? getMipmapLevels(width, height, 1) : 0; logger.finer("setupTexture(%s) %dx%d %d mipmaps", textureName, width, height, mipmaps); int magFilter = blur ? GL11.GL_LINEAR : GL11.GL_NEAREST; int minFilter = mipmaps > 0 ? GL11.GL_LINEAR_MIPMAP_LINEAR : magFilter; int wrap = clamp ? GL11.GL_CLAMP : GL11.GL_REPEAT; if (mipmaps > 0) { GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, mipmaps); checkGLError("%s: set GL_TEXTURE_MAX_LEVEL = %d", textureName, mipmaps); if (anisoSupported && anisoLevel > 1) { GL11.glTexParameterf( GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, anisoLevel); checkGLError("%s: set GL_TEXTURE_MAX_ANISOTROPY_EXT = %f", textureName, anisoLevel); } if (lodSupported) { GL11.glTexEnvi( EXTTextureLODBias.GL_TEXTURE_FILTER_CONTROL_EXT, EXTTextureLODBias.GL_TEXTURE_LOD_BIAS_EXT, lodBias); checkGLError("%s: set GL_TEXTURE_LOD_BIAS_EXT = %d", textureName, lodBias); } } GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, minFilter); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, magFilter); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, wrap); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, wrap); for (int level = 0; level <= mipmaps; level++) { GL11.glTexImage2D( GL11.GL_TEXTURE_2D, level, GL11.GL_RGBA, width, height, 0, TEX_FORMAT, TEX_DATA_TYPE, (IntBuffer) null); checkGLError("%s: glTexImage2D %dx%d level %d", textureName, width, height, level); width >>= 1; height >>= 1; } } public static void setupTexture(int glTexture, int width, int height, String textureName) { GLAPI.glBindTexture(glTexture); logger.finer("setupTexture(tilesheet %s, %d, %dx%d)", textureName, glTexture, width, height); setupTexture(width, height, false, false, textureName); } static void reset() { mipmapType.clear(); mipmapType.put("terrain", true); mipmapType.put("items", false); PropertiesFile properties = PropertiesFile.get(logger, MIPMAP_PROPERTIES); if (properties != null) { for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey() .trim(); boolean value = Boolean.parseBoolean( entry.getValue() .trim() .toLowerCase()); if (key.endsWith(".png")) { mipmapType.put(key, value); } } } } static boolean useMipmapsForTexture(String texture) { if (!useMipmap || texture == null) { return false; } else if (mipmapType.containsKey(texture)) { return mipmapType.get(texture); } else return !texture.contains("item") && !texture.startsWith("textures/colormap/") && !texture.startsWith("textures/environment/") && !texture.startsWith("textures/font/") && !texture.startsWith("textures/gui/") && !texture.startsWith("textures/map/") && !texture.startsWith("textures/misc/") && !texture.startsWith(TexturePackAPI.MCPATCHER_SUBDIR + "colormap/") && !texture.startsWith(TexturePackAPI.MCPATCHER_SUBDIR + "cit/") && !texture.startsWith(TexturePackAPI.MCPATCHER_SUBDIR + "dial/") && !texture.startsWith(TexturePackAPI.MCPATCHER_SUBDIR + "font/") && !texture.startsWith(TexturePackAPI.MCPATCHER_SUBDIR + "lightmap/") && !texture.startsWith(TexturePackAPI.MCPATCHER_SUBDIR + "sky/") && // 1.5 stuff !texture.startsWith("%") && !texture.startsWith("##") && !texture.startsWith("/achievement/") && !texture.startsWith("/environment/") && !texture.startsWith("/font/") && !texture.startsWith("/gui/") && !texture.startsWith("/misc/") && !texture.startsWith("/terrain/") && !texture.startsWith("/title/"); } static int getMipmapLevelsForCurrentTexture() { int filter = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER); if (filter != GL11.GL_NEAREST_MIPMAP_LINEAR && filter != GL11.GL_NEAREST_MIPMAP_NEAREST) { return 0; } return Math.min(maxMipmapLevel, GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL)); } private static int gcd(int a, int b) { return BigInteger.valueOf(a) .gcd(BigInteger.valueOf(b)) .intValue(); } private static int getMipmapLevels(int width, int height, int minSize) { int size = gcd(width, height); int mipmap; for (mipmap = 0; size >= minSize && ((size & 1) == 0) && mipmap < maxMipmapLevel; size >>= 1, mipmap++) {} return mipmap; } static void scaleHalf(IntBuffer in, int w, int h, IntBuffer out, int rotate) { for (int i = 0; i < w / 2; i++) { for (int j = 0; j < h / 2; j++) { int k = w * 2 * j + 2 * i; int pixel00 = in.get(k); int pixel01 = in.get(k + 1); int pixel10 = in.get(k + w); int pixel11 = in.get(k + w + 1); if (rotate != 0) { pixel00 = Integer.rotateLeft(pixel00, rotate); pixel01 = Integer.rotateLeft(pixel01, rotate); pixel10 = Integer.rotateLeft(pixel10, rotate); pixel11 = Integer.rotateLeft(pixel11, rotate); } int pixel = average4RGBA(pixel00, pixel01, pixel10, pixel11); if (rotate != 0) { pixel = Integer.rotateRight(pixel, rotate); } out.put(w / 2 * j + i, pixel); } } } private static int average4RGBA(int pixel00, int pixel01, int pixel10, int pixel11) { int a00 = pixel00 & 0xff; int a01 = pixel01 & 0xff; int a10 = pixel10 & 0xff; int a11 = pixel11 & 0xff; switch ((a00 << 24) | (a01 << 16) | (a10 << 8) | a11) { case 0xff000000: return pixel00; case 0x00ff0000: return pixel01; case 0x0000ff00: return pixel10; case 0x000000ff: return pixel11; case 0xffff0000: return average2RGBA(pixel00, pixel01); case 0xff00ff00: return average2RGBA(pixel00, pixel10); case 0xff0000ff: return average2RGBA(pixel00, pixel11); case 0x00ffff00: return average2RGBA(pixel01, pixel10); case 0x00ff00ff: return average2RGBA(pixel01, pixel11); case 0x0000ffff: return average2RGBA(pixel10, pixel11); case 0x00000000: case 0xffffffff: return average2RGBA(average2RGBA(pixel00, pixel11), average2RGBA(pixel01, pixel10)); default: int a = a00 + a01 + a10 + a11; int pixel = a >> 2; for (int i = 8; i < 32; i += 8) { int average = (a00 * ((pixel00 >> i) & 0xff) + a01 * ((pixel01 >> i) & 0xff) + a10 * ((pixel10 >> i) & 0xff) + a11 * ((pixel11 >> i) & 0xff)) / a; pixel |= (average << i); } return pixel; } } private static int average2RGBA(int a, int b) { return (((a & 0xfefefefe) >>> 1) + ((b & 0xfefefefe) >>> 1)) | (a & b & 0x01010101); } private static void checkGLError(String format, Object... params) { int error = GL11.glGetError(); if (error != 0) { String message = GLU.gluErrorString(error) + ": " + String.format(format, params); new RuntimeException(message).printStackTrace(); } } }
Angelica
src\main\java\com\prupe\mcpatcher\mob\LineRenderer.java
package com.prupe.mcpatcher.mob; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.ResourceLocation; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.util.InputHandler; import jss.notfine.config.MCPatcherForgeConfig; public class LineRenderer { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.RANDOM_MOBS); private static final double D_WIDTH = 1.0 / 1024.0; private static final double D_POS = 1.0 / 256.0; private static final boolean enable = MCPatcherForgeConfig.RandomMobs.leashLine; private static final LineRenderer[] renderers = new LineRenderer[2]; private final ResourceLocation texture; private final double width; private final double a; private final double b; private final double sx; private final double sy; private final double sz; private final int segments; private final double tileFactor; private final boolean active; private final InputHandler keyboard; private double plusWidth; private double plusTile; private double plusSX; private double plusSY; private double plusSZ; public static boolean renderLine(int type, double x, double y, double z, double dx, double dy, double dz) { LineRenderer renderer = renderers[type]; return renderer != null && renderer.render(x, y, z, dx, dy, dz); } static void reset() { if (enable) { setup(0, "fishingline", 0.0075, 0.0, 0.25, 16); setup(1, "lead", 0.025, 4.0 / 3.0, 0.125, 24); } } private static void setup(int type, String name, double defaultWidth, double a, double b, int segments) { LineRenderer renderer = new LineRenderer(name, defaultWidth, a, b, segments); if (renderer.active) { logger.fine("using %s", renderer); renderers[type] = renderer; } else { logger.fine("%s not found", renderer); renderers[type] = null; } } private LineRenderer(String name, double width, double a, double b, int segments) { texture = TexturePackAPI.newMCPatcherResourceLocation("line/" + name + ".png"); active = TexturePackAPI.hasResource(texture); PropertiesFile properties = PropertiesFile .getNonNull(logger, TexturePackAPI.transformResourceLocation(texture, ".png", ".properties")); this.width = properties.getDouble("width", width); this.a = properties.getDouble("a", a); this.b = properties.getDouble("b", b); this.sx = properties.getDouble("sx", 0.0); this.sy = properties.getDouble("sy", 0.0); this.sz = properties.getDouble("sz", 0.0); this.segments = properties.getInt("segments", segments); this.tileFactor = properties.getDouble("tileFactor", 24.0); keyboard = new InputHandler(name, properties.getBoolean("debug", false)); } private boolean render(double x, double y, double z, double dx, double dy, double dz) { if (keyboard.isKeyDown(Keyboard.KEY_MULTIPLY)) { return false; } boolean changed = false; if (!keyboard.isEnabled()) { // nothing } else if (keyboard.isKeyPressed(Keyboard.KEY_ADD)) { changed = true; plusWidth += D_WIDTH; } else if (keyboard.isKeyPressed(Keyboard.KEY_SUBTRACT)) { changed = true; plusWidth -= D_WIDTH; } else if (keyboard.isKeyPressed(Keyboard.KEY_DIVIDE)) { changed = true; plusWidth = plusTile = plusSX = plusSY = plusSZ = 0.0; } else if (keyboard.isKeyPressed(Keyboard.KEY_NUMPAD3)) { changed = true; plusTile--; } else if (keyboard.isKeyPressed(Keyboard.KEY_NUMPAD9)) { changed = true; plusTile++; } else if (keyboard.isKeyDown(Keyboard.KEY_NUMPAD4)) { changed = true; plusSX -= D_POS; } else if (keyboard.isKeyDown(Keyboard.KEY_NUMPAD6)) { changed = true; plusSX += D_POS; } else if (keyboard.isKeyDown(Keyboard.KEY_NUMPAD1)) { changed = true; plusSY -= D_POS; } else if (keyboard.isKeyDown(Keyboard.KEY_NUMPAD7)) { changed = true; plusSY += D_POS; } else if (keyboard.isKeyDown(Keyboard.KEY_NUMPAD2)) { changed = true; plusSZ += D_POS; } else if (keyboard.isKeyDown(Keyboard.KEY_NUMPAD8)) { changed = true; plusSZ -= D_POS; } TexturePackAPI.bindTexture(texture); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); dx += sx + plusSX; dy += sy + plusSY; dz += sz + plusSZ; double x0 = x; double y0 = y + a + b; double z0 = z; double u0 = 0.0; double len = Math.sqrt(dx * dx + dy * dy + dz * dz); double t = tileFactor + plusTile; double w = width + plusWidth; if (changed) { logger.info( "%s: dx=%f, dy=%f, dz=%f, len=%f(*%d=%f), slen=%f", this, dx, dy, dz, len, (int) t, len * t, len * t / segments); System.out.printf("width=%f\n", w); System.out.printf("tileFactor=%f\n", t); System.out.printf("sx=%f\n", sx + plusSX); System.out.printf("sy=%f\n", sy + plusSY); System.out.printf("sz=%f\n", sz + plusSZ); } len *= t / segments; for (int i = 1; i <= segments; i++) { double s = i / (double) segments; double x1 = x + s * dx; double y1 = y + (s * s + s) * 0.5 * dy + a * (1.0 - s) + b; double z1 = z + s * dz; double u1 = (segments - i) * len; tessellator.addVertexWithUV(x0, y0, z0, u0, 1.0); tessellator.addVertexWithUV(x1, y1, z1, u1, 1.0); tessellator.addVertexWithUV(x1 + w, y1 + w, z1, u1, 0.0); tessellator.addVertexWithUV(x0 + w, y0 + w, z0, u0, 0.0); tessellator.addVertexWithUV(x0, y0 + w, z0, u0, 1.0); tessellator.addVertexWithUV(x1, y1 + w, z1, u1, 1.0); tessellator.addVertexWithUV(x1 + w, y1, z1 + w, u1, 0.0); tessellator.addVertexWithUV(x0 + w, y0, z0 + w, u0, 0.0); x0 = x1; y0 = y1; z0 = z1; u0 = u1; } tessellator.draw(); GL11.glEnable(GL11.GL_CULL_FACE); return true; } @Override public String toString() { return "LineRenderer{" + texture + ", " + (width + plusWidth) + "}"; } }
Angelica
src\main\java\com\prupe\mcpatcher\mob\MobOverlay.java
package com.prupe.mcpatcher.mob; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; public class MobOverlay { private static final ResourceLocation MOOSHROOM_OVERLAY = TexturePackAPI .newMCPatcherResourceLocation("mob/cow/mooshroom_overlay.png"); private static final ResourceLocation SNOWMAN_OVERLAY = TexturePackAPI .newMCPatcherResourceLocation("mob/snowman_overlay.png"); private static final double MOO_X0 = -0.45; private static final double MOO_X1 = 0.45; private static final double MOO_Y0 = -0.5; private static final double MOO_Y1 = 0.5; private static final double MOO_Z0 = -0.45; private static final double MOO_Z1 = 0.45; private static final double SNOW_X0 = -0.5; private static final double SNOW_X1 = 0.5; private static final double SNOW_Y0 = -0.5; private static final double SNOW_Y1 = 0.5; private static final double SNOW_Z0 = -0.5; private static final double SNOW_Z1 = 0.5; private static boolean overlayActive; private static int overlayCounter; private static boolean haveMooshroom; private static boolean haveSnowman; static void reset() { haveMooshroom = TexturePackAPI.hasResource(MOOSHROOM_OVERLAY); haveSnowman = TexturePackAPI.hasResource(SNOWMAN_OVERLAY); } public static ResourceLocation setupMooshroom(EntityLivingBase entity, ResourceLocation defaultTexture) { overlayCounter = 0; if (haveMooshroom) { overlayActive = true; return MobRandomizer.randomTexture(entity, MOOSHROOM_OVERLAY); } else { overlayActive = false; return defaultTexture; } } public static boolean renderMooshroomOverlay(double offset) { if (overlayActive && overlayCounter < 3) { float tileX0 = overlayCounter / 3.0f; float tileX1 = ++overlayCounter / 3.0f; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV(MOO_X0 + offset, MOO_Y1 + offset, MOO_Z0 - offset, tileX0, 0.0); tessellator.addVertexWithUV(MOO_X0 + offset, MOO_Y0 + offset, MOO_Z0 - offset, tileX0, 1.0); tessellator.addVertexWithUV(MOO_X1 + offset, MOO_Y0 + offset, MOO_Z1 - offset, tileX1, 1.0); tessellator.addVertexWithUV(MOO_X1 + offset, MOO_Y1 + offset, MOO_Z1 - offset, tileX1, 0.0); tessellator.addVertexWithUV(MOO_X1 + offset, MOO_Y1 + offset, MOO_Z1 - offset, tileX0, 0.0); tessellator.addVertexWithUV(MOO_X1 + offset, MOO_Y0 + offset, MOO_Z1 - offset, tileX0, 1.0); tessellator.addVertexWithUV(MOO_X0 + offset, MOO_Y0 + offset, MOO_Z0 - offset, tileX1, 1.0); tessellator.addVertexWithUV(MOO_X0 + offset, MOO_Y1 + offset, MOO_Z0 - offset, tileX1, 0.0); tessellator.addVertexWithUV(MOO_X0 + offset, MOO_Y1 + offset, MOO_Z1 - offset, tileX0, 0.0); tessellator.addVertexWithUV(MOO_X0 + offset, MOO_Y0 + offset, MOO_Z1 - offset, tileX0, 1.0); tessellator.addVertexWithUV(MOO_X1 + offset, MOO_Y0 + offset, MOO_Z0 - offset, tileX1, 1.0); tessellator.addVertexWithUV(MOO_X1 + offset, MOO_Y1 + offset, MOO_Z0 - offset, tileX1, 0.0); tessellator.addVertexWithUV(MOO_X1 + offset, MOO_Y1 + offset, MOO_Z0 - offset, tileX0, 0.0); tessellator.addVertexWithUV(MOO_X1 + offset, MOO_Y0 + offset, MOO_Z0 - offset, tileX0, 1.0); tessellator.addVertexWithUV(MOO_X0 + offset, MOO_Y0 + offset, MOO_Z1 - offset, tileX1, 1.0); tessellator.addVertexWithUV(MOO_X0 + offset, MOO_Y1 + offset, MOO_Z1 - offset, tileX1, 0.0); tessellator.draw(); } return overlayActive; } public static void finishMooshroom() { overlayCounter = 0; overlayActive = false; } public static boolean renderSnowmanOverlay(EntityLivingBase entity) { if (!haveSnowman) { return false; } TexturePackAPI.bindTexture(MobRandomizer.randomTexture(entity, SNOWMAN_OVERLAY)); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); double[] c = new double[4]; // bottom = y- getTileCoordinates(0, c); tessellator.addVertexWithUV(SNOW_X1, SNOW_Y0, SNOW_Z0, c[0], c[2]); tessellator.addVertexWithUV(SNOW_X1, SNOW_Y0, SNOW_Z1, c[1], c[2]); tessellator.addVertexWithUV(SNOW_X0, SNOW_Y0, SNOW_Z1, c[1], c[3]); tessellator.addVertexWithUV(SNOW_X0, SNOW_Y0, SNOW_Z0, c[0], c[3]); // top = y+ getTileCoordinates(1, c); tessellator.addVertexWithUV(SNOW_X0, SNOW_Y1, SNOW_Z0, c[0], c[2]); tessellator.addVertexWithUV(SNOW_X0, SNOW_Y1, SNOW_Z1, c[1], c[2]); tessellator.addVertexWithUV(SNOW_X1, SNOW_Y1, SNOW_Z1, c[1], c[3]); tessellator.addVertexWithUV(SNOW_X1, SNOW_Y1, SNOW_Z0, c[0], c[3]); // back = x- getTileCoordinates(2, c); tessellator.addVertexWithUV(SNOW_X0, SNOW_Y1, SNOW_Z1, c[0], c[2]); tessellator.addVertexWithUV(SNOW_X0, SNOW_Y1, SNOW_Z0, c[1], c[2]); tessellator.addVertexWithUV(SNOW_X0, SNOW_Y0, SNOW_Z0, c[1], c[3]); tessellator.addVertexWithUV(SNOW_X0, SNOW_Y0, SNOW_Z1, c[0], c[3]); // right = z- getTileCoordinates(3, c); tessellator.addVertexWithUV(SNOW_X0, SNOW_Y1, SNOW_Z0, c[0], c[2]); tessellator.addVertexWithUV(SNOW_X1, SNOW_Y1, SNOW_Z0, c[1], c[2]); tessellator.addVertexWithUV(SNOW_X1, SNOW_Y0, SNOW_Z0, c[1], c[3]); tessellator.addVertexWithUV(SNOW_X0, SNOW_Y0, SNOW_Z0, c[0], c[3]); // front = x+ getTileCoordinates(4, c); tessellator.addVertexWithUV(SNOW_X1, SNOW_Y1, SNOW_Z0, c[0], c[2]); tessellator.addVertexWithUV(SNOW_X1, SNOW_Y1, SNOW_Z1, c[1], c[2]); tessellator.addVertexWithUV(SNOW_X1, SNOW_Y0, SNOW_Z1, c[1], c[3]); tessellator.addVertexWithUV(SNOW_X1, SNOW_Y0, SNOW_Z0, c[0], c[3]); // left = z+ getTileCoordinates(5, c); tessellator.addVertexWithUV(SNOW_X1, SNOW_Y1, SNOW_Z1, c[0], c[2]); tessellator.addVertexWithUV(SNOW_X0, SNOW_Y1, SNOW_Z1, c[1], c[2]); tessellator.addVertexWithUV(SNOW_X0, SNOW_Y0, SNOW_Z1, c[1], c[3]); tessellator.addVertexWithUV(SNOW_X1, SNOW_Y0, SNOW_Z1, c[0], c[3]); tessellator.draw(); return true; } private static void getTileCoordinates(int tileNum, double[] c) { c[0] = (tileNum % 3) / 3.0; c[1] = c[0] + 1.0 / 3.0; c[2] = (tileNum / 3) / 2.0; c[3] = c[2] + 0.5; } }
Angelica
src\main\java\com\prupe\mcpatcher\mob\MobRandomizer.java
package com.prupe.mcpatcher.mob; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.biome.BiomeAPI; import com.prupe.mcpatcher.mal.resource.TexturePackChangeHandler; public class MobRandomizer { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.RANDOM_MOBS); private static final Map<String, ResourceLocation> cache = new LinkedHashMap<>(); static { TexturePackChangeHandler.register(new TexturePackChangeHandler(MCPatcherUtils.RANDOM_MOBS, 2) { @Override public void beforeChange() { cache.clear(); } @Override public void afterChange() { MobRuleList.clear(); MobOverlay.reset(); LineRenderer.reset(); } }); } public static void init() {} public static ResourceLocation randomTexture(EntityLivingBase entity, ResourceLocation texture) { if (texture == null || !texture.getResourcePath() .endsWith(".png")) { return texture; } String key = texture + ":" + entity.getEntityId(); ResourceLocation newTexture = cache.get(key); if (newTexture == null) { ExtraInfo info = ExtraInfo.getInfo(entity); MobRuleList list = MobRuleList.get(texture); newTexture = list.getSkin(info.skin, info.origX, info.origY, info.origZ, info.origBiome); cache.put(key, newTexture); logger.finer("entity %s using %s (cache: %d)", entity, newTexture, cache.size()); if (cache.size() > 250) { while (cache.size() > 200) { cache.remove( cache.keySet() .iterator() .next()); } } } return newTexture; } public static ResourceLocation randomTexture(Entity entity, ResourceLocation texture) { if (entity instanceof EntityLivingBase) { return randomTexture((EntityLivingBase) entity, texture); } else { return texture; } } public static final class ExtraInfo { private static final String SKIN_TAG = "randomMobsSkin"; private static final String ORIG_X_TAG = "origX"; private static final String ORIG_Y_TAG = "origY"; private static final String ORIG_Z_TAG = "origZ"; private static final long MULTIPLIER = 0x5deece66dL; private static final long ADDEND = 0xbL; private static final long MASK = (1L << 48) - 1; private static final Map<Integer, ExtraInfo> allInfo = new HashMap<>(); private static final Map<WeakReference<EntityLivingBase>, ExtraInfo> allRefs = new HashMap<>(); private static final ReferenceQueue<EntityLivingBase> refQueue = new ReferenceQueue<>(); private final int entityId; private final HashSet<WeakReference<EntityLivingBase>> references; private final long skin; private final int origX; private final int origY; private final int origZ; private Integer origBiome; ExtraInfo(EntityLivingBase entity) { this(entity, getSkinId(entity.getEntityId()), (int) entity.posX, (int) entity.posY, (int) entity.posZ); } ExtraInfo(EntityLivingBase entity, long skin, int origX, int origY, int origZ) { entityId = entity.getEntityId(); references = new HashSet<>(); this.skin = skin; this.origX = origX; this.origY = origY; this.origZ = origZ; } private void setBiome() { if (origBiome == null) { origBiome = BiomeAPI.getBiomeIDAt(BiomeAPI.getWorld(), origX, origY, origZ); } } @Override public String toString() { return String.format( "%s{%d, %d, %d, %d, %d, %s}", getClass().getSimpleName(), entityId, skin, origX, origY, origZ, origBiome); } private static void clearUnusedReferences() { synchronized (allInfo) { Reference<? extends EntityLivingBase> ref; while ((ref = refQueue.poll()) != null) { ExtraInfo info = allRefs.get(ref); if (info != null) { info.references.remove(ref); if (info.references.isEmpty()) { logger.finest("removing unused ref %d", info.entityId); allInfo.remove(info.entityId); } } allRefs.remove(ref); } } } static ExtraInfo getInfo(EntityLivingBase entity) { ExtraInfo info; synchronized (allInfo) { clearUnusedReferences(); info = allInfo.get(entity.getEntityId()); if (info == null) { info = new ExtraInfo(entity); putInfo(entity, info); } boolean found = false; for (WeakReference<EntityLivingBase> ref : info.references) { if (ref.get() == entity) { found = true; break; } } if (!found) { WeakReference<EntityLivingBase> reference = new WeakReference<>(entity, refQueue); info.references.add(reference); allRefs.put(reference, info); logger.finest( "added ref #%d for %d (%d entities)", info.references.size(), entity.getEntityId(), allInfo.size()); } info.setBiome(); } return info; } static void putInfo(EntityLivingBase entity, ExtraInfo info) { synchronized (allInfo) { allInfo.put(entity.getEntityId(), info); } } static void clearInfo() { synchronized (allInfo) { allInfo.clear(); } } private static long getSkinId(int entityId) { long n = entityId; n = n ^ (n << 16) ^ (n << 32) ^ (n << 48); n = MULTIPLIER * n + ADDEND; n = MULTIPLIER * n + ADDEND; n &= MASK; return (n >> 32) ^ n; } public static void readFromNBT(EntityLivingBase entity, NBTTagCompound nbt) { long skin = nbt.getLong(SKIN_TAG); if (skin != 0L) { int x = nbt.getInteger(ORIG_X_TAG); int y = nbt.getInteger(ORIG_Y_TAG); int z = nbt.getInteger(ORIG_Z_TAG); putInfo(entity, new ExtraInfo(entity, skin, x, y, z)); } } public static void writeToNBT(EntityLivingBase entity, NBTTagCompound nbt) { synchronized (allInfo) { ExtraInfo info = allInfo.get(entity.getEntityId()); if (info != null) { nbt.setLong(SKIN_TAG, info.skin); nbt.setInteger(ORIG_X_TAG, info.origX); nbt.setInteger(ORIG_Y_TAG, info.origY); nbt.setInteger(ORIG_Z_TAG, info.origZ); } } } } }
Angelica
src\main\java\com\prupe\mcpatcher\mob\MobRuleList.java
package com.prupe.mcpatcher.mob; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.biome.BiomeAPI; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.util.WeightedIndex; class MobRuleList { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.RANDOM_MOBS); public static final String ALTERNATIVES_REGEX = "_(eyes|overlay|tame|angry|collar|fur|invulnerable|shooting)\\.properties$"; private static final Map<ResourceLocation, MobRuleList> allRules = new HashMap<>(); private final ResourceLocation baseSkin; private final List<ResourceLocation> allSkins; private final int skinCount; private final List<MobRuleEntry> entries; private MobRuleList(ResourceLocation baseSkin) { this.baseSkin = baseSkin; String newPath = baseSkin.getResourcePath() .replaceFirst("^textures/entity/", TexturePackAPI.MCPATCHER_SUBDIR + "mob/"); ResourceLocation newSkin = new ResourceLocation(baseSkin.getResourceDomain(), newPath); allSkins = new ArrayList<>(); allSkins.add(baseSkin); for (int i = 2;; i++) { ResourceLocation skin = TexturePackAPI.transformResourceLocation(newSkin, ".png", i + ".png"); if (!TexturePackAPI.hasResource(skin)) { break; } allSkins.add(skin); } skinCount = allSkins.size(); if (skinCount <= 1) { entries = null; return; } logger.fine("found %d variations for %s", skinCount, baseSkin); ResourceLocation filename = TexturePackAPI.transformResourceLocation(newSkin, ".png", ".properties"); ResourceLocation altFilename = new ResourceLocation( newSkin.getResourceDomain(), filename.getResourcePath() .replaceFirst(ALTERNATIVES_REGEX, ".properties")); PropertiesFile properties = PropertiesFile.get(logger, filename); if (properties == null && !filename.equals(altFilename)) { properties = PropertiesFile.get(logger, altFilename); if (properties != null) { logger.fine("using %s for %s", altFilename, baseSkin); } } ArrayList<MobRuleEntry> tmpEntries = new ArrayList<>(); if (properties != null) { for (int i = 0;; i++) { MobRuleEntry entry = MobRuleEntry.load(properties, i, skinCount); if (entry == null) { if (i > 0) { break; } } else { logger.fine(" %s", entry.toString()); tmpEntries.add(entry); } } } entries = tmpEntries.isEmpty() ? null : tmpEntries; } ResourceLocation getSkin(long key, int i, int j, int k, Integer biome) { if (entries == null) { int index = (int) (key % skinCount); if (index < 0) { index += skinCount; } return allSkins.get(index); } else { if (j < 0) { j = 0; } for (MobRuleEntry entry : entries) { if (entry.match(i, j, k, biome)) { int index = entry.weightedIndex.choose(key); return allSkins.get(entry.skins[index]); } } } return baseSkin; } static MobRuleList get(ResourceLocation texture) { MobRuleList list = allRules.get(texture); if (list == null) { list = new MobRuleList(texture); allRules.put(texture, list); } return list; } static void clear() { allRules.clear(); } private static class MobRuleEntry { final int[] skins; final WeightedIndex weightedIndex; private final BitSet biomes; private final BitSet height; static MobRuleEntry load(PropertiesFile properties, int index, int limit) { String skinList = properties.getString("skins." + index, "") .toLowerCase(); int[] skins; if (skinList.equals("*") || skinList.equals("all") || skinList.equals("any")) { skins = new int[limit]; for (int i = 0; i < skins.length; i++) { skins[i] = i; } } else { skins = MCPatcherUtils.parseIntegerList(skinList, 1, limit); if (skins.length <= 0) { return null; } for (int i = 0; i < skins.length; i++) { skins[i]--; } } WeightedIndex chooser = WeightedIndex.create(skins.length, properties.getString("weights." + index, "")); if (chooser == null) { return null; } BitSet biomes; String biomeList = properties.getString("biomes." + index, ""); if (biomeList.isEmpty()) { biomes = null; } else { biomes = new BitSet(); BiomeAPI.parseBiomeList(biomeList, biomes); } BitSet height = BiomeAPI.getHeightListProperty(properties, "." + index); return new MobRuleEntry(skins, chooser, biomes, height); } MobRuleEntry(int[] skins, WeightedIndex weightedIndex, BitSet biomes, BitSet height) { this.skins = skins; this.weightedIndex = weightedIndex; this.biomes = biomes; this.height = height; } boolean match(int x, int y, int z, Integer biome) { if (biomes != null) { if (biome == null || !biomes.get(biome)) { return false; } } return height == null || height.get(y); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("skins:"); for (int i : skins) { sb.append(' ') .append(i + 1); } if (biomes != null) { sb.append(", biomes:"); for (int i = biomes.nextSetBit(0); i >= 0; i = biomes.nextSetBit(i + 1)) { sb.append(' ') .append(i); } } if (height != null) { sb.append(", height:"); for (int i = height.nextSetBit(0); i >= 0; i = height.nextSetBit(i + 1)) { sb.append(' ') .append(i); } } sb.append(", weights: ") .append(weightedIndex.toString()); return sb.toString(); } } }
Angelica
src\main\java\com\prupe\mcpatcher\renderpass\RenderPass.java
package com.prupe.mcpatcher.renderpass; import java.util.Arrays; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Map; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; import org.lwjgl.opengl.GL11; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.ctm.CTMUtils; import com.prupe.mcpatcher.mal.block.BlockAPI; import com.prupe.mcpatcher.mal.block.RenderPassAPI; import com.prupe.mcpatcher.mal.resource.BlendMethod; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.resource.TexturePackChangeHandler; public class RenderPass { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.BETTER_GLASS); private static final ResourceLocation RENDERPASS_PROPERTIES = TexturePackAPI .newMCPatcherResourceLocation("renderpass.properties"); private static final Map<Block, Integer> baseRenderPass = new IdentityHashMap<>(); private static final Map<Block, Integer> extraRenderPass = new IdentityHashMap<>(); private static final Map<Block, Integer> renderPassBits = new IdentityHashMap<>(); private static final Set<Block> customRenderPassBlocks = new HashSet<>(); private static BlendMethod blendMethod; private static ResourceLocation blendBlankResource; private static boolean enableLightmap; private static boolean enableColormap; private static final boolean[] backfaceCulling = new boolean[RenderPassAPI.NUM_RENDER_PASSES]; private static int currentRenderPass = -1; private static int maxRenderPass = 1; private static boolean canRenderInThisPass; private static boolean hasCustomRenderPasses; private static boolean ambientOcclusion; private static final int COLOR_POS_0 = 3; private static final int COLOR_POS_1 = COLOR_POS_0 + 7; private static final int COLOR_POS_2 = COLOR_POS_1 + 7; private static final int COLOR_POS_3 = COLOR_POS_2 + 7; private static int saveColor0; private static int saveColor1; private static int saveColor2; private static int saveColor3; static { RenderPassAPI.instance = new RenderPassAPI() { @Override public boolean skipDefaultRendering(Block block) { return currentRenderPass > MAX_BASE_RENDER_PASS; } @Override public boolean skipThisRenderPass(Block block, int pass) { if (currentRenderPass < 0) { return pass > MAX_BASE_RENDER_PASS; } if (pass < 0) { pass = RenderPassMap.getDefaultRenderPass(block); } return pass != currentRenderPass; } @Override public boolean useColorMultiplierThisPass(Block block) { return currentRenderPass != OVERLAY_RENDER_PASS || enableColormap; } @Override public boolean useLightmapThisPass() { return currentRenderPass != OVERLAY_RENDER_PASS || enableLightmap; } @Override public void clear() { canRenderInThisPass = false; maxRenderPass = MAX_BASE_RENDER_PASS - 1; baseRenderPass.clear(); extraRenderPass.clear(); renderPassBits.clear(); customRenderPassBlocks.clear(); blendMethod = BlendMethod.ALPHA; blendBlankResource = blendMethod.getBlankResource(); if (blendBlankResource == null) { blendBlankResource = BlendMethod.ALPHA.getBlankResource(); } enableLightmap = true; enableColormap = false; Arrays.fill(backfaceCulling, true); backfaceCulling[RenderPassAPI.BACKFACE_RENDER_PASS] = false; for (Block block : BlockAPI.getAllBlocks()) { baseRenderPass.put(block, RenderPassMap.getDefaultRenderPass(block)); } } @Override public void refreshBlendingOptions() { PropertiesFile properties = PropertiesFile.get(logger, RENDERPASS_PROPERTIES); if (properties != null) { remapProperties(properties); String method = properties.getString("blend.overlay", "alpha") .trim() .toLowerCase(); blendMethod = BlendMethod.parse(method); if (blendMethod == null) { logger.error("%s: unknown blend method '%s'", RENDERPASS_PROPERTIES, method); blendMethod = BlendMethod.ALPHA; } blendBlankResource = blendMethod.getBlankResource(); if (blendBlankResource == null) { blendBlankResource = BlendMethod.ALPHA.getBlankResource(); } enableLightmap = properties.getBoolean("enableLightmap.overlay", !blendMethod.isColorBased()); enableColormap = properties.getBoolean("enableColormap.overlay", false); backfaceCulling[RenderPassAPI.OVERLAY_RENDER_PASS] = properties .getBoolean("backfaceCulling.overlay", true); backfaceCulling[RenderPassAPI.CUTOUT_RENDER_PASS] = backfaceCulling[RenderPassMap .getCutoutRenderPass()] = properties.getBoolean("backfaceCulling.cutout", true); backfaceCulling[RenderPassAPI.CUTOUT_MIPPED_RENDER_PASS] = properties .getBoolean("backfaceCulling.cutout_mipped", backfaceCulling[RenderPassAPI.CUTOUT_RENDER_PASS]); backfaceCulling[RenderPassAPI.TRANSLUCENT_RENDER_PASS] = properties .getBoolean("backfaceCulling.translucent", true); } } private void remapProperties(PropertiesFile properties) { for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); key = key.replaceFirst("\\.3$", ".overlay"); key = key.replaceFirst("\\.2$", ".backface"); if (!key.equals(entry.getKey())) { properties.warning("%s is deprecated in 1.8. Use %s instead", entry.getKey(), key); } properties.setProperty(key, entry.getValue()); } } @Override public void setRenderPassForBlock(Block block, int pass) { if (block == null || pass < 0) { return; } String name; if (pass <= MAX_BASE_RENDER_PASS) { baseRenderPass.put(block, pass); name = "base"; } else { extraRenderPass.put(block, pass); name = "extra"; } logger.fine( "%s %s render pass -> %s", BlockAPI.getBlockName(block), name, RenderPassAPI.instance.getRenderPassName(pass)); customRenderPassBlocks.add(block); maxRenderPass = Math.max(maxRenderPass, pass); } @Override public ResourceLocation getBlankResource(int pass) { return pass == OVERLAY_RENDER_PASS ? blendBlankResource : super.getBlankResource(pass); } @Override public ResourceLocation getBlankResource() { return getBlankResource(currentRenderPass); } }; TexturePackChangeHandler.register(new TexturePackChangeHandler(MCPatcherUtils.BETTER_GLASS, 4) { @Override public void beforeChange() {} @Override public void afterChange() { for (Block block : BlockAPI.getAllBlocks()) { int bits = 0; Integer i = baseRenderPass.get(block); if (i != null && i >= 0) { bits |= (1 << i); } i = extraRenderPass.get(block); if (i != null && i >= 0) { bits |= (1 << i); } renderPassBits.put(block, bits); } } }); } public static void start(int pass) { currentRenderPass = RenderPassMap.vanillaToMCPatcher(pass); CTMUtils.setBlankResource(); } public static void finish() { currentRenderPass = -1; CTMUtils.setBlankResource(); } public static boolean skipAllRenderPasses(boolean[] skipRenderPass) { return skipRenderPass[0] && skipRenderPass[1] && skipRenderPass[2] && skipRenderPass[3]; } public static boolean checkRenderPasses(Block block, boolean moreRenderPasses) { int bits = renderPassBits.get(block) >>> currentRenderPass; canRenderInThisPass = (bits & 1) != 0; hasCustomRenderPasses = customRenderPassBlocks.contains(block); return moreRenderPasses || (bits >>> 1) != 0; } public static boolean canRenderInThisPass(boolean canRender) { return hasCustomRenderPasses ? canRenderInThisPass : canRender; } // pre-14w02a public static boolean shouldSideBeRendered(Block block, IBlockAccess blockAccess, int x, int y, int z, int face) { if (block.shouldSideBeRendered(blockAccess, x, y, z, face)) { return true; } else if (!extraRenderPass.containsKey(block)) { Block neighbor = blockAccess.getBlock(x, y, z); return extraRenderPass.containsKey(neighbor); } else { return false; } } public static boolean setAmbientOcclusion(boolean ambientOcclusion) { RenderPass.ambientOcclusion = ambientOcclusion; return ambientOcclusion; } public static float getAOBaseMultiplier(float multiplier) { return RenderPassAPI.instance.useLightmapThisPass() ? multiplier : 1.0f; } public static boolean useBlockShading() { return RenderPassAPI.instance.useLightmapThisPass(); } // *sigh* Mojang removed the "unshaded" model face buffer in 14w11a, making this hack necessary again public static void unshadeBuffer(int[] b) { if (!useBlockShading()) { saveColor0 = b[COLOR_POS_0]; saveColor1 = b[COLOR_POS_1]; saveColor2 = b[COLOR_POS_2]; saveColor3 = b[COLOR_POS_3]; b[COLOR_POS_0] = b[COLOR_POS_1] = b[COLOR_POS_2] = b[COLOR_POS_3] = -1; } } public static void reshadeBuffer(int[] b) { if (!useBlockShading()) { b[COLOR_POS_0] = saveColor0; b[COLOR_POS_1] = saveColor1; b[COLOR_POS_2] = saveColor2; b[COLOR_POS_3] = saveColor3; } } public static boolean preRenderPass(int pass) { currentRenderPass = pass; if (pass > maxRenderPass) { return false; } switch (pass) { case RenderPassAPI.SOLID_RENDER_PASS: case RenderPassAPI.CUTOUT_MIPPED_RENDER_PASS: case RenderPassAPI.CUTOUT_RENDER_PASS: case RenderPassAPI.TRANSLUCENT_RENDER_PASS: case RenderPassAPI.BACKFACE_RENDER_PASS: if (!backfaceCulling[pass]) { GL11.glDisable(GL11.GL_CULL_FACE); } break; case RenderPassAPI.OVERLAY_RENDER_PASS: GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GL11.glPolygonOffset(-2.0f, -2.0f); GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL); if (backfaceCulling[pass]) { GL11.glEnable(GL11.GL_CULL_FACE); } else { GL11.glDisable(GL11.GL_CULL_FACE); } if (ambientOcclusion) { GL11.glShadeModel(GL11.GL_SMOOTH); } blendMethod.applyBlending(); break; default: break; } return true; } public static int postRenderPass(int value) { switch (currentRenderPass) { case RenderPassAPI.SOLID_RENDER_PASS: case RenderPassAPI.CUTOUT_MIPPED_RENDER_PASS: case RenderPassAPI.CUTOUT_RENDER_PASS: case RenderPassAPI.TRANSLUCENT_RENDER_PASS: case RenderPassAPI.BACKFACE_RENDER_PASS: if (!backfaceCulling[currentRenderPass]) { GL11.glEnable(GL11.GL_CULL_FACE); } break; case RenderPassAPI.OVERLAY_RENDER_PASS: GL11.glPolygonOffset(0.0f, 0.0f); GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL); if (!backfaceCulling[currentRenderPass]) { GL11.glEnable(GL11.GL_CULL_FACE); } GL11.glDisable(GL11.GL_BLEND); GL11.glShadeModel(GL11.GL_FLAT); break; default: break; } currentRenderPass = -1; return value; } public static void enableDisableLightmap(EntityRenderer renderer, double partialTick) { if (RenderPassAPI.instance.useLightmapThisPass()) { renderer.enableLightmap(partialTick); } else { renderer.disableLightmap(partialTick); } } }
Angelica
src\main\java\com\prupe\mcpatcher\renderpass\RenderPassMap.java
package com.prupe.mcpatcher.renderpass; import net.minecraft.block.Block; import com.prupe.mcpatcher.mal.block.RenderPassAPI; public class RenderPassMap { private static final int[] MAP = new int[] { 0, 0, 0, 1, 2, 3 }; public static int map18To17(int pass) { return pass > 1 ? pass < MAP.length ? MAP[pass] : -1 : pass; } public static int map17To18(int pass) { return pass <= 1 ? vanillaToMCPatcher(pass) : pass; } protected static int vanillaToMCPatcher(int pass) { for (int i = 0; i < MAP.length; i++) { if (MAP[i] == pass) { return i; } } return -1; } protected static int getDefaultRenderPass(Block block) { return vanillaToMCPatcher(block.getRenderBlockPass()); } protected static int getCutoutRenderPass() { return RenderPassAPI.SOLID_RENDER_PASS; } }
Angelica
src\main\java\com\prupe\mcpatcher\sky\FireworksHelper.java
package com.prupe.mcpatcher.sky; import net.minecraft.client.particle.EntityFX; import net.minecraft.client.particle.EntityFireworkOverlayFX; import net.minecraft.client.particle.EntityFireworkSparkFX; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.mal.resource.BlendMethod; import com.prupe.mcpatcher.mal.resource.GLAPI; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import jss.notfine.config.MCPatcherForgeConfig; public class FireworksHelper { private static final int LIT_LAYER = 3; private static final int EXTRA_LAYER = LIT_LAYER + 1; private static final ResourceLocation PARTICLE_PROPERTIES = TexturePackAPI .newMCPatcherResourceLocation("particle.properties"); private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.BETTER_SKIES); private static final boolean enable = MCPatcherForgeConfig.BetterSkies.brightenFireworks; private static BlendMethod blendMethod; public static int getFXLayer(EntityFX entity) { if (enable && (entity instanceof EntityFireworkSparkFX || entity instanceof EntityFireworkOverlayFX)) { return EXTRA_LAYER; } else { return entity.getFXLayer(); } } public static boolean skipThisLayer(boolean skip, int layer) { return skip || layer == LIT_LAYER || (!enable && layer > LIT_LAYER); } public static void setParticleBlendMethod(int layer, int pass, boolean setDefault) { if (enable && layer == EXTRA_LAYER && blendMethod != null) { blendMethod.applyBlending(); } else if (setDefault) { GLAPI.glBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); } } static void reload() { PropertiesFile properties = PropertiesFile.getNonNull(logger, PARTICLE_PROPERTIES); String blend = properties.getString("blend." + EXTRA_LAYER, "add"); blendMethod = BlendMethod.parse(blend); if (blendMethod == null) { properties.error("%s: unknown blend method %s", PARTICLE_PROPERTIES, blend); } else if (enable) { properties.config("using %s blending for fireworks particles", blendMethod); } else { properties.config("using default blending for fireworks particles"); } } }
Angelica
src\main\java\com\prupe\mcpatcher\sky\SkyRenderer.java
package com.prupe.mcpatcher.sky; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import org.lwjgl.opengl.GL11; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.resource.BlendMethod; import com.prupe.mcpatcher.mal.resource.GLAPI; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.resource.TexturePackChangeHandler; import jss.notfine.config.MCPatcherForgeConfig; public class SkyRenderer { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.BETTER_SKIES); private static final boolean enable = MCPatcherForgeConfig.BetterSkies.skybox; private static final boolean unloadTextures = MCPatcherForgeConfig.BetterSkies.unloadTextures; public static final double horizonHeight = MCPatcherForgeConfig.BetterSkies.horizon; private static double worldTime; private static float celestialAngle; private static float rainStrength; private static final Map<Integer, WorldEntry> worldSkies = new HashMap<>(); private static WorldEntry currentWorld; public static boolean active; static { TexturePackChangeHandler.register(new TexturePackChangeHandler(MCPatcherUtils.BETTER_SKIES, 2) { @Override public void beforeChange() { worldSkies.clear(); } @Override public void afterChange() { if (enable) { World world = Minecraft.getMinecraft().theWorld; if (world != null) { getWorldEntry(world.provider.dimensionId); } } FireworksHelper.reload(); } }); } public static void setup(World world, float partialTick, float celestialAngle) { if (TexturePackAPI.isDefaultTexturePack()) { active = false; } else { int worldType = Minecraft.getMinecraft().theWorld.provider.dimensionId; WorldEntry newEntry = getWorldEntry(worldType); if (newEntry != currentWorld && currentWorld != null) { currentWorld.unloadTextures(); } currentWorld = newEntry; active = currentWorld.active(); if (active) { worldTime = world.getWorldTime() + partialTick; rainStrength = 1.0f - world.getRainStrength(partialTick); SkyRenderer.celestialAngle = celestialAngle; } } } public static void renderAll() { if (active) { currentWorld.renderAll(); } } public static ResourceLocation setupCelestialObject(ResourceLocation defaultTexture) { if (active) { Layer.clearBlendingMethod(); Layer layer = currentWorld.getCelestialObject(defaultTexture); if (layer != null) { layer.setBlendingMethod(rainStrength); return layer.texture; } } return defaultTexture; } private static WorldEntry getWorldEntry(int worldType) { WorldEntry entry = worldSkies.get(worldType); if (entry == null) { entry = new WorldEntry(worldType); worldSkies.put(worldType, entry); } return entry; } private static class WorldEntry { private final int worldType; private final List<Layer> skies = new ArrayList<>(); private final Map<ResourceLocation, Layer> objects = new HashMap<>(); private final Set<ResourceLocation> textures = new HashSet<>(); WorldEntry(int worldType) { this.worldType = worldType; loadSkies(); loadCelestialObject("sun"); loadCelestialObject("moon_phases"); } private void loadSkies() { for (int i = -1;; i++) { String path = "sky/world" + worldType + "/sky" + (i < 0 ? "" : String.valueOf(i)) + ".properties"; ResourceLocation resource = TexturePackAPI.newMCPatcherResourceLocation(path); Layer layer = Layer.create(resource); if (layer == null) { if (i > 0) { break; } } else if (layer.properties.valid()) { logger.fine("loaded %s", resource); skies.add(layer); textures.add(layer.texture); } } } private void loadCelestialObject(String objName) { ResourceLocation textureName = new ResourceLocation("textures" + "/environment/" + objName + ".png"); String path = "sky/world" + worldType + "/" + objName + ".properties"; ResourceLocation resource = TexturePackAPI.newMCPatcherResourceLocation(path); PropertiesFile properties = PropertiesFile.get(logger, resource); if (properties != null) { properties.setProperty("fade", "false"); properties.setProperty("rotate", "true"); Layer layer = new Layer(properties); if (properties.valid()) { logger.fine("using %s (%s) for the %s", resource, layer.texture, objName); objects.put(textureName, layer); } } } boolean active() { return !skies.isEmpty() || !objects.isEmpty(); } void renderAll() { if (unloadTextures) { Set<ResourceLocation> texturesNeeded = new HashSet<>(); for (Layer layer : skies) { if (layer.prepare()) { texturesNeeded.add(layer.texture); } } Set<ResourceLocation> texturesToUnload = new HashSet<>(textures); texturesToUnload.removeAll(texturesNeeded); for (ResourceLocation resource : texturesToUnload) { TexturePackAPI.unloadTexture(resource); } } for (Layer layer : skies) { if (!unloadTextures) { layer.prepare(); } if (layer.brightness > 0.0f) { layer.render(); Layer.clearBlendingMethod(); } } } Layer getCelestialObject(ResourceLocation defaultTexture) { return objects.get(defaultTexture); } void unloadTextures() { for (Layer layer : skies) { TexturePackAPI.unloadTexture(layer.texture); } } } private static class Layer { private static final int SECS_PER_DAY = 24 * 60 * 60; private static final int TICKS_PER_DAY = 24000; private static final double TOD_OFFSET = -0.25; private static final double SKY_DISTANCE = 100.0; private final PropertiesFile properties; private ResourceLocation texture; private boolean fade; private boolean rotate; private float[] axis; private float speed; private BlendMethod blendMethod; private double a; private double b; private double c; float brightness; static Layer create(ResourceLocation resource) { PropertiesFile properties = PropertiesFile.get(logger, resource); if (properties == null) { return null; } else { return new Layer(properties); } } Layer(PropertiesFile properties) { this.properties = properties; boolean valid = (readTexture() && readRotation() & readBlendingMethod() && readFadeTimers()); } private boolean readTexture() { texture = properties.getResourceLocation( "source", properties.toString() .replaceFirst("\\.properties$", ".png")); if (TexturePackAPI.hasResource(texture)) { return true; } else { return properties.error("source texture %s not found", texture); } } private boolean readRotation() { rotate = properties.getBoolean("rotate", true); if (rotate) { speed = properties.getFloat("speed", 1.0f); String value = properties.getString("axis", "0.0 0.0 1.0"); String[] tokens = value.split("\\s+"); if (tokens.length == 3) { float x; float y; float z; try { x = Float.parseFloat(tokens[0]); y = Float.parseFloat(tokens[1]); z = Float.parseFloat(tokens[2]); } catch (NumberFormatException e) { return properties.error("invalid rotation axis"); } if (x * x + y * y + z * z == 0.0f) { return properties.error("rotation axis cannot be 0"); } axis = new float[] { z, y, -x }; } else { return properties.error("invalid rotate value %s", value); } } return true; } private boolean readBlendingMethod() { String value = properties.getString("blend", "add"); blendMethod = BlendMethod.parse(value); if (blendMethod == null) { return properties.error("unknown blend method %s", value); } return true; } private boolean readFadeTimers() { fade = properties.getBoolean("fade", true); if (!fade) { return true; } int startFadeIn = parseTime(properties, "startFadeIn"); int endFadeIn = parseTime(properties, "endFadeIn"); int endFadeOut = parseTime(properties, "endFadeOut"); if (!properties.valid()) { return false; } while (endFadeIn <= startFadeIn) { endFadeIn += SECS_PER_DAY; } while (endFadeOut <= endFadeIn) { endFadeOut += SECS_PER_DAY; } if (endFadeOut - startFadeIn >= SECS_PER_DAY) { return properties.error("fade times must fall within a 24 hour period"); } int startFadeOut = startFadeIn + endFadeOut - endFadeIn; // f(x) = a cos x + b sin x + c // f(s0) = 0 // f(s1) = 1 // f(e1) = 0 // Solve for a, b, c using Cramer's rule. double s0 = normalize(startFadeIn, SECS_PER_DAY, TOD_OFFSET); double s1 = normalize(endFadeIn, SECS_PER_DAY, TOD_OFFSET); double e0 = normalize(startFadeOut, SECS_PER_DAY, TOD_OFFSET); double e1 = normalize(endFadeOut, SECS_PER_DAY, TOD_OFFSET); double det = Math.cos(s0) * Math.sin(s1) + Math.cos(e1) * Math.sin(s0) + Math.cos(s1) * Math.sin(e1) - Math.cos(s0) * Math.sin(e1) - Math.cos(s1) * Math.sin(s0) - Math.cos(e1) * Math.sin(s1); if (det == 0.0) { return properties.error("determinant is 0"); } a = (Math.sin(e1) - Math.sin(s0)) / det; b = (Math.cos(s0) - Math.cos(e1)) / det; c = (Math.cos(e1) * Math.sin(s0) - Math.cos(s0) * Math.sin(e1)) / det; logger.finer("%s: y = %f cos x + %f sin x + %f", properties, a, b, c); logger.finer(" at %f: %f", s0, f(s0)); logger.finer(" at %f: %f", s1, f(s1)); logger.finer(" at %f: %f", e0, f(e0)); logger.finer(" at %f: %f", e1, f(e1)); return true; } private int parseTime(PropertiesFile properties, String key) { String s = properties.getString(key, ""); if ("".equals(s)) { properties.error("missing value for %s", key); return -1; } String[] t = s.split(":"); if (t.length >= 2) { try { int hh = Integer.parseInt(t[0].trim()); int mm = Integer.parseInt(t[1].trim()); int ss; if (t.length >= 3) { ss = Integer.parseInt(t[2].trim()); } else { ss = 0; } return (60 * 60 * hh + 60 * mm + ss) % SECS_PER_DAY; } catch (NumberFormatException e) {} } properties.error("invalid %s time %s", key, s); return -1; } private static double normalize(double time, int period, double offset) { return 2.0 * Math.PI * (time / period + offset); } private double f(double x) { return a * Math.cos(x) + b * Math.sin(x) + c; } boolean prepare() { brightness = rainStrength; if (fade) { double x = normalize(worldTime, TICKS_PER_DAY, 0.0); brightness *= (float) f(x); } if (brightness <= 0.0f) { return false; } if (brightness > 1.0f) { brightness = 1.0f; } return true; } boolean render() { TexturePackAPI.bindTexture(texture); setBlendingMethod(brightness); GL11.glPushMatrix(); if (rotate) { GL11.glRotatef(celestialAngle * 360.0f * speed, axis[0], axis[1], axis[2]); } // north GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); GL11.glRotatef(-90.0f, 0.0f, 0.0f, 1.0f); drawTile(4); // top GL11.glPushMatrix(); GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); drawTile(1); GL11.glPopMatrix(); // bottom GL11.glPushMatrix(); GL11.glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); drawTile(0); GL11.glPopMatrix(); // west GL11.glRotatef(90.0f, 0.0f, 0.0f, 1.0f); drawTile(5); // south GL11.glRotatef(90.0f, 0.0f, 0.0f, 1.0f); drawTile(2); // east GL11.glRotatef(90.0f, 0.0f, 0.0f, 1.0f); drawTile(3); GL11.glPopMatrix(); return true; } private static void drawTile(int tile) { double tileX = (tile % 3) / 3.0; double tileY = (tile / 3) / 2.0; final Tessellator tess = Tessellator.instance; tess.startDrawingQuads(); tess.addVertexWithUV(-SKY_DISTANCE, -SKY_DISTANCE, -SKY_DISTANCE, tileX, tileY); tess.addVertexWithUV(-SKY_DISTANCE, -SKY_DISTANCE, SKY_DISTANCE, tileX, tileY + 0.5); tess.addVertexWithUV(SKY_DISTANCE, -SKY_DISTANCE, SKY_DISTANCE, tileX + 1.0 / 3.0, tileY + 0.5); tess.addVertexWithUV(SKY_DISTANCE, -SKY_DISTANCE, -SKY_DISTANCE, tileX + 1.0 / 3.0, tileY); tess.draw(); } void setBlendingMethod(float brightness) { blendMethod.applyFade(brightness); blendMethod.applyAlphaTest(); blendMethod.applyBlending(); GL11.glEnable(GL11.GL_TEXTURE_2D); } static void clearBlendingMethod() { GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glEnable(GL11.GL_BLEND); GLAPI.glBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ZERO); GL11.glColor4f(1.0f, 1.0f, 1.0f, rainStrength); } } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\biome\BiomeAPI.java
package com.prupe.mcpatcher.mal.biome; import java.util.BitSet; import net.minecraft.client.Minecraft; import net.minecraft.world.IBlockAccess; import net.minecraft.world.biome.BiomeGenBase; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.resource.PropertiesFile; public class BiomeAPI { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CUSTOM_COLORS); public static final int WORLD_MAX_HEIGHT = 255; private static boolean biomesLogged; private static BiomeGenBase lastBiome; private static int lastI; private static int lastK; BiomeAPI() {} public static void parseBiomeList(String list, BitSet bits) { logBiomes(); if (MCPatcherUtils.isNullOrEmpty(list)) { return; } for (String s : list.split(list.contains(",") ? "\\s*,\\s*" : "\\s+")) { BiomeGenBase biome = findBiomeByName(s); if (biome != null) { bits.set(biome.biomeID); } } } public static BitSet getHeightListProperty(PropertiesFile properties, String suffix) { int minHeight = Math.max(properties.getInt("minHeight" + suffix, 0), 0); int maxHeight = Math.min(properties.getInt("maxHeight" + suffix, WORLD_MAX_HEIGHT), WORLD_MAX_HEIGHT); String heightStr = properties.getString("heights" + suffix, ""); if (minHeight == 0 && maxHeight == WORLD_MAX_HEIGHT && heightStr.isEmpty()) { return null; } else { BitSet heightBits = new BitSet(WORLD_MAX_HEIGHT + 1); if (heightStr.isEmpty()) { heightStr = minHeight + "-" + maxHeight; } for (int i : MCPatcherUtils.parseIntegerList(heightStr, 0, WORLD_MAX_HEIGHT)) { heightBits.set(i); } return heightBits; } } public static BiomeGenBase findBiomeByName(String name) { logBiomes(); if (name == null) { return null; } name = name.replace(" ", ""); if (name.isEmpty()) { return null; } for (BiomeGenBase biome : BiomeGenBase.getBiomeGenArray()) { if (biome == null || biome.biomeName == null) { continue; } if (name.equalsIgnoreCase(biome.biomeName) || name.equalsIgnoreCase(biome.biomeName.replace(" ", ""))) { if (biome.biomeID >= 0 && biome.biomeID < BiomeGenBase.getBiomeGenArray().length) { return biome; } } } return null; } public static IBlockAccess getWorld() { return Minecraft.getMinecraft().theWorld; } public static int getBiomeIDAt(IBlockAccess blockAccess, int i, int j, int k) { BiomeGenBase biome = getBiomeGenAt(blockAccess, i, j, k); return biome == null ? BiomeGenBase.getBiomeGenArray().length : biome.biomeID; } public static BiomeGenBase getBiomeGenAt(IBlockAccess blockAccess, int i, int j, int k) { if (lastBiome == null || i != lastI || k != lastK) { lastI = i; lastK = k; lastBiome = blockAccess.getBiomeGenForCoords(i, k); } return lastBiome; } public static int getWaterColorMultiplier(BiomeGenBase biome) { return biome == null ? 0xffffff : biome.getWaterColorMultiplier(); } private static void logBiomes() { if (!biomesLogged) { biomesLogged = true; for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) { BiomeGenBase biome = BiomeGenBase.getBiomeGenArray()[i]; if (biome != null) { int x = (int) (255.0f * (1.0f - biome.temperature)); int y = (int) (255.0f * (1.0f - biome.temperature * biome.rainfall)); logger.config( "setupBiome #%d id=%d \"%s\" %06x (%d,%d)", i, biome.biomeID, biome.biomeName, biome.waterColorMultiplier, x, y); } } } } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\biome\ColorMap.java
package com.prupe.mcpatcher.mal.biome; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Properties; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; import net.minecraft.world.biome.BiomeGenBase; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import com.prupe.mcpatcher.mal.resource.ResourceList; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.util.WeightedIndex; import jss.notfine.config.MCPatcherForgeConfig; abstract public class ColorMap implements IColorMap { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CUSTOM_COLORS); public static final boolean useSwampColors = MCPatcherForgeConfig.CustomColors.swampColors; private static final int FIXED = 0; private static final int TEMPERATURE_HUMIDITY = 1; private static final int BIOME_HEIGHT = 2; private static final int COLORMAP_WIDTH = 256; public static final String BLOCK_COLORMAP_DIR = TexturePackAPI.MCPATCHER_SUBDIR + "colormap/blocks"; public static final List<ResourceLocation> unusedPNGs = new ArrayList<>(); private static final String VANILLA_TYPE = "_vanillaType"; private static final String ALT_SOURCE = "_altSource"; private static int defaultColorMapFormat; private static boolean defaultFlipY; private static float defaultYVariance; protected final ResourceLocation resource; protected final int[] map; protected final int width; protected final int height; protected final float maxX; protected final float maxY; private final float[] xy = new float[2]; private final float[] lastColor = new float[3]; public static IColorMap loadVanillaColorMap(ResourceLocation vanillaImage, ResourceLocation swampImage) { Properties properties = new Properties(); properties.setProperty("format", "1"); properties.setProperty("source", vanillaImage.toString()); if (!TexturePackAPI.hasCustomResource(vanillaImage)) { if (vanillaImage.getResourcePath() .contains("grass")) { properties.setProperty(VANILLA_TYPE, "grass"); } else if (vanillaImage.getResourcePath() .contains("foliage")) { properties.setProperty(VANILLA_TYPE, "foliage"); } } if (swampImage != null) { properties.setProperty(ALT_SOURCE, swampImage.toString()); } return loadColorMap(true, vanillaImage, properties); } public static IColorMap loadFixedColorMap(boolean useCustom, ResourceLocation resource) { return loadColorMap(useCustom, resource, null); } public static IColorMap loadColorMap(boolean useCustom, ResourceLocation resource, Properties properties) { IColorMap map = loadColorMap1(useCustom, resource, properties); if (map != null) { map.claimResources(unusedPNGs); } return map; } private static IColorMap loadColorMap1(boolean useCustom, ResourceLocation resource, Properties properties) { if (!useCustom || resource == null) { return null; } ResourceLocation propertiesResource; ResourceLocation imageResource; if (resource.toString() .endsWith(".png")) { propertiesResource = TexturePackAPI.transformResourceLocation(resource, ".png", ".properties"); imageResource = resource; } else if (resource.toString() .endsWith(".properties")) { propertiesResource = resource; imageResource = TexturePackAPI.transformResourceLocation(resource, ".properties", ".png"); } else { return null; } if (properties == null) { properties = TexturePackAPI.getProperties(propertiesResource); if (properties == null) { properties = new Properties(); } } int format = parseFormat(MCPatcherUtils.getStringProperty(properties, "format", "")); if (format == FIXED) { int color = MCPatcherUtils.getHexProperty(properties, "color", 0xffffff); return new Fixed(color); } String path = MCPatcherUtils.getStringProperty(properties, "source", ""); if (!MCPatcherUtils.isNullOrEmpty(path)) { imageResource = TexturePackAPI.parseResourceLocation(resource, path); } BufferedImage image = TexturePackAPI.getImage(imageResource); if (image == null) { return null; } switch (format) { case TEMPERATURE_HUMIDITY: String vanillaSource = MCPatcherUtils.getStringProperty(properties, VANILLA_TYPE, ""); IColorMap defaultMap; if ("grass".equals(vanillaSource)) { defaultMap = new Grass(image); } else if ("foliage".equals(vanillaSource)) { defaultMap = new Foliage(image); } else { defaultMap = new TempHumidity(imageResource, properties, image); } path = MCPatcherUtils.getStringProperty(properties, ALT_SOURCE, ""); if (useSwampColors && !MCPatcherUtils.isNullOrEmpty(path)) { ResourceLocation swampResource = TexturePackAPI.parseResourceLocation(resource, path); image = TexturePackAPI.getImage(swampResource); if (image != null) { IColorMap swampMap = new TempHumidity(swampResource, properties, image); return new Swamp(defaultMap, swampMap); } } return defaultMap; case BIOME_HEIGHT: Grid grid = new Grid(imageResource, properties, image); if (grid.isInteger()) { return new IntegerGrid(grid); } else { return grid; } default: logger.error("%s: unknown format %d", resource, format); return null; } } public static void reset() { unusedPNGs.clear(); defaultColorMapFormat = TEMPERATURE_HUMIDITY; defaultFlipY = false; defaultYVariance = MCPatcherForgeConfig.CustomColors.yVariance; } public static void reloadColorMapSettings(PropertiesFile properties) { unusedPNGs.addAll( ResourceList.getInstance() .listResources(BLOCK_COLORMAP_DIR, ".png", false)); defaultColorMapFormat = parseFormat(properties.getString("palette.format", "")); defaultFlipY = properties.getBoolean("palette.flipY", false); defaultYVariance = properties.getFloat("palette.yVariance", 0.0f); } private static int parseFormat(String value) { if (MCPatcherUtils.isNullOrEmpty(value)) { return defaultColorMapFormat; } value = value.toLowerCase(); if (value.matches("^\\d+$")) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { e.printStackTrace(); } } else if (value.equals("fixed")) { return FIXED; } else if (value.equals("temperature+humidity") || value.equals("t+h") || value.equals("vanilla")) { return TEMPERATURE_HUMIDITY; } else if (value.equals("biome+height") || value.equals("b+h") || value.equals("grid")) { return BIOME_HEIGHT; } return defaultColorMapFormat; } ColorMap(ResourceLocation resource, Properties properties, BufferedImage image) { this(resource, MCPatcherUtils.getImageRGB(image), image.getWidth(), image.getHeight()); } ColorMap(ResourceLocation resource, int[] map, int width, int height) { this.resource = resource; this.map = map; this.width = width; this.height = height; for (int i = 0; i < map.length; i++) { map[i] &= 0xffffff; } maxX = width - 1.0f; maxY = height - 1.0f; } abstract protected void computeXY(BiomeGenBase biome, int i, int j, int k, float[] f); @Override public String toString() { return getClass().getSimpleName() + "{" + resource + "}"; } @Override public final int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { // TODO: implement this neatly BiomeGenBase base = BiomeAPI.getBiomeGenAt(blockAccess, i, j, k); computeXY(base, i, j, k, xy); return getRGB(xy[0], xy[1]); } @Override public final float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { int rgb = getColorMultiplier(blockAccess, i, j, k); ColorUtils.intToFloat3(rgb, lastColor); return lastColor; } @Override public void claimResources(Collection<ResourceLocation> resources) { resources.remove(resource); } protected int getRGB(float x, float y) { x = MathHelper.clamp_float(x, 0.0f, maxX); y = MathHelper.clamp_float(y, 0.0f, maxY); int x0 = (int) x; int dx = (int) (256.0f * (x - (float) x0)); int x1 = x0 + 1; int y0 = (int) y; int dy = (int) (256.0f * (y - (float) y0)); int y1 = y0 + 1; if (dx == 0 && dy == 0) { return getRGB(x0, y0); } else if (dx == 0) { return interpolate(x0, y0, x0, y1, dy); } else if (dy == 0) { return interpolate(x0, y0, x1, y0, dx); } else { return interpolate(interpolate(x0, y0, x1, y0, dx), interpolate(x0, y1, x1, y1, dx), dy); } } private int getRGB(int x, int y) { return map[x + width * y]; } private int interpolate(int x1, int y1, int x2, int y2, int a2) { return interpolate(getRGB(x1, y1), getRGB(x2, y2), a2); } private static int interpolate(int rgb1, int rgb2, int a2) { int a1 = 256 - a2; int r1 = (rgb1 >> 16) & 0xff; int g1 = (rgb1 >> 8) & 0xff; int b1 = rgb1 & 0xff; int r2 = (rgb2 >> 16) & 0xff; int g2 = (rgb2 >> 8) & 0xff; int b2 = rgb2 & 0xff; int r = (a1 * r1 + a2 * r2) >> 8; int g = (a1 * g1 + a2 * g2) >> 8; int b = (a1 * b1 + a2 * b2) >> 8; return (r << 16) | (g << 8) | b; } protected static float noise0to1(int i, int j, int k, int l) { int hash = (int) WeightedIndex.hash128To64(i, j, k, l) & Integer.MAX_VALUE; return (float) ((double) hash / (double) Integer.MAX_VALUE); } protected static float noiseMinus1to1(int i, int j, int k, int l) { int hash = (int) WeightedIndex.hash128To64(i, j, k, l); return (float) ((double) hash / (double) Integer.MIN_VALUE); } public static final class Fixed implements IColorMap { private final int colorI; private final float[] colorF = new float[3]; public Fixed(int color) { colorI = color; ColorUtils.intToFloat3(colorI, colorF); } @Override public String toString() { return String.format("Fixed{%06x}", colorI); } @Override public boolean isHeightDependent() { return false; } @Override public int getColorMultiplier() { return colorI; } @Override public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { return colorI; } @Override public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { return colorF; } @Override public void claimResources(Collection<ResourceLocation> resources) {} @Override public IColorMap copy() { return this; } } public static final class Water implements IColorMap { private final float[] lastColor = new float[3]; @Override public String toString() { return String.format("Water{%06x}", getColorMultiplier()); } @Override public boolean isHeightDependent() { return false; } @Override public int getColorMultiplier() { return BiomeAPI.getWaterColorMultiplier(BiomeAPI.findBiomeByName("Ocean")); } @Override public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { return BiomeAPI.getWaterColorMultiplier(BiomeAPI.getBiomeGenAt(blockAccess, i, j, k)); } @Override public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { ColorUtils.intToFloat3(getColorMultiplier(blockAccess, i, j, k), lastColor); return lastColor; } @Override public void claimResources(Collection<ResourceLocation> resources) {} @Override public IColorMap copy() { return new Water(); } } public abstract static class Vanilla implements IColorMap { protected final int defaultColor; protected final float[] lastColor = new float[3]; Vanilla(BufferedImage image) { this(image.getRGB(127, 127)); } Vanilla(int defaultColor) { this.defaultColor = defaultColor & 0xffffff; } @Override public String toString() { return String.format("%s{%06x}", getClass().getSimpleName(), defaultColor); } @Override final public boolean isHeightDependent() { return true; } @Override final public int getColorMultiplier() { return defaultColor; } @Override final public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { return getColorMultiplier(BiomeAPI.getBiomeGenAt(blockAccess, i, j, k), i, j, k); } @Override final public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { ColorUtils.intToFloat3(getColorMultiplier(blockAccess, i, j, k), lastColor); return lastColor; } @Override final public void claimResources(Collection<ResourceLocation> resources) {} abstract int getColorMultiplier(BiomeGenBase biome, int i, int j, int k); } public static final class Grass extends Vanilla { Grass(BufferedImage image) { super(image); } Grass(int defaultColor) { super(defaultColor); } @Override public IColorMap copy() { return new Grass(defaultColor); } @Override int getColorMultiplier(BiomeGenBase biome, int i, int j, int k) { return biome.getBiomeGrassColor(i, j, k); } } public static final class Foliage extends Vanilla { Foliage(BufferedImage image) { super(image); } Foliage(int defaultColor) { super(defaultColor); } @Override public IColorMap copy() { return new Foliage(defaultColor); } @Override int getColorMultiplier(BiomeGenBase biome, int i, int j, int k) { return biome.getBiomeFoliageColor(i, j, k); } } public static final class Swamp implements IColorMap { private final IColorMap defaultMap; private final IColorMap swampMap; private final BiomeGenBase swampBiome; Swamp(IColorMap defaultMap, IColorMap swampMap) { this.defaultMap = defaultMap; this.swampMap = swampMap; swampBiome = BiomeAPI.findBiomeByName("Swampland"); } @Override public String toString() { return defaultMap.toString(); } @Override public boolean isHeightDependent() { return defaultMap.isHeightDependent() || swampMap.isHeightDependent(); } @Override public int getColorMultiplier() { return defaultMap.getColorMultiplier(); } @Override public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { IColorMap map = BiomeAPI.getBiomeGenAt(blockAccess, i, j, k) == swampBiome ? swampMap : defaultMap; return map.getColorMultiplier(blockAccess, i, j, k); } @Override public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { IColorMap map = BiomeAPI.getBiomeGenAt(blockAccess, i, j, k) == swampBiome ? swampMap : defaultMap; return map.getColorMultiplierF(blockAccess, i, j, k); } @Override public void claimResources(Collection<ResourceLocation> resources) { defaultMap.claimResources(resources); swampMap.claimResources(resources); } @Override public IColorMap copy() { return new Swamp(defaultMap.copy(), swampMap.copy()); } } public static final class TempHumidity extends ColorMap { private final int defaultColor; private TempHumidity(ResourceLocation resource, Properties properties, BufferedImage image) { super(resource, properties, image); defaultColor = MCPatcherUtils.getHexProperty(properties, "color", getRGB(maxX * 0.5f, maxY * 0.5f)); } private TempHumidity(ResourceLocation resource, int[] map, int width, int height, int defaultColor) { super(resource, map, width, height); this.defaultColor = defaultColor; } @Override public boolean isHeightDependent() { return true; } @Override public int getColorMultiplier() { return defaultColor; } @Override public IColorMap copy() { return new TempHumidity(resource, map, width, height, defaultColor); } @Override protected void computeXY(BiomeGenBase biome, int i, int j, int k, float[] f) { float temperature = ColorUtils.clamp(biome.getFloatTemperature(i, j, k)); float rainfall = ColorUtils.clamp(biome.getFloatRainfall()); f[0] = maxX * (1.0f - temperature); f[1] = maxY * (1.0f - temperature * rainfall); } } public static final class Grid extends ColorMap { private final float[] biomeX = new float[BiomeGenBase.getBiomeGenArray().length]; private final float yVariance; private final float yOffset; private final int defaultColor; private Grid(ResourceLocation resource, Properties properties, BufferedImage image) { super(resource, properties, image); if (MCPatcherUtils.getBooleanProperty(properties, "flipY", defaultFlipY)) { int[] temp = new int[width]; for (int i = 0; i < map.length / 2; i += width) { int j = map.length - width - i; System.arraycopy(map, i, temp, 0, width); System.arraycopy(map, j, map, i, width); System.arraycopy(temp, 0, map, j, width); } } yVariance = Math.max(MCPatcherUtils.getFloatProperty(properties, "yVariance", defaultYVariance), 0.0f); yOffset = MCPatcherUtils.getFloatProperty(properties, "yOffset", 0.0f); for (int i = 0; i < biomeX.length; i++) { biomeX[i] = i % width; } for (Map.Entry<Object, Object> entry : properties.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); if (key.endsWith(".x") && !MCPatcherUtils.isNullOrEmpty(value)) { key = key.substring(0, key.length() - 2); BiomeGenBase biome = BiomeAPI.findBiomeByName(key); if (biome != null && biome.biomeID >= 0 && biome.biomeID < BiomeGenBase.getBiomeGenArray().length) { try { biomeX[biome.biomeID] = Float.parseFloat(value); } catch (NumberFormatException e) { e.printStackTrace(); } } } } defaultColor = MCPatcherUtils .getHexProperty(properties, "color", getRGB(biomeX[1], getY(ColorMapBase.DEFAULT_HEIGHT))); } private Grid(ResourceLocation resource, int[] map, int width, int height, float[] biomeX, float yVariance, float yOffset, int defaultColor) { super(resource, map, width, height); System.arraycopy(biomeX, 0, this.biomeX, 0, biomeX.length); this.yVariance = yVariance; this.yOffset = yOffset; this.defaultColor = defaultColor; } boolean isInteger() { if (yVariance != 0.0f || Math.floor(yOffset) != yOffset) { return false; } for (int i = 0; i < biomeX.length; i++) { if (biomeX[i] != i % width) { return false; } } return true; } @Override public boolean isHeightDependent() { return true; } @Override public int getColorMultiplier() { return defaultColor; } @Override public IColorMap copy() { return new Grid(resource, map, width, height, biomeX, yVariance, yOffset, defaultColor); } @Override protected void computeXY(BiomeGenBase biome, int i, int j, int k, float[] f) { f[0] = getX(biome, i, j, k); f[1] = getY(biome, i, j, k); } private float getX(BiomeGenBase biome, int i, int j, int k) { return biomeX[biome.biomeID]; } private float getY(int j) { return (float) j - yOffset; } private float getY(BiomeGenBase biome, int i, int j, int k) { float y = getY(j); if (yVariance != 0.0f) { y += yVariance * noiseMinus1to1(k, -j, i, ~biome.biomeID); } return y; } } public static final class IntegerGrid implements IColorMap { private final ResourceLocation resource; private final int[] map; private final int width; private final int maxHeight; private final int yOffset; private final int defaultColor; private final float[] lastColor = new float[3]; IntegerGrid(Grid grid) { this(grid.resource, grid.map, grid.width, grid.height - 1, (int) grid.yOffset, grid.defaultColor); } IntegerGrid(ResourceLocation resource, int[] map, int width, int maxHeight, int yOffset, int defaultColor) { this.resource = resource; this.map = map; this.width = width; this.maxHeight = maxHeight; this.yOffset = yOffset; this.defaultColor = defaultColor; } @Override public String toString() { return getClass().getSimpleName() + "{" + resource + "}"; } @Override public boolean isHeightDependent() { return true; } @Override public int getColorMultiplier() { return defaultColor; } @Override public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { return getRGB(BiomeAPI.getBiomeIDAt(blockAccess, i, j, k), j); } @Override public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { int rgb = getColorMultiplier(blockAccess, i, j, k); ColorUtils.intToFloat3(rgb, lastColor); return lastColor; } @Override public void claimResources(Collection<ResourceLocation> resources) { resources.remove(resource); } @Override public IColorMap copy() { return new IntegerGrid(resource, map, width, maxHeight, yOffset, defaultColor); } private int getRGB(int x, int y) { x = MathHelper.clamp_int(x, 0, COLORMAP_WIDTH - 1) % width; y = MathHelper.clamp_int(y - yOffset, 0, maxHeight); return map[y * width + x]; } } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\biome\ColorMapBase.java
package com.prupe.mcpatcher.mal.biome; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.logging.Level; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; import com.prupe.mcpatcher.MCLogger; abstract public class ColorMapBase { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CUSTOM_COLORS); public static final int DEFAULT_HEIGHT = 64; public static final class Blended implements IColorMap { private final IColorMap parent; private final int blendRadius; private final int[][] offset; private final float[] weight; private final float[] lastColor = new float[3]; public Blended(IColorMap parent, int blendRadius) { this.parent = parent; this.blendRadius = blendRadius; List<int[]> blendOffset = new ArrayList<>(); List<Float> blendWeight = new ArrayList<>(); float blendScale = 0.0f; for (int r = 0; r <= blendRadius; r++) { if (r == 0) { blendScale += addSample(blendOffset, blendWeight, 0, 0); } else { switch (r % 8) { case 1: blendScale += addSamples(blendOffset, blendWeight, r, 0, 1); break; case 2: blendScale += addSamples(blendOffset, blendWeight, r, 1, 1); break; case 3: case 4: blendScale += addSamples(blendOffset, blendWeight, r, 1, 2); break; case 5: case 6: blendScale += addSamples(blendOffset, blendWeight, r, 1, 3); break; case 7: default: blendScale += addSamples(blendOffset, blendWeight, r, 2, 3); break; } } } offset = blendOffset.toArray(new int[blendOffset.size()][]); this.weight = new float[blendWeight.size()]; for (int i = 0; i < blendWeight.size(); i++) { this.weight[i] = blendWeight.get(i) / blendScale; } } private static float addSample(List<int[]> blendOffset, List<Float> blendWeight, int di, int dk) { float weight = (float) Math.pow(1.0f + Math.max(Math.abs(di), Math.abs(dk)), -0.5); blendOffset.add(new int[] { di, dk }); blendWeight.add(weight); return weight; } private static float addSamples(List<int[]> blendOffset, List<Float> blendWeight, int r, int num, int denom) { int s = num * r / denom; float sum = 0.0f; if (r % 2 == 0) { r ^= s; s ^= r; r ^= s; } sum += addSample(blendOffset, blendWeight, r, s); sum += addSample(blendOffset, blendWeight, -s, r); sum += addSample(blendOffset, blendWeight, -r, -s); sum += addSample(blendOffset, blendWeight, s, -r); return sum; } @Override public String toString() { return parent.toString(); } @Override public boolean isHeightDependent() { return parent.isHeightDependent(); } @Override public int getColorMultiplier() { return parent.getColorMultiplier(); } @Override public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { return ColorUtils.float3ToInt(getColorMultiplierF(blockAccess, i, j, k)); } @Override public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { lastColor[0] = 0.0f; lastColor[1] = 0.0f; lastColor[2] = 0.0f; for (int n = 0; n < weight.length; n++) { int[] offset = this.offset[n]; float weight = this.weight[n]; float[] tmpColor = parent.getColorMultiplierF(blockAccess, i + offset[0], j, k + offset[1]); lastColor[0] += tmpColor[0] * weight; lastColor[1] += tmpColor[1] * weight; lastColor[2] += tmpColor[2] * weight; } return lastColor; } @Override public void claimResources(Collection<ResourceLocation> resources) { parent.claimResources(resources); } @Override public IColorMap copy() { return new Blended(parent.copy(), blendRadius); } } public static final class Cached implements IColorMap { private final IColorMap parent; private int lastI = Integer.MIN_VALUE; private int lastJ = Integer.MIN_VALUE; private int lastK = Integer.MIN_VALUE; private int lastColorI; private float[] lastColorF; public Cached(IColorMap parent) { this.parent = parent; } @Override public String toString() { return parent.toString(); } @Override public boolean isHeightDependent() { return parent.isHeightDependent(); } @Override public int getColorMultiplier() { return parent.getColorMultiplier(); } @Override public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { if (i != lastI || j != lastJ || k != lastK) { lastColorI = parent.getColorMultiplier(blockAccess, i, j, k); lastI = i; lastJ = j; lastK = k; } return lastColorI; } @Override public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { if (i != lastI || j != lastJ || k != lastK) { lastColorF = parent.getColorMultiplierF(blockAccess, i, j, k); lastI = i; lastJ = j; lastK = k; } return lastColorF; } @Override public void claimResources(Collection<ResourceLocation> resources) { parent.claimResources(resources); } @Override public IColorMap copy() { return new Cached(parent.copy()); } } public static final class Smoothed implements IColorMap { private final IColorMap parent; private final float smoothTime; private final float[] lastColor = new float[3]; private long lastTime; public Smoothed(IColorMap parent, float smoothTime) { this.parent = parent; this.smoothTime = smoothTime; } @Override public String toString() { return parent.toString(); } @Override public boolean isHeightDependent() { return parent.isHeightDependent(); } @Override public int getColorMultiplier() { return parent.getColorMultiplier(); } @Override public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { return ColorUtils.float3ToInt(getColorMultiplierF(blockAccess, i, j, k)); } @Override public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { float[] currentColor = parent.getColorMultiplierF(blockAccess, i, j, k); long now = System.currentTimeMillis(); if (lastTime == 0L) { lastColor[0] = currentColor[0]; lastColor[1] = currentColor[1]; lastColor[2] = currentColor[2]; } else { float r = ColorUtils.clamp((float) (now - lastTime) / smoothTime); float s = 1.0f - r; lastColor[0] = r * currentColor[0] + s * lastColor[0]; lastColor[1] = r * currentColor[1] + s * lastColor[1]; lastColor[2] = r * currentColor[2] + s * lastColor[2]; } lastTime = now; return lastColor; } @Override public void claimResources(Collection<ResourceLocation> resources) { parent.claimResources(resources); } @Override public IColorMap copy() { return new Smoothed(parent.copy(), smoothTime); } } public static final class Chunked implements IColorMap { private static final int I_MASK = ~0xf; private static final int K_MASK = ~0xf; private static final int I_SIZE = 17; private static final int J_SIZE = 2; private static final int K_SIZE = 17; private static final int IK_SIZE = I_SIZE * K_SIZE; private static final int IJK_SIZE = I_SIZE * J_SIZE * K_SIZE; private final IColorMap parent; private int baseI = Integer.MIN_VALUE; private int baseJ = Integer.MIN_VALUE; private int baseK = Integer.MIN_VALUE; private int baseOffset; private final float[][] data = new float[IJK_SIZE][]; private final float[][] data1 = new float[IJK_SIZE][3]; private final boolean logEnabled = logger.isLoggable(Level.FINEST); private long lastLogTime = System.currentTimeMillis(); private int calls; private int missChunk; private int missSheet; private int missBlock; public Chunked(IColorMap parent) { this.parent = parent; } @Override public String toString() { return parent.toString(); } @Override public boolean isHeightDependent() { return parent.isHeightDependent(); } @Override public int getColorMultiplier() { return parent.getColorMultiplier(); } @Override public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { return ColorUtils.float3ToInt(getColorMultiplierF(blockAccess, i, j, k)); } @Override public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { int offset = getChunkOffset(i, j, k); calls++; if (offset < 0) { setChunkBase(i, j, k); offset = getChunkOffset(i, j, k); missChunk++; } float[] color = data[offset]; if (color == null) { color = data[offset] = data1[offset]; copy3f(color, parent.getColorMultiplierF(blockAccess, i, j, k)); missBlock++; } if (logEnabled) { long now = System.currentTimeMillis(); if (now - lastLogTime > 5000L) { float mult = 100.0f / (float) calls; logger.finest( "%s: calls: %d, miss chunk: %.2f%%, miss sheet: %.2f%%, miss block: %.2f%%", this, calls, (float) missChunk * mult, (float) missSheet * mult, (float) missBlock * mult); lastLogTime = now; } } return color; } @Override public void claimResources(Collection<ResourceLocation> resources) { parent.claimResources(resources); } @Override public IColorMap copy() { return new Chunked(parent.copy()); } private static void copy3f(float[] dst, float[] src) { dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; } private void setChunkBase(int i, int j, int k) { baseI = i & I_MASK; baseJ = j; baseK = k & K_MASK; baseOffset = 0; Arrays.fill(data, null); } private int getChunkOffset(int i, int j, int k) { i -= baseI; j -= baseJ; k -= baseK; if (j >= 0 && j <= J_SIZE && k >= 0 && k < K_SIZE && i >= 0 && i < I_SIZE) { if (j == J_SIZE) { j--; baseJ++; missSheet++; Arrays.fill(data, baseOffset, IJK_SIZE, null); baseOffset ^= IK_SIZE; } return (baseOffset + j * IK_SIZE + k * I_SIZE + i) % IJK_SIZE; } else { return -1; } } } public static final class Outer implements IColorMap { private final IColorMap parent; private final boolean isHeightDependent; private final int mapDefault; public Outer(IColorMap parent) { this.parent = parent; isHeightDependent = parent.isHeightDependent(); mapDefault = parent.getColorMultiplier(); } @Override public String toString() { return parent.toString(); } @Override public boolean isHeightDependent() { return parent.isHeightDependent(); } @Override public int getColorMultiplier() { return mapDefault; } @Override public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) { if (!isHeightDependent) { j = DEFAULT_HEIGHT; } return parent.getColorMultiplier(blockAccess, i, j, k); } @Override public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) { if (!isHeightDependent) { j = DEFAULT_HEIGHT; } return parent.getColorMultiplierF(blockAccess, i, j, k); } @Override public void claimResources(Collection<ResourceLocation> resources) { parent.claimResources(resources); } @Override public IColorMap copy() { return new Outer(parent.copy()); } } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\biome\ColorUtils.java
package com.prupe.mcpatcher.mal.biome; import net.minecraft.util.MathHelper; public class ColorUtils { public static void intToFloat3(int rgb, float[] f, int offset) { if ((rgb & 0xffffff) == 0xffffff) { f[offset] = f[offset + 1] = f[offset + 2] = 1.0f; } else { f[offset] = (float) (rgb & 0xff0000) / (float) 0xff0000; f[offset + 1] = (float) (rgb & 0xff00) / (float) 0xff00; f[offset + 2] = (float) (rgb & 0xff) / (float) 0xff; } } public static void intToFloat3(int rgb, float[] f) { intToFloat3(rgb, f, 0); } public static int float3ToInt(float[] f, int offset) { return ((int) (255.0f * f[offset])) << 16 | ((int) (255.0f * f[offset + 1])) << 8 | (int) (255.0f * f[offset + 2]); } public static int float3ToInt(float[] f) { return float3ToInt(f, 0); } public static float clamp(float f) { return MathHelper.clamp_float(f, 0.0f, 1.0f); } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\biome\IColorMap.java
package com.prupe.mcpatcher.mal.biome; import java.util.Collection; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; public interface IColorMap { boolean isHeightDependent(); int getColorMultiplier(); int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k); float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k); void claimResources(Collection<ResourceLocation> resources); IColorMap copy(); }
Angelica
src\main\java\com\prupe\mcpatcher\mal\block\BlockAPI.java
package com.prupe.mcpatcher.mal.block; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import net.minecraft.block.Block; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.resource.PropertiesFile; import cpw.mods.fml.common.registry.FMLControlledNamespacedRegistry; import cpw.mods.fml.common.registry.GameData; public class BlockAPI { @SuppressWarnings("unchecked") BlockAPI(FMLControlledNamespacedRegistry<Block> registry) { File outputFile = new File("blocks17.txt"); if (outputFile.isFile()) { PrintStream ps = null; try { ps = new PrintStream(outputFile); String[] nameList = new String[4096]; for (String name17 : (Set<String>) registry.getKeys()) { Object block = registry.getObject(name17); if (block != null) { int id = registry.getIDForObject(block); if (id >= 0 && id < nameList.length) { nameList[id] = name17; } } } for (int id = 0; id < nameList.length; id++) { if (nameList[id] != null) { ps.printf("canonicalIdByName.put(\"%s\", %d);\n", nameList[id], id); } } } catch (IOException e) { e.printStackTrace(); } finally { MCPatcherUtils.close(ps); } } } public static String getBlockName(Block block) { return block == null ? "(null)" : block.getUnlocalizedName(); } public static List<Block> getAllBlocks() { List<Block> blocks = new ArrayList<>(); for (Block block : GameData.getBlockRegistry() .typeSafeIterable()) { if (block != null && !blocks.contains(block)) { blocks.add(block); } } return blocks; } public static BlockStateMatcher createMatcher(PropertiesFile source, String matchString) { Map<String, String> propertyMap = new HashMap<>(); String namespace = null; String blockName = null; StringBuilder metadata = new StringBuilder(); StringBuilder metaString = new StringBuilder(); for (String s : matchString.split("\\s*:\\s*")) { if (s.isEmpty()) { continue; } boolean appendThis = false; String[] tokens = s.split("\\s*=\\s*", 2); if (blockName == null) { blockName = s; } else if (tokens.length == 2) { propertyMap.put(tokens[0], tokens[1]); appendThis = true; } else if (namespace == null && !s.matches("\\d[-, 0-9]*")) { namespace = blockName; blockName = s; } else if (s.matches("\\d[-, 0-9]*")) { metadata.append(' ') .append(s); appendThis = true; } else { source.warning("invalid token '%s' in %s", source, s, matchString); return null; } if (appendThis) { metaString.append(':'); metaString.append(s); } } if (MCPatcherUtils.isNullOrEmpty(namespace)) { namespace = source.getResource().getResourceDomain(); } if (MCPatcherUtils.isNullOrEmpty(blockName)) { source.warning("cannot parse namespace/block name from %s", matchString); return null; } Block block = GameData.getBlockRegistry() .getObject(namespace + ':' + blockName); if (block == null) { source.warning("unknown block %s:%s", namespace, blockName); return null; } return new BlockStateMatcher( metaString.toString(), block, metadata.toString() .trim()); } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\block\BlockStateMatcher.java
package com.prupe.mcpatcher.mal.block; import net.minecraft.block.Block; import net.minecraft.world.IBlockAccess; import com.prupe.mcpatcher.MCPatcherUtils; import cpw.mods.fml.common.registry.GameData; public class BlockStateMatcher { private final String fullString; private final ThreadLocal<Object> threadLocal = new ThreadLocal<>(); protected final Block block; protected Object data; private static final int MAX_METADATA = 15; private static final int NO_METADATA = -1; private final int metadataBits; private static Block doublePlantBlock; private static Block logBlock; public BlockStateMatcher(String metaString, Block block, String metadataList) { this.fullString = BlockAPI.getBlockName(block) + metaString; this.block = block; if (MCPatcherUtils.isNullOrEmpty(metadataList)) { metadataBits = NO_METADATA; } else { int bits = 0; for (int i : MCPatcherUtils.parseIntegerList(metadataList, 0, MAX_METADATA)) { bits |= 1 << i; } metadataBits = bits; } doublePlantBlock = GameData.getBlockRegistry() .getObject("minecraft:double_plant"); logBlock = GameData.getBlockRegistry() .getObject("minecraft:log"); } final public Block getBlock() { return block; } final public Object getData() { return data; } final public void setData(Object data) { this.data = data; } final public Object getThreadData() { return threadLocal.get(); } final public void setThreadData(Object data) { threadLocal.set(data); } @Override final public String toString() { return fullString; } public boolean match(IBlockAccess blockAccess, int x, int y, int z) { Block block = blockAccess.getBlock(x, y, z); if (block != this.block) { return false; } int metadata = blockAccess.getBlockMetadata(x, y, z); if (block == doublePlantBlock) { if ((metadata & 0x8) != 0 && blockAccess.getBlock(x, y - 1, z) == block) { metadata = blockAccess.getBlockMetadata(x, y - 1, z); } metadata &= 0x7; } else if (block == logBlock) { metadata &= ~0xc; } return (metadataBits & (1 << metadata)) != 0; } public boolean match(Block block, int metadata) { return block == this.block && (metadataBits & (1 << metadata)) != 0; } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\block\RenderBlocksUtils.java
package com.prupe.mcpatcher.mal.block; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import jss.notfine.config.MCPatcherForgeConfig; // Shared by both CTM and Custom Colors. public class RenderBlocksUtils { private static final int COLOR = 0; private static final int NONCOLOR = 1; private static final int COLOR_AND_NONCOLOR = 2; private static final int[] colorMultiplierType = new int[6]; private static final float[][] nonAOMultipliers = new float[6][3]; public static final float[] AO_BASE = new float[] { 0.5f, 1.0f, 0.8f, 0.8f, 0.6f, 0.6f }; public static int layerIndex; public static IIcon blankIcon; public static void setupColorMultiplier(Block block, IBlockAccess blockAccess, int x, int y, int z, boolean haveOverrideTexture, float r, float g, float b) { if (haveOverrideTexture || !RenderPassAPI.instance.useColorMultiplierThisPass(block)) { colorMultiplierType[0] = COLOR; colorMultiplierType[2] = COLOR; colorMultiplierType[3] = COLOR; colorMultiplierType[4] = COLOR; colorMultiplierType[5] = COLOR; } else if (block == Blocks.grass) { colorMultiplierType[0] = NONCOLOR; if (MCPatcherForgeConfig.ConnectedTextures.betterGrass) { if (isSnowCovered(blockAccess, x, y, z)) { colorMultiplierType[2] = NONCOLOR; colorMultiplierType[3] = NONCOLOR; colorMultiplierType[4] = NONCOLOR; colorMultiplierType[5] = NONCOLOR; } else { y--; colorMultiplierType[2] = block == blockAccess.getBlock(x, y, z - 1) && !isSnowCovered(blockAccess, x, y, z - 1) ? COLOR : COLOR_AND_NONCOLOR; colorMultiplierType[3] = block == blockAccess.getBlock(x, y, z + 1) && !isSnowCovered(blockAccess, x, y, z + 1) ? COLOR : COLOR_AND_NONCOLOR; colorMultiplierType[4] = block == blockAccess.getBlock(x - 1, y, z) && !isSnowCovered(blockAccess, x - 1, y, z) ? COLOR : COLOR_AND_NONCOLOR; colorMultiplierType[5] = block == blockAccess.getBlock(x + 1, y, z) && !isSnowCovered(blockAccess, x + 1, y, z) ? COLOR : COLOR_AND_NONCOLOR; } } else { colorMultiplierType[2] = COLOR_AND_NONCOLOR; colorMultiplierType[3] = COLOR_AND_NONCOLOR; colorMultiplierType[4] = COLOR_AND_NONCOLOR; colorMultiplierType[5] = COLOR_AND_NONCOLOR; } } else { colorMultiplierType[0] = COLOR; colorMultiplierType[2] = COLOR; colorMultiplierType[3] = COLOR; colorMultiplierType[4] = COLOR; colorMultiplierType[5] = COLOR; } if (!isAmbientOcclusionEnabled() || block.getLightValue() != 0) { setupColorMultiplier(0, r, g, b); setupColorMultiplier(1, r, g, b); setupColorMultiplier(2, r, g, b); setupColorMultiplier(3, r, g, b); setupColorMultiplier(4, r, g, b); setupColorMultiplier(5, r, g, b); } } public static void setupColorMultiplier(Block block, boolean useColor) { if (block == Blocks.grass || !useColor) { colorMultiplierType[0] = NONCOLOR; colorMultiplierType[2] = NONCOLOR; colorMultiplierType[3] = NONCOLOR; colorMultiplierType[4] = NONCOLOR; colorMultiplierType[5] = NONCOLOR; } else { colorMultiplierType[0] = COLOR; colorMultiplierType[2] = COLOR; colorMultiplierType[3] = COLOR; colorMultiplierType[4] = COLOR; colorMultiplierType[5] = COLOR; } } private static void setupColorMultiplier(int face, float r, float g, float b) { float[] mult = nonAOMultipliers[face]; float ao = AO_BASE[face]; mult[0] = ao; mult[1] = ao; mult[2] = ao; if (colorMultiplierType[face] != NONCOLOR) { mult[0] *= r; mult[1] *= g; mult[2] *= b; } } public static boolean useColorMultiplier(int face) { layerIndex = 0; return useColorMultiplier1(face); } private static boolean useColorMultiplier1(int face) { if (layerIndex == 0) { return colorMultiplierType[getFaceIndex(face)] == COLOR; } else { return colorMultiplierType[getFaceIndex(face)] != NONCOLOR; } } public static float getColorMultiplierRed(int face) { return nonAOMultipliers[getFaceIndex(face)][0]; } public static float getColorMultiplierGreen(int face) { return nonAOMultipliers[getFaceIndex(face)][1]; } public static float getColorMultiplierBlue(int face) { return nonAOMultipliers[getFaceIndex(face)][2]; } private static int getFaceIndex(int face) { return face < 0 ? 1 : face % 6; } public static IIcon getGrassTexture(Block block, IBlockAccess blockAccess, int x, int y, int z, int face, IIcon topIcon) { if (!MCPatcherForgeConfig.ConnectedTextures.betterGrass || face < 2) { return null; } boolean isSnow = isSnowCovered(blockAccess, x, y, z); y--; switch (face) { case 2 -> z--; case 3 -> z++; case 4 -> x--; case 5 -> x++; default -> { return null; } } if (block != blockAccess.getBlock(x, y, z)) { return null; } boolean neighborIsSnow = isSnowCovered(blockAccess, x, y, z); if (isSnow != neighborIsSnow) { return null; } return isSnow ? Blocks.snow_layer.getIcon(blockAccess, x, y, z, face) : topIcon; } private static boolean isSnowCovered(IBlockAccess blockAccess, int x, int y, int z) { Block topBlock = blockAccess.getBlock(x, y + 1, z); return topBlock == Blocks.snow_layer || topBlock == Blocks.snow; } public static boolean isAmbientOcclusionEnabled() { return Minecraft.isAmbientOcclusionEnabled(); } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\block\RenderPassAPI.java
package com.prupe.mcpatcher.mal.block; import net.minecraft.block.Block; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.mal.resource.BlendMethod; public class RenderPassAPI { public static RenderPassAPI instance = new RenderPassAPI(); private static final String[] NAMES = new String[] { "solid", "cutout_mipped", "cutout", "translucent", "backface", "overlay" }; public static final int SOLID_RENDER_PASS = 0; public static final int CUTOUT_MIPPED_RENDER_PASS = 1; public static final int CUTOUT_RENDER_PASS = 2; public static final int TRANSLUCENT_RENDER_PASS = 3; public static final int BACKFACE_RENDER_PASS = 4; public static final int OVERLAY_RENDER_PASS = 5; public static final int MAX_BASE_RENDER_PASS = BACKFACE_RENDER_PASS; public static final int MAX_EXTRA_RENDER_PASS = NAMES.length - 1; public static final int NUM_RENDER_PASSES = NAMES.length; public int parseRenderPass(String value) { int pass = value.matches("\\d+") ? Integer.parseInt(value) : -1; if (value.equalsIgnoreCase("solid") || pass == 0) { return SOLID_RENDER_PASS; } else if (value.equalsIgnoreCase("cutout_mipped")) { return CUTOUT_MIPPED_RENDER_PASS; } else if (value.equalsIgnoreCase("cutout")) { return CUTOUT_RENDER_PASS; } else if (value.equalsIgnoreCase("translucent") || pass == 1) { return TRANSLUCENT_RENDER_PASS; } else if (value.equalsIgnoreCase("backface") || pass == 2) { return BACKFACE_RENDER_PASS; } else if (value.equalsIgnoreCase("overlay") || pass == 3) { return OVERLAY_RENDER_PASS; } else { return pass; } } public String getRenderPassName(int pass) { if (pass < 0) { return "(default)"; } else if (pass < NAMES.length) { return NAMES[pass]; } else { return "(unknown pass " + pass + ")"; } } public boolean skipDefaultRendering(Block block) { return false; } public boolean skipThisRenderPass(Block block, int pass) { return pass > MAX_BASE_RENDER_PASS; } public boolean useColorMultiplierThisPass(Block block) { return true; } public boolean useLightmapThisPass() { return true; } public void clear() {} public void refreshBlendingOptions() {} public void setRenderPassForBlock(Block block, int pass) {} public ResourceLocation getBlankResource(int pass) { return BlendMethod.ALPHA.getBlankResource(); } public ResourceLocation getBlankResource() { return BlendMethod.ALPHA.getBlankResource(); } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\item\ItemAPI.java
package com.prupe.mcpatcher.mal.item; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Set; import net.minecraft.item.Item; import com.prupe.mcpatcher.MCPatcherUtils; import cpw.mods.fml.common.registry.GameData; public class ItemAPI { @SuppressWarnings("unchecked") ItemAPI() { File outputFile = new File("items17.txt"); if (outputFile.isFile()) { PrintStream ps = null; try { ps = new PrintStream(outputFile); String[] nameList = new String[32000]; for (String name17 : (Set<String>) GameData.getItemRegistry() .getKeys()) { Item item = GameData.getItemRegistry() .getObject(name17); if (item != null) { int id = GameData.getItemRegistry() .getIDForObject(item); if (id >= 256 && id < nameList.length) { nameList[id] = name17; } } } for (int id = 0; id < nameList.length; id++) { if (nameList[id] != null) { ps.printf("canonicalIdByName.put(\"%s\", %d);\n", nameList[id], id); } } } catch (IOException e) { e.printStackTrace(); } finally { MCPatcherUtils.close(ps); } } } public static Item getFixedItem(String name) { Item item = parseItemName(name); if (item == null) { throw new IllegalArgumentException("unknown item " + name); } else { return item; } } public static Item parseItemName(String name) { if (MCPatcherUtils.isNullOrEmpty(name)) { return null; } if (name.matches("\\d+")) { int id = Integer.parseInt(name); return GameData.getItemRegistry() .getObjectById(id); } name = getFullName(name); return GameData.getItemRegistry() .getObject(name); } public static String getItemName(Item item) { if (item == null) { return "(null)"; } String name = GameData.getItemRegistry() .getNameForObject(item); return name == null ? String.valueOf( GameData.getItemRegistry() .getIDForObject(item)) : name; } public static String getFullName(String name) { return name == null ? null : name.indexOf(':') >= 0 ? name : "minecraft:" + name; } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\nbt\NBTRule.java
package com.prupe.mcpatcher.mal.nbt; import java.lang.reflect.Method; import java.util.regex.Pattern; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagByte; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagDouble; import net.minecraft.nbt.NBTTagFloat; import net.minecraft.nbt.NBTTagInt; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagLong; import net.minecraft.nbt.NBTTagShort; import net.minecraft.nbt.NBTTagString; import jss.notfine.util.NBTTagCompoundExpansion; import jss.notfine.util.NBTTagListExpansion; abstract public class NBTRule { public static final String NBT_RULE_PREFIX = "nbt."; public static final String NBT_RULE_SEPARATOR = "."; public static final String NBT_RULE_WILDCARD = "*"; public static final String NBT_REGEX_PREFIX = "regex:"; public static final String NBT_IREGEX_PREFIX = "iregex:"; public static final String NBT_GLOB_PREFIX = "pattern:"; public static final String NBT_IGLOB_PREFIX = "ipattern:"; private final String[] tagName; private final Integer[] tagIndex; public static NBTRule create(String tag, String value) { if (tag == null || value == null || !tag.startsWith(NBT_RULE_PREFIX)) { return null; } try { tag = tag.substring(NBT_RULE_PREFIX.length()); if (value.startsWith(NBT_REGEX_PREFIX)) { return new Regex(tag, value.substring(NBT_REGEX_PREFIX.length()), true); } else if (value.startsWith(NBT_IREGEX_PREFIX)) { return new Regex(tag, value.substring(NBT_IREGEX_PREFIX.length()), false); } else if (value.startsWith(NBT_GLOB_PREFIX)) { return new Glob(tag, value.substring(NBT_GLOB_PREFIX.length()), true); } else if (value.startsWith(NBT_IGLOB_PREFIX)) { return new Glob(tag, value.substring(NBT_IGLOB_PREFIX.length()), false); } else { return new Exact(tag, value); } } catch (Exception e) { e.printStackTrace(); return null; } } protected NBTRule(String tag, String value) { tagName = tag.split(Pattern.quote(NBT_RULE_SEPARATOR)); tagIndex = new Integer[tagName.length]; for (int i = 0; i < tagName.length; i++) { if (NBT_RULE_WILDCARD.equals(tagName[i])) { tagName[i] = null; tagIndex[i] = null; } else { try { tagIndex[i] = Integer.valueOf(tagName[i]); } catch (NumberFormatException e) { tagIndex[i] = -1; } } } } public final boolean match(NBTTagCompound nbt) { return nbt != null && match(nbt, 0); } private boolean match(NBTTagCompound nbt, int index) { if (index >= tagName.length) { return false; } else if (tagName[index] == null) { for (NBTBase nbtBase : ((NBTTagCompoundExpansion) nbt).getTags()) { if (match1(nbtBase, index + 1)) { return true; } } return false; } else { NBTBase nbtBase = nbt.getTag(tagName[index]); return match1(nbtBase, index + 1); } } private boolean match(NBTTagList nbt, int index) { if (index >= tagIndex.length) { return false; } else if (tagIndex[index] == null) { for (int i = 0; i < nbt.tagCount(); i++) { if (match1(((NBTTagListExpansion) nbt).tagAt(i), index + 1)) { return true; } } return false; } else { int tagNum = tagIndex[index]; return tagNum >= 0 && tagNum < nbt.tagCount() && match1(((NBTTagListExpansion) nbt).tagAt(tagNum), index + 1); } } private boolean match1(NBTBase nbt, int index) { if (nbt == null) { return false; } else if (nbt instanceof NBTTagCompound) { return match((NBTTagCompound) nbt, index); } else if (nbt instanceof NBTTagList) { return match((NBTTagList) nbt, index); } else if (index < tagName.length) { return false; } else if (nbt instanceof NBTTagString) { return match((NBTTagString) nbt); } else if (nbt instanceof NBTTagInt) { return match((NBTTagInt) nbt); } else if (nbt instanceof NBTTagDouble) { return match((NBTTagDouble) nbt); } else if (nbt instanceof NBTTagFloat) { return match((NBTTagFloat) nbt); } else if (nbt instanceof NBTTagLong) { return match((NBTTagLong) nbt); } else if (nbt instanceof NBTTagShort) { return match((NBTTagShort) nbt); } else if (nbt instanceof NBTTagByte) { return match((NBTTagByte) nbt); } else { return false; } } protected boolean match(NBTTagByte nbt) { return false; } protected boolean match(NBTTagDouble nbt) { return false; } protected boolean match(NBTTagFloat nbt) { return false; } protected boolean match(NBTTagInt nbt) { return false; } protected boolean match(NBTTagLong nbt) { return false; } protected boolean match(NBTTagShort nbt) { return false; } protected boolean match(NBTTagString nbt) { return false; } private static final class Exact extends NBTRule { private final Byte byteValue; private final Double doubleValue; private final Float floatValue; private final Integer integerValue; private final Long longValue; private final Short shortValue; private final String stringValue; Exact(String tag, String value) { super(tag, value); stringValue = value; doubleValue = parse(Double.class, value); if (doubleValue == null) { floatValue = null; } else { floatValue = doubleValue.floatValue(); } longValue = parse(Long.class, value); if (longValue == null) { byteValue = null; integerValue = null; shortValue = null; } else { byteValue = longValue.byteValue(); integerValue = longValue.intValue(); shortValue = longValue.shortValue(); } } // Cursed private static <T extends Number> T parse(Class<T> cl, String value) { try { Method valueOf = cl.getDeclaredMethod("valueOf", String.class); Object result = valueOf.invoke(null, value); if (result != null && cl.isAssignableFrom(result.getClass())) { return cl.cast(result); } } catch (Exception e) {} return null; } @Override protected boolean match(NBTTagByte nbt) { return byteValue != null && byteValue == nbt.func_150290_f(); } @Override protected boolean match(NBTTagDouble nbt) { return doubleValue != null && doubleValue == nbt.func_150286_g(); } @Override protected boolean match(NBTTagFloat nbt) { return floatValue != null && floatValue == nbt.func_150288_h(); } @Override protected boolean match(NBTTagInt nbt) { return integerValue != null && integerValue == nbt.func_150287_d(); } @Override protected boolean match(NBTTagLong nbt) { return longValue != null && longValue == nbt.func_150291_c(); } @Override protected boolean match(NBTTagShort nbt) { return shortValue != null && shortValue == nbt.func_150289_e(); } @Override protected boolean match(NBTTagString nbt) { return nbt.func_150285_a_() .equals(stringValue); } } private static final class Regex extends NBTRule { private final Pattern pattern; Regex(String tag, String value, boolean caseSensitive) { super(tag, value); pattern = Pattern.compile(value, caseSensitive ? 0 : Pattern.CASE_INSENSITIVE); } @Override protected boolean match(NBTTagString nbt) { return pattern.matcher(nbt.func_150285_a_()) .matches(); } } private static final class Glob extends NBTRule { private static final char STAR = '*'; private static final char SINGLE = '?'; private static final char ESCAPE = '\\'; private final String glob; private final boolean caseSensitive; protected Glob(String tag, String value, boolean caseSensitive) { super(tag, value); this.caseSensitive = caseSensitive; if (!caseSensitive) { value = value.toLowerCase(); } glob = value; } @Override protected boolean match(NBTTagString nbt) { String value = nbt.func_150285_a_(); return matchPartial(value, 0, value.length(), 0, glob.length()); } private boolean matchPartial(String value, int curV, int maxV, int curG, int maxG) { for (; curG < maxG; curG++, curV++) { char g = glob.charAt(curG); if (g == STAR) { while (true) { if (matchPartial(value, curV, maxV, curG + 1, maxG)) { return true; } if (curV >= maxV) { break; } curV++; } return false; } else if (curV >= maxV) { break; } else if (g == SINGLE) { continue; } if (g == ESCAPE && curG + 1 < maxG) { curG++; g = glob.charAt(curG); } if (!matchChar(g, value.charAt(curV))) { return false; } } return curG == maxG && curV == maxV; } private boolean matchChar(char a, char b) { return a == (caseSensitive ? b : Character.toLowerCase(b)); } } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\resource\BlendMethod.java
package com.prupe.mcpatcher.mal.resource; import java.util.HashSet; import java.util.Set; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import com.prupe.mcpatcher.MCPatcherUtils; public class BlendMethod { private static final Set<ResourceLocation> blankResources = new HashSet<>(); public static final BlendMethod ALPHA = new BlendMethod( "alpha", GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, true, false, true, 0); public static final BlendMethod ADD = new BlendMethod("add", GL11.GL_SRC_ALPHA, GL11.GL_ONE, true, false, true, 0); public static final BlendMethod SUBTRACT = new BlendMethod( "subtract", GL11.GL_ONE_MINUS_DST_COLOR, GL11.GL_ZERO, true, true, false, 0); public static final BlendMethod MULTIPLY = new BlendMethod( "multiply", GL11.GL_DST_COLOR, GL11.GL_ONE_MINUS_SRC_ALPHA, true, true, true, 0xffffffff); public static final BlendMethod DODGE = new BlendMethod("dodge", GL11.GL_ONE, GL11.GL_ONE, true, true, false, 0); public static final BlendMethod BURN = new BlendMethod( "burn", GL11.GL_ZERO, GL11.GL_ONE_MINUS_SRC_COLOR, true, true, false, null); public static final BlendMethod SCREEN = new BlendMethod( "screen", GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_COLOR, true, true, false, 0xffffffff); public static final BlendMethod OVERLAY = new BlendMethod( "overlay", GL11.GL_DST_COLOR, GL11.GL_SRC_COLOR, true, true, false, 0x80808080); public static final BlendMethod REPLACE = new BlendMethod("replace", 0, 0, false, false, true, null); private final int srcBlend; private final int dstBlend; private final String name; private final boolean blend; private final boolean fadeRGB; private final boolean fadeAlpha; private final ResourceLocation blankResource; public static BlendMethod parse(String text) { text = text.toLowerCase() .trim(); switch (text) { case "alpha" -> { return ALPHA; } case "add" -> { return ADD; } case "subtract" -> { return SUBTRACT; } case "multiply" -> { return MULTIPLY; } case "dodge" -> { return DODGE; } case "burn" -> { return BURN; } case "screen" -> { return SCREEN; } case "overlay", "color" -> { return OVERLAY; } case "replace", "none" -> { return REPLACE; } default -> { String[] tokens = text.split("\\s+"); if (tokens.length >= 2) { try { int srcBlend = Integer.parseInt(tokens[0]); int dstBlend = Integer.parseInt(tokens[1]); return new BlendMethod( "custom(" + srcBlend + "," + dstBlend + ")", srcBlend, dstBlend, true, true, false, 0); } catch (NumberFormatException e) {} } } } return null; } public static Set<ResourceLocation> getAllBlankResources() { return blankResources; } private BlendMethod(String name, int srcBlend, int dstBlend, boolean blend, boolean fadeRGB, boolean fadeAlpha, Integer neutralRGB) { this.name = name; this.srcBlend = srcBlend; this.dstBlend = dstBlend; this.blend = blend; this.fadeRGB = fadeRGB; this.fadeAlpha = fadeAlpha; if (neutralRGB == null) { blankResource = null; } else { String filename = String.format(MCPatcherUtils.BLANK_PNG_FORMAT, neutralRGB); blankResource = TexturePackAPI.newMCPatcherResourceLocation(filename); } if (blankResource != null) { blankResources.add(blankResource); } } @Override public String toString() { return name; } public void applyFade(float fade) { if (fadeRGB && fadeAlpha) { GL11.glColor4f(fade, fade, fade, fade); } else if (fadeRGB) { GL11.glColor4f(fade, fade, fade, 1.0f); } else if (fadeAlpha) { GL11.glColor4f(1.0f, 1.0f, 1.0f, fade); } } public void applyAlphaTest() { if (blend) { GL11.glDisable(GL11.GL_ALPHA_TEST); } else { GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glAlphaFunc(GL11.GL_GREATER, 0.01f); } } public void applyDepthFunc() { if (blend) { GL11.glDepthFunc(GL11.GL_EQUAL); } else { GL11.glDepthFunc(GL11.GL_LEQUAL); GL11.glDepthMask(true); } } public void applyBlending() { if (blend) { GL11.glEnable(GL11.GL_BLEND); GLAPI.glBlendFuncSeparate(srcBlend, dstBlend, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); } else { GL11.glDisable(GL11.GL_BLEND); } } public boolean isColorBased() { return fadeRGB; } public boolean canFade() { return blend && (fadeAlpha || fadeRGB); } public ResourceLocation getBlankResource() { return blankResource; } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\resource\GLAPI.java
package com.prupe.mcpatcher.mal.resource; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.GLContext; public class GLAPI { private static final boolean useGlBlendFuncSeparate = GLContext.getCapabilities().OpenGL14; public static void glBindTexture(int texture) { if (texture >= 0) { GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture); } } public static void glBlendFuncSeparate(int src, int dst, int srcAlpha, int dstAlpha) { if (useGlBlendFuncSeparate) { GL14.glBlendFuncSeparate(src, dst, srcAlpha, dstAlpha); } else { GL11.glBlendFunc(src, dst); } } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\resource\PropertiesFile.java
package com.prupe.mcpatcher.mal.resource; import java.util.Map; import java.util.Properties; import java.util.Set; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; final public class PropertiesFile { private final MCLogger logger; private final ResourceLocation resource; private final String prefix; private final Properties properties; private int errorCount; public static PropertiesFile get(MCLogger logger, ResourceLocation resource) { Properties properties = TexturePackAPI.getProperties(resource); if (properties == null) { return null; } else { return new PropertiesFile(logger, resource, properties); } } public static PropertiesFile getNonNull(MCLogger logger, ResourceLocation resource) { PropertiesFile propertiesFile = get(logger, resource); if (propertiesFile == null) { return new PropertiesFile(logger, resource, new Properties()); } else { return propertiesFile; } } public PropertiesFile(MCLogger logger, ResourceLocation resource) { this(logger, resource, new Properties()); } public PropertiesFile(MCLogger logger, ResourceLocation resource, Properties properties) { this.logger = logger; this.resource = resource; prefix = resource == null ? "" : (resource + ": ").replace("%", "%%"); this.properties = properties; } public String getString(String key, String defaultValue) { return MCPatcherUtils.getStringProperty(properties, key, defaultValue); } public ResourceLocation getResourceLocation(String key, String defaultValue) { String value = getString(key, defaultValue); return TexturePackAPI.parseResourceLocation(resource, value); } public int getInt(String key, int defaultValue) { return MCPatcherUtils.getIntProperty(properties, key, defaultValue); } public int getHex(String key, int defaultValue) { return MCPatcherUtils.getHexProperty(properties, key, defaultValue); } public float getFloat(String key, float defaultValue) { return MCPatcherUtils.getFloatProperty(properties, key, defaultValue); } public double getDouble(String key, double defaultValue) { return MCPatcherUtils.getDoubleProperty(properties, key, defaultValue); } public int[] getIntList(String key, int minValue, int maxValue, String defaultValue) { String value = getString(key, defaultValue); if (value == null) { return null; } else { return MCPatcherUtils.parseIntegerList(value, minValue, maxValue); } } public boolean getBoolean(String key, boolean defaultValue) { return MCPatcherUtils.getBooleanProperty(properties, key, defaultValue); } public void setProperty(String key, String value) { properties.setProperty(key, value); } public void finer(String format, Object... params) { logger.finer(prefix + format, params); } public void fine(String format, Object... params) { logger.fine(prefix + format, params); } public void config(String format, Object... params) { logger.config(format, params); } public void warning(String format, Object... params) { logger.warning(prefix + format, params); } public boolean error(String format, Object... params) { logger.error(prefix + format, params); errorCount++; return false; } public int getErrorCount() { return errorCount; } public boolean valid() { return getErrorCount() == 0; } @SuppressWarnings("unchecked") public Set<Map.Entry<String, String>> entrySet() { return (Set<Map.Entry<String, String>>) (Set<?>) properties.entrySet(); } public ResourceLocation getResource() { return resource; } @Override public String toString() { return resource.toString(); } @Override public int hashCode() { return resource.hashCode(); } @Override public boolean equals(Object that) { if (this == that) { return true; } else if (!(that instanceof PropertiesFile)) { return false; } else { return resource.equals(((PropertiesFile) that).resource); } } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\resource\ResourceList.java
package com.prupe.mcpatcher.mal.resource; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.WeakHashMap; import java.util.logging.Level; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import net.minecraft.client.resources.AbstractResourcePack; import net.minecraft.client.resources.DefaultResourcePack; import net.minecraft.client.resources.FileResourcePack; import net.minecraft.client.resources.IResourcePack; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; public class ResourceList { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.TEXTURE_PACK); private static ResourceList instance; private static final Map<IResourcePack, Integer> resourcePackOrder = new WeakHashMap<>(); private final IResourcePack resourcePack; private final Set<ResourceLocationWithSource> allResources = new TreeSet<>( new ResourceLocationWithSource.Comparator1()); public static ResourceList getInstance() { if (instance == null) { List<IResourcePack> resourcePacks = TexturePackAPI.getResourcePacks(null); int order = resourcePacks.size(); resourcePackOrder.clear(); for (IResourcePack resourcePack : resourcePacks) { resourcePackOrder.put(resourcePack, order); order--; } instance = new ResourceList(); } return instance; } public static void clearInstance() { instance = null; } public static int getResourcePackOrder(IResourcePack resourcePack) { Integer i = resourcePackOrder.get(resourcePack); return i == null ? Integer.MAX_VALUE : i; } private ResourceList() { this.resourcePack = null; for (IResourcePack resourcePack : TexturePackAPI.getResourcePacks(null)) { ResourceList sublist; if (resourcePack instanceof FileResourcePack) { sublist = new ResourceList((FileResourcePack) resourcePack); } else if (resourcePack instanceof DefaultResourcePack) { sublist = new ResourceList((DefaultResourcePack) resourcePack); } else if (resourcePack instanceof AbstractResourcePack) { sublist = new ResourceList((AbstractResourcePack) resourcePack); } else { continue; } allResources.removeAll(sublist.allResources); allResources.addAll(sublist.allResources); } logger.fine("new %s", this); if (logger.isLoggable(Level.FINEST)) { for (ResourceLocationWithSource resource : allResources) { logger.finest( "%s -> %s", resource, resource.getSource() .getPackName()); } } } private ResourceList(FileResourcePack resourcePack) { this.resourcePack = resourcePack; try { scanZipFile(resourcePack.getResourcePackZipFile()); } catch (IOException e) { logger.error(e.getMessage()); } logger.fine("new %s", this); } private ResourceList(DefaultResourcePack resourcePack) { this.resourcePack = resourcePack; String version = "1.7.10"; File jar = MCPatcherUtils.getMinecraftPath("versions", version, version + ".jar"); if (jar.isFile()) { ZipFile zipFile = null; try { zipFile = new ZipFile(jar); scanZipFile(zipFile); } catch (Exception e) { e.printStackTrace(); } finally { MCPatcherUtils.close(zipFile); } } @SuppressWarnings("unchecked") Map<String, File> map = resourcePack.field_152781_b; // map if (map != null) { for (Map.Entry<String, File> entry : map.entrySet()) { String key = entry.getKey(); File file = entry.getValue(); ResourceLocation resource = new ResourceLocation(key); addResource(resource, file.isFile(), file.isDirectory()); } } if (!allResources.isEmpty()) { logger.fine("new %s", this); } } private ResourceList(AbstractResourcePack resourcePack) { this.resourcePack = resourcePack; File directory = resourcePack.resourcePackFile; if (directory == null || !directory.isDirectory()) { return; } Set<String> allFiles = new HashSet<>(); listAllFiles(directory, "", allFiles); for (String path : allFiles) { ResourceLocation resource = TexturePackAPI.parsePath(path); if (resource != null) { File file = new File(directory, path); addResource(resource, file.isFile(), file.isDirectory()); } } logger.fine("new %s", this); } private void scanZipFile(ZipFile zipFile) { if (zipFile == null) { return; } for (ZipEntry entry : Collections.list(zipFile.entries())) { String path = entry.getName(); ResourceLocation resource = TexturePackAPI.parsePath(path); if (resource != null) { addResource(resource, !entry.isDirectory(), entry.isDirectory()); } } } private static void listAllFiles(File base, String subdir, Set<String> files) { File[] entries = new File(base, subdir).listFiles(); if (entries == null) { return; } for (File file : entries) { String newPath = subdir + file.getName(); if (files.add(newPath)) { if (file.isDirectory()) { listAllFiles(base, subdir + file.getName() + '/', files); } } } } private void addResource(ResourceLocation resource, boolean isFile, boolean isDirectory) { if (isFile) { allResources.add(new ResourceLocationWithSource(resourcePack, resource)); } else if (isDirectory) { if (!resource.getResourcePath() .endsWith("/")) { resource = new ResourceLocation(resource.getResourceDomain(), resource.getResourcePath() + '/'); } allResources.add(new ResourceLocationWithSource(resourcePack, resource)); } } public List<ResourceLocation> listResources(String directory, String suffix, boolean sortByFilename) { return listResources(directory, suffix, true, false, sortByFilename); } public List<ResourceLocation> listResources(String directory, String suffix, boolean recursive, boolean directories, boolean sortByFilename) { return listResources(null, directory, suffix, recursive, directories, sortByFilename); } public List<ResourceLocation> listResources(String namespace, String directory, String suffix, boolean recursive, boolean directories, final boolean sortByFilename) { if (suffix == null) { suffix = ""; } if (MCPatcherUtils.isNullOrEmpty(directory)) { directory = ""; } else if (!directory.endsWith("/")) { directory += '/'; } Set<ResourceLocationWithSource> tmpList = new TreeSet<>( new ResourceLocationWithSource.Comparator1(true, sortByFilename ? suffix : null)); boolean allNamespaces = MCPatcherUtils.isNullOrEmpty(namespace); for (ResourceLocationWithSource resource : allResources) { if (directories != resource.isDirectory()) { continue; } if (!allNamespaces && !namespace.equals(resource.getResourceDomain())) { continue; } String path = resource.getResourcePath(); if (!path.endsWith(suffix)) { continue; } if (!path.startsWith(directory)) { continue; } if (!recursive) { String subpath = path.substring(directory.length()); if (subpath.contains("/")) { continue; } } tmpList.add(resource); } return new ArrayList<>(tmpList); } @Override public String toString() { StringBuilder sb = new StringBuilder("ResourceList: "); if (resourcePack == null) { sb.append("(combined) "); } else { sb.append(resourcePack.getPackName()) .append(' '); } int fileCount = 0; int directoryCount = 0; Set<String> namespaces = new HashSet<>(); for (ResourceLocationWithSource resource : allResources) { if (resource.isDirectory()) { directoryCount++; } else { fileCount++; } namespaces.add(resource.getResourceDomain()); } sb.append(fileCount) .append(" files, "); sb.append(directoryCount) .append(" directories in "); sb.append(namespaces.size()) .append(" namespaces"); return sb.toString(); } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\resource\ResourceLocationWithSource.java
package com.prupe.mcpatcher.mal.resource; import java.util.Comparator; import java.util.regex.Pattern; import net.minecraft.client.resources.IResourcePack; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.MCPatcherUtils; public class ResourceLocationWithSource extends ResourceLocation { private final IResourcePack source; private final int order; private final boolean isDirectory; public ResourceLocationWithSource(IResourcePack source, ResourceLocation resource) { super( resource.getResourceDomain(), resource.getResourcePath() .replaceFirst("/$", "")); this.source = source; order = ResourceList.getResourcePackOrder(source); isDirectory = resource.getResourcePath() .endsWith("/"); } public IResourcePack getSource() { return source; } public int getOrder() { return order; } public boolean isDirectory() { return isDirectory; } static class Comparator1 implements Comparator<ResourceLocationWithSource> { private final boolean bySource; private final String suffixExpr; Comparator1() { this(false, null); } Comparator1(boolean bySource, String suffix) { this.bySource = bySource; this.suffixExpr = MCPatcherUtils.isNullOrEmpty(suffix) ? null : Pattern.quote(suffix) + "$"; } @Override public int compare(ResourceLocationWithSource o1, ResourceLocationWithSource o2) { int result; if (bySource) { result = o1.getOrder() - o2.getOrder(); if (result != 0) { return result; } } String n1 = o1.getResourceDomain(); String n2 = o2.getResourceDomain(); result = n1.compareTo(n2); if (result != 0) { return result; } String p1 = o1.getResourcePath(); String p2 = o2.getResourcePath(); if (suffixExpr != null) { String f1 = p1.replaceAll(".*/", "") .replaceFirst(suffixExpr, ""); String f2 = p2.replaceAll(".*/", "") .replaceFirst(suffixExpr, ""); result = f1.compareTo(f2); if (result != 0) { return result; } } return p1.compareTo(p2); } } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\resource\TexturePackAPI.java
package com.prupe.mcpatcher.mal.resource; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Pattern; import javax.imageio.ImageIO; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ThreadDownloadImageData; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.client.renderer.texture.DynamicTexture; import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.client.renderer.texture.SimpleTexture; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.resources.FallbackResourceManager; import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.resources.IResourcePack; import net.minecraft.client.resources.SimpleReloadableResourceManager; import net.minecraft.util.ResourceLocation; import org.apache.commons.io.IOUtils; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import jss.notfine.util.AbstractTextureExpansion; public class TexturePackAPI { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.TEXTURE_PACK); public static final String DEFAULT_NAMESPACE = "minecraft"; public static final String MCPATCHER_SUBDIR = "mcpatcher/"; public static final ResourceLocation ITEMS_PNG = new ResourceLocation("textures/atlas/items.png"); private static final String ASSETS = "assets/"; public static List<IResourcePack> getResourcePacks(String namespace) { List<IResourcePack> resourcePacks = new ArrayList<>(); IResourceManager resourceManager = Minecraft.getMinecraft().getResourceManager(); if (resourceManager instanceof SimpleReloadableResourceManager) { @SuppressWarnings("unchecked") Set<Map.Entry<String, FallbackResourceManager>> entrySet = ((SimpleReloadableResourceManager) resourceManager).domainResourceManagers .entrySet(); for (Map.Entry<String, FallbackResourceManager> entry : entrySet) { if (namespace == null || namespace.equals(entry.getKey())) { List<IResourcePack> packs = entry.getValue().resourcePacks; if (packs != null) { resourcePacks.removeAll(packs); resourcePacks.addAll(packs); } } } } return resourcePacks; } @SuppressWarnings("unchecked") public static Set<String> getNamespaces() { Set<String> namespaces = new HashSet<>(); namespaces.add(DEFAULT_NAMESPACE); IResourceManager resourceManager = Minecraft.getMinecraft().getResourceManager(); if (resourceManager instanceof SimpleReloadableResourceManager simpleReloadableResourceManager) { namespaces.addAll(simpleReloadableResourceManager.domainResourceManagers.keySet()); } return namespaces; } public static boolean isDefaultTexturePack() { return getResourcePacks(DEFAULT_NAMESPACE).size() <= 1; } public static InputStream getInputStream(ResourceLocation resource) { try { if (resource instanceof ResourceLocationWithSource resourceLocationWithSource) { try { return resourceLocationWithSource.getSource() .getInputStream(resource); } catch (IOException e) {} } return resource == null ? null : Minecraft.getMinecraft() .getResourceManager() .getResource(resource) .getInputStream(); } catch (IOException e) { return null; } } public static boolean hasResource(ResourceLocation resource) { if (resource == null) { return false; } else if (resource.getResourcePath() .endsWith(".png")) { return getImage(resource) != null; } else if (resource.getResourcePath() .endsWith(".properties")) { return getProperties(resource) != null; } else { InputStream is = getInputStream(resource); MCPatcherUtils.close(is); return is != null; } } public static boolean hasCustomResource(ResourceLocation resource) { InputStream jar = null; InputStream pack = null; try { pack = getInputStream(resource); jar = Minecraft.getMinecraft().mcDefaultResourcePack.getInputStream(resource); if (pack == null || jar == null) { return false; } return !Arrays.equals(IOUtils.toByteArray(jar), IOUtils.toByteArray(pack)); } catch (IOException e) { e.printStackTrace(); } finally { MCPatcherUtils.close(jar); MCPatcherUtils.close(pack); } return false; } public static BufferedImage getImage(ResourceLocation resource) { if (resource == null) { return null; } InputStream input = getInputStream(resource); BufferedImage image = null; if (input != null) { try { image = ImageIO.read(input); } catch (IOException e) { logger.error("could not read %s", resource); e.printStackTrace(); } finally { MCPatcherUtils.close(input); } } return image; } public static Properties getProperties(ResourceLocation resource) { Properties properties = new Properties(); if (getProperties(resource, properties)) { return properties; } else { return null; } } public static boolean getProperties(ResourceLocation resource, Properties properties) { if (properties != null) { InputStream input = getInputStream(resource); try { if (input != null) { properties.load(input); return true; } } catch (IOException e) { logger.error("could not read %s", resource); e.printStackTrace(); } finally { MCPatcherUtils.close(input); } } return false; } public static ResourceLocation transformResourceLocation(ResourceLocation resource, String oldExt, String newExt) { return new ResourceLocation( resource.getResourceDomain(), resource.getResourcePath() .replaceFirst(Pattern.quote(oldExt) + "$", newExt)); } public static ResourceLocation parsePath(String path) { if (MCPatcherUtils.isNullOrEmpty(path)) { return null; } path = path.replace(File.separatorChar, '/'); if (path.startsWith(ASSETS)) { path = path.substring(ASSETS.length()); int slash = path.indexOf('/'); if (slash > 0 && slash + 1 < path.length()) { return new ResourceLocation(path.substring(0, slash), path.substring(slash + 1)); } } return null; } public static ResourceLocation parseResourceLocation(ResourceLocation baseResource, String path) { if (MCPatcherUtils.isNullOrEmpty(path)) { return null; } boolean absolute = false; if (path.startsWith("%blur%")) { path = path.substring(6); } if (path.startsWith("%clamp%")) { path = path.substring(7); } if (path.startsWith("/")) { path = path.substring(1); absolute = true; } if (path.startsWith("assets/minecraft/")) { path = path.substring(17); absolute = true; } // Absolute path, including namespace: // namespace:path/filename -> assets/namespace/path/filename int colon = path.indexOf(':'); if (colon >= 0) { return new ResourceLocation(path.substring(0, colon), path.substring(colon + 1)); } ResourceLocation resource; if (path.startsWith("~/")) { // Relative to namespace mcpatcher dir: // ~/path -> assets/(namespace of base file)/mcpatcher/path resource = new ResourceLocation(baseResource.getResourceDomain(), MCPATCHER_SUBDIR + path.substring(2)); } else if (path.startsWith("./")) { // Relative to properties file: // ./path -> (dir of base file)/path resource = new ResourceLocation( baseResource.getResourceDomain(), baseResource.getResourcePath() .replaceFirst("[^/]+$", "") + path.substring(2)); } else if (!absolute && !path.contains("/")) { // Relative to properties file: // filename -> (dir of base file)/filename resource = new ResourceLocation( baseResource.getResourceDomain(), baseResource.getResourcePath() .replaceFirst("[^/]+$", "") + path); } else { // Absolute path, w/o namespace: // path/filename -> assets/(namespace of base file)/path/filename resource = new ResourceLocation(baseResource.getResourceDomain(), path); } if (baseResource instanceof ResourceLocationWithSource) { resource = new ResourceLocationWithSource( ((ResourceLocationWithSource) baseResource).getSource(), resource); } return resource; } public static ResourceLocation newMCPatcherResourceLocation(String path) { return new ResourceLocation(MCPATCHER_SUBDIR + path.replaceFirst("^/+", "")); } public static int getTextureIfLoaded(ResourceLocation resource) { if (resource == null) { return -1; } ITextureObject texture = Minecraft.getMinecraft() .getTextureManager() .getTexture(resource); return texture instanceof AbstractTexture ? texture.getGlTextureId() : -1; } public static boolean isTextureLoaded(ResourceLocation resource) { return getTextureIfLoaded(resource) >= 0; } public static ITextureObject getTextureObject(ResourceLocation resource) { return Minecraft.getMinecraft() .getTextureManager() .getTexture(resource); } public static void bindTexture(ResourceLocation resource) { if (resource != null) { Minecraft.getMinecraft() .getTextureManager() .bindTexture(resource); } } public static void unloadTexture(ResourceLocation resource) { if (resource != null) { TextureManager textureManager = Minecraft.getMinecraft() .getTextureManager(); ITextureObject texture = textureManager.getTexture(resource); if (texture != null && !(texture instanceof TextureMap) && !(texture instanceof DynamicTexture)) { if (texture instanceof AbstractTexture) { ((AbstractTextureExpansion) texture).unloadGLTexture(); } logger.finer("unloading texture %s", resource); textureManager.mapTextureObjects.remove(resource); } } } public static void flushUnusedTextures() { TextureManager textureManager = Minecraft.getMinecraft().getTextureManager(); if (textureManager != null) { @SuppressWarnings("unchecked") Map.Entry<ResourceLocation, ITextureObject>[] arr = (Map.Entry<ResourceLocation, ITextureObject>[]) textureManager.mapTextureObjects.entrySet().toArray(new Map.Entry[0]); for (Map.Entry<ResourceLocation, ITextureObject> entry : arr) { ITextureObject texture = entry.getValue(); if (texture instanceof SimpleTexture && !(texture instanceof ThreadDownloadImageData)) { ResourceLocation resource = entry.getKey(); if (!TexturePackAPI.hasResource(resource)) { unloadTexture(resource); } } } } } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\resource\TexturePackChangeHandler.java
package com.prupe.mcpatcher.mal.resource; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import net.minecraft.client.resources.IResourcePack; import com.prupe.mcpatcher.MCLogger; abstract public class TexturePackChangeHandler implements Comparable<TexturePackChangeHandler> { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.TEXTURE_PACK); private static final ArrayList<TexturePackChangeHandler> handlers = new ArrayList<>(); private static int recurseDepth; private static boolean initialized; private static long startTime; private static long startMem; private boolean updateNeeded; protected final String name; protected final int order; public TexturePackChangeHandler(String name, int order) { this.name = name; this.order = order; } public void initialize() { beforeChange(); afterChange(); } public void refresh() { beforeChange(); afterChange(); } abstract public void beforeChange(); abstract public void afterChange(); public void afterChange2() {} @Override public int compareTo(TexturePackChangeHandler that) { return this.order - that.order; } public static void register(TexturePackChangeHandler handler) { if (handler != null) { try { logger.info("initializing %s...", handler.name); handler.initialize(); } catch (Exception e) { e.printStackTrace(); logger.severe("%s initialization failed", handler.name); } handlers.add(handler); logger.fine("registered texture pack handler %s, priority %d", handler.name, handler.order); Collections.sort(handlers); } } public static void checkForTexturePackChange() { for (TexturePackChangeHandler handler : handlers) { if (handler.updateNeeded) { handler.updateNeeded = false; try { logger.info("refreshing %s...", handler.name); handler.refresh(); } catch (Exception e) { e.printStackTrace(); logger.severe("%s refresh failed", handler.name); } } } } public static void beforeChange1() { logger.finer("beforeChange1 depth %d", recurseDepth); if (recurseDepth++ > 0) { return; } startTime = System.currentTimeMillis(); Runtime runtime = Runtime.getRuntime(); startMem = runtime.totalMemory() - runtime.freeMemory(); ResourceList.clearInstance(); List<IResourcePack> resourcePacks = TexturePackAPI.getResourcePacks(null); logger .fine("%s resource packs (%d selected):", initialized ? "changing" : "initializing", resourcePacks.size()); for (IResourcePack pack : resourcePacks) { logger.fine("resource pack: %s", pack.getPackName()); } Set<String> namespaces = TexturePackAPI.getNamespaces(); logger.fine("%d resource namespaces:", namespaces.size()); for (String namespace : namespaces) { logger.fine("namespace: %s", namespace); } for (TexturePackChangeHandler handler : handlers) { try { logger.info("refreshing %s (pre)...", handler.name); handler.beforeChange(); } catch (Exception e) { e.printStackTrace(); logger.severe("%s.beforeChange failed", handler.name); } } TexturePackAPI.flushUnusedTextures(); } public static void afterChange1() { logger.finer("afterChange1 depth %d", recurseDepth - 1); if (--recurseDepth > 0) { return; } for (TexturePackChangeHandler handler : handlers) { try { logger.info("refreshing %s (post)...", handler.name); handler.afterChange(); } catch (Exception e) { e.printStackTrace(); logger.severe("%s.afterChange failed", handler.name); } } for (int i = handlers.size() - 1; i >= 0; i--) { TexturePackChangeHandler handler = handlers.get(i); try { handler.afterChange2(); } catch (Exception e) { e.printStackTrace(); logger.severe("%s.afterChange2 failed", handler.name); } } long timeDiff = System.currentTimeMillis() - startTime; Runtime runtime = Runtime.getRuntime(); long memDiff = runtime.totalMemory() - runtime.freeMemory() - startMem; logger.info("done (%.3fs elapsed, mem usage %+.1fMB)\n", timeDiff / 1000.0, memDiff / 1048576.0); initialized = true; recurseDepth = 0; } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\tile\TileLoader.java
package com.prupe.mcpatcher.mal.tile; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import com.prupe.mcpatcher.MCLogger; import com.prupe.mcpatcher.MCPatcherUtils; import com.prupe.mcpatcher.mal.resource.BlendMethod; import com.prupe.mcpatcher.mal.resource.TexturePackAPI; import com.prupe.mcpatcher.mal.resource.TexturePackChangeHandler; import jss.notfine.config.MCPatcherForgeConfig; public class TileLoader { private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.TILESHEET); private static final List<TileLoader> loaders = new ArrayList<>(); private static final Map<String, String> specialTextures = new HashMap<>(); private static final TexturePackChangeHandler changeHandler; private static boolean changeHandlerCalled; private static final long MAX_TILESHEET_SIZE; protected final String mapName; protected final MCLogger subLogger; private TextureMap baseTextureMap; private final Map<String, TextureAtlasSprite> baseTexturesByName = new HashMap<>(); private final Set<ResourceLocation> tilesToRegister = new HashSet<>(); private final Map<ResourceLocation, BufferedImage> tileImages = new HashMap<>(); private final Map<String, IIcon> iconMap = new HashMap<>(); static { long maxSize = 4096L; maxSize = Minecraft.getGLMaximumTextureSize(); MAX_TILESHEET_SIZE = (maxSize * maxSize * 4) * 7 / 8; logger.config("max texture size is %dx%d (%.1fMB)", maxSize, maxSize, MAX_TILESHEET_SIZE / 1048576.0f); changeHandler = new TexturePackChangeHandler("Tilesheet API", 2) { @Override public void initialize() {} @Override public void beforeChange() { changeHandlerCalled = true; loaders.clear(); specialTextures.clear(); } @Override public void afterChange() { for (TileLoader loader : loaders) { if (!loader.tilesToRegister.isEmpty()) { loader.subLogger.warning( "could not load all %s tiles (%d remaining)", loader.mapName, loader.tilesToRegister.size()); loader.tilesToRegister.clear(); } } changeHandlerCalled = false; } @Override public void afterChange2() { for (TileLoader loader : loaders) { loader.finish(); } } }; TexturePackChangeHandler.register(changeHandler); } public static void registerIcons(TextureMap textureMap, String mapName, Map<String, TextureAtlasSprite> map) { mapName = mapName.replaceFirst("/$", ""); logger.fine("before registerIcons(%s) %d icons", mapName, map.size()); if (!changeHandlerCalled) { logger.severe("beforeChange was not called, invoking directly"); changeHandler.beforeChange(); } for (TileLoader loader : loaders) { if (loader.isForThisMap(mapName)) { if (loader.baseTextureMap == null) { loader.baseTextureMap = textureMap; loader.baseTexturesByName.putAll(map); } if (!loader.tilesToRegister.isEmpty()) { loader.subLogger .fine("adding icons to %s (%d remaining)", mapName, loader.tilesToRegister.size(), mapName); while (!loader.tilesToRegister.isEmpty() && loader.registerOneIcon(textureMap, mapName, map)) { // nothing } loader.subLogger.fine( "done adding icons to %s (%d remaining)", mapName, loader.tilesToRegister.size(), mapName); } } } logger.fine("after registerIcons(%s) %d icons", mapName, map.size()); } public static String getOverridePath(String prefix, String basePath, String name, String ext) { String path; if (name.endsWith(".png")) { path = name.replaceFirst("^/", "") .replaceFirst("\\.[^.]+$", "") + ext; } else { path = basePath; if (!basePath.endsWith("/")) { path += "/"; } path += name; path += ext; } path = prefix + path; logger.finer("getOverridePath(%s, %s, %s, %s) -> %s", prefix, basePath, name, ext, path); return path; } public static boolean isSpecialTexture(TextureMap map, String texture, String special) { return special.equals(texture) || special.equals(specialTextures.get(texture)); } public static BufferedImage generateDebugTexture(String text, int width, int height, boolean alternate) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics graphics = image.getGraphics(); graphics.setColor(alternate ? new Color(0, 255, 255, 128) : Color.WHITE); graphics.fillRect(0, 0, width, height); graphics.setColor(alternate ? Color.RED : Color.BLACK); int ypos = 10; if (alternate) { ypos += height / 2; } int charsPerRow = width / 8; if (charsPerRow <= 0) { return image; } StringBuilder textBuilder = new StringBuilder(text); while (textBuilder.length() % charsPerRow != 0) { textBuilder.append(" "); } text = textBuilder.toString(); while (ypos < height && !text.isEmpty()) { graphics.drawString(text.substring(0, charsPerRow), 1, ypos); ypos += graphics.getFont() .getSize(); text = text.substring(charsPerRow); } return image; } public static void init() {} public TileLoader(String mapName, MCLogger logger) { this.mapName = mapName; subLogger = logger; loaders.add(this); } private static long getTextureSize(TextureAtlasSprite texture) { return texture == null ? 0 : 4 * texture.getIconWidth() * texture.getIconHeight(); } private static long getTextureSize(Collection<TextureAtlasSprite> textures) { long size = 0; for (TextureAtlasSprite texture : textures) { size += getTextureSize(texture); } return size; } public static ResourceLocation getDefaultAddress(ResourceLocation propertiesAddress) { return TexturePackAPI.transformResourceLocation(propertiesAddress, ".properties", ".png"); } public static ResourceLocation parseTileAddress(ResourceLocation propertiesAddress, String value) { return parseTileAddress(propertiesAddress, value, BlendMethod.ALPHA.getBlankResource()); } public static ResourceLocation parseTileAddress(ResourceLocation propertiesAddress, String value, ResourceLocation blankResource) { if (value == null) { return null; } if (value.equals("blank")) { return blankResource; } if (value.equals("null") || value.equals("none") || value.equals("default") || value.isEmpty()) { return null; } if (!value.endsWith(".png")) { value += ".png"; } return TexturePackAPI.parseResourceLocation(propertiesAddress, value); } public boolean preloadTile(ResourceLocation resource, boolean alternate, String special) { if (tileImages.containsKey(resource)) { return true; } BufferedImage image = null; if (!MCPatcherForgeConfig.ConnectedTextures.debugTextures) { image = TexturePackAPI.getImage(resource); if (image == null) { subLogger.warning("missing %s", resource); } } if (image == null) { image = generateDebugTexture(resource.getResourcePath(), 64, 64, alternate); } tilesToRegister.add(resource); tileImages.put(resource, image); if (special != null) { specialTextures.put(resource.toString(), special); } return true; } public boolean preloadTile(ResourceLocation resource, boolean alternate) { return preloadTile(resource, alternate, null); } protected boolean isForThisMap(String mapName) { return mapName.equals("textures") || mapName.startsWith(this.mapName); } private boolean registerDefaultIcon(String name) { if (name.startsWith(mapName) && name.endsWith(".png") && baseTextureMap != null) { String defaultName = name.substring(mapName.length()) .replaceFirst("\\.png$", ""); TextureAtlasSprite texture = baseTexturesByName.get(defaultName); if (texture != null) { subLogger.finer("%s -> existing icon %s", name, defaultName); iconMap.put(name, texture); return true; } } return false; } private boolean registerOneIcon(TextureMap textureMap, String mapName, Map<String, TextureAtlasSprite> map) { ResourceLocation resource = tilesToRegister.iterator() .next(); String name = resource.toString(); if (registerDefaultIcon(name)) { tilesToRegister.remove(resource); return true; } BufferedImage image = tileImages.get(resource); if (image == null) { subLogger.error("tile for %s unexpectedly missing", resource); tilesToRegister.remove(resource); return true; } int width = image.getWidth(); int height = image.getHeight(); long currentSize = getTextureSize(map.values()); long newSize = 4 * width * width; if (newSize + currentSize > MAX_TILESHEET_SIZE) { float sizeMB = (float) currentSize / 1048576.0f; if (currentSize <= 0) { subLogger.error("%s too big for any tilesheet (%.1fMB), dropping", name, sizeMB); tilesToRegister.remove(resource); return true; } else { subLogger.warning("%s nearly full (%.1fMB), will start a new tilesheet", mapName, sizeMB); return false; } } IIcon icon = textureMap.registerIcon(name); map.put(name, (TextureAtlasSprite) icon); iconMap.put(name, icon); String extra = (width == height ? "" : ", " + (height / width) + " frames"); subLogger.finer("%s -> %s icon %dx%d%s", name, mapName, width, width, extra); tilesToRegister.remove(resource); return true; } public void finish() { tilesToRegister.clear(); tileImages.clear(); } public IIcon getIcon(String name) { if (MCPatcherUtils.isNullOrEmpty(name)) { return null; } IIcon icon = iconMap.get(name); if (icon == null) { icon = baseTexturesByName.get(name); } return icon; } public IIcon getIcon(ResourceLocation resource) { return resource == null ? null : getIcon(resource.toString()); } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\util\InputHandler.java
package com.prupe.mcpatcher.mal.util; import java.util.BitSet; import org.lwjgl.input.Keyboard; public class InputHandler { private final BitSet keysDown = new BitSet(); private final String name; private final boolean enabled; public InputHandler(String name, boolean enabled) { this.name = name; this.enabled = enabled; } public String getName() { return name; } public boolean isEnabled() { return enabled; } public boolean isKeyPressed(int key) { if (!enabled) { // nothing } else if (Keyboard.isKeyDown(key)) { if (!keysDown.get(key)) { keysDown.set(key); return true; } } else { keysDown.clear(key); } return false; } public boolean isKeyDown(int key) { return enabled && Keyboard.isKeyDown(key); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("InputUtils{") .append(name) .append(':'); for (int i = keysDown.nextSetBit(0); i >= 0; i = keysDown.nextSetBit(i + 1)) { sb.append(' ') .append(Keyboard.getKeyName(i)); } sb.append('}'); return sb.toString(); } }
Angelica
src\main\java\com\prupe\mcpatcher\mal\util\WeightedIndex.java
package com.prupe.mcpatcher.mal.util; abstract public class WeightedIndex { private static final long K1 = 0xb492b66fbe98f273L; private static final long KMUL = 0x9ddfea08eb382d69L; final int size; public static WeightedIndex create(int size) { if (size <= 0) { return null; } return new WeightedIndex(size) { @Override public int choose(long key) { return mod(key, size); } @Override public String toString() { return "unweighted"; } }; } public static WeightedIndex create(int size, final String weightList) { if (size <= 0 || weightList == null) { return create(size); } final int[] weights = new int[size]; int sum1 = 0; boolean useWeight = false; String[] list = weightList.trim() .split("\\s+"); for (int i = 0; i < size; i++) { if (i < list.length && list[i].matches("^\\d+$")) { weights[i] = Math.max(Integer.parseInt(list[i]), 0); } else { weights[i] = 1; } if (i > 0 && weights[i] != weights[0]) { useWeight = true; } sum1 += weights[i]; } if (!useWeight || sum1 <= 0) { return create(size); } final int sum = sum1; return new WeightedIndex(size) { @Override public int choose(long key) { int index; int m = mod(key, sum); for (index = 0; index < size - 1 && m >= weights[index]; index++) { m -= weights[index]; } return index; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("%("); for (int i = 0; i < weights.length; i++) { if (i > 0) { sb.append(", "); } sb.append(String.format("%.1f", 100.0 * weights[i] / sum)); } sb.append(")"); return sb.toString(); } }; } protected WeightedIndex(int size) { this.size = size; } protected final int mod(long n, int modulus) { return (int) (((n >> 32) ^ n) & 0x7fffffff) % modulus; } abstract public int choose(long key); // adapted from CityHash http://code.google.com/p/cityhash/source/browse/trunk/ (MIT license) public static long hash128To64(int i, int j, int k, int l) { return hash128To64(((long) i << 32) | ((long) j & 0xffffffffL), ((long) k << 32) | ((long) l & 0xffffffffL)); } public static long hash128To64(long a, long b) { a = shiftMix(a * K1) * K1; long c = b * K1 + mix128to64(a, b); long d = shiftMix(a + b); a = mix128to64(a, c); b = mix128to64(d, b); return a ^ b ^ mix128to64(b, a); } private static long shiftMix(long val) { return val ^ (val >>> 47); } private static long mix128to64(long u, long v) { long a = shiftMix((u ^ v) * KMUL); long b = shiftMix((u ^ a) * KMUL); b *= KMUL; return b; } }
Angelica
src\main\java\de\odysseus\ithaka\digraph\Digraph.java
/* * Copyright 2012 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.ithaka.digraph; import java.util.Collection; import java.util.OptionalInt; import java.util.Set; /** * Directed graph interface. * * @param <V> vertex type */ public interface Digraph<V> extends EdgeWeights<V> { /** * Get an edge. * * @param source source vertex * @param target target vertex * @return edge weight (<code>0</code> if there is no edge from <code>source</code> to <code>target</code>) */ OptionalInt get(V source, V target); /** * Edge test. * * @param source source vertex * @param target target vertex * @return <code>true</code> iff this de.odysseus.ithaka.digraph contains an edge from <code>source</code> to <code>target</code> */ boolean contains(V source, V target); /** * Vertex test * * @return <code>true</code> iff this de.odysseus.ithaka.digraph contains <code>vertex</code> */ boolean contains(V vertex); /** * Add vertex. * * @return <code>true</code> iff <code>vertex</code> has been added */ boolean add(V vertex); /** * Put an edge. * Vertices are added automatically if they appear in an edge. * * @param source source vertex * @param target target vertex * @param weight edge weight * @return edge weight that has been previously set (<code>0</code> if there was no edge from <code>source</code> * to <code>target</code>) */ OptionalInt put(V source, V target, int weight); /** * Remove an edge. * * @param source source vertex * @param target target vertex * @return edge weight that has been previously set (<code>0</code> if there was no edge from <code>source</code> * to <code>target</code>) */ OptionalInt remove(V source, V target); /** * Remove a vertex. * * @param vertex vertex * @return <code>true</code> iff this de.odysseus.ithaka.digraph contained <code>vertex</code> */ boolean remove(V vertex); /** * Remove all vertices. * * @param vertices vertices */ void removeAll(Collection<V> vertices); /** * Iterate over vertices. * * @return vertices */ Iterable<V> vertices(); /** * Iterate over edge targets for given source vertex. * * @param source source vertex * @return edge targets of edges starting at <code>source</code> */ Iterable<V> targets(V source); /** * @return number of vertices in this de.odysseus.ithaka.digraph */ int getVertexCount(); /** * @return sum of edge weights */ int totalWeight(); /** * @return number of edges starting at <code>vertex</code> */ int getOutDegree(V vertex); /** * @return number of edges in this de.odysseus.ithaka.digraph */ int getEdgeCount(); /** * @return <code>true</code> iff this de.odysseus.ithaka.digraph is acyclic (i.e. it is a DAG) */ boolean isAcyclic(); /** * Get reverse de.odysseus.ithaka.digraph (same vertices, with edges reversed). * * @return reverse de.odysseus.ithaka.digraph */ Digraph<V> reverse(); /** * Get induced subgraph (with vertices in this de.odysseus.ithaka.digraph and the given vertex set and edges that appear in this de.odysseus.ithaka.digraph over the given vertex set). * * @return subgraph */ Digraph<V> subgraph(Set<V> vertices); }