repo_id
stringclasses
383 values
file_path
stringlengths
7
168
content
stringlengths
0
1.75M
amidst
src\main\java\amidst\mojangapi\minecraftinterface\legacy\LegacyClassTranslator.java
package amidst.mojangapi.minecraftinterface.legacy; import static amidst.mojangapi.minecraftinterface.legacy.LegacySymbolicNames.*; import amidst.clazz.real.AccessFlags; import amidst.clazz.real.RealClass; import amidst.clazz.translator.ClassTranslator; import amidst.documentation.Immutable; @Immutable public enum LegacyClassTranslator { INSTANCE; private static final int WILDCARD = RealClass.CLASS_DATA_WILDCARD; private final ClassTranslator classTranslator = createClassTranslator(); public static ClassTranslator get() { return INSTANCE.classTranslator; } // @formatter:off private ClassTranslator createClassTranslator() { return ClassTranslator .builder() .ifDetect(c -> c.isClassDataWildcardMatching(createIntCacheWildcardBytes()) || c.searchForStringContaining(", tcache: ") ) .thenDeclareRequired(CLASS_INT_CACHE) .requiredMethod(METHOD_INT_CACHE_RESET_INT_CACHE, "a").end() .next() .ifDetect(c -> c.searchForStringContaining("default_1_1")) .thenDeclareOptional(CLASS_WORLD_TYPE) .requiredField(FIELD_WORLD_TYPE_DEFAULT, "b") .requiredField(FIELD_WORLD_TYPE_FLAT, "c") .requiredField(FIELD_WORLD_TYPE_LARGE_BIOMES, "d") .requiredField(FIELD_WORLD_TYPE_AMPLIFIED, "e") .requiredField(FIELD_WORLD_TYPE_CUSTOMIZED, "f") .next() .ifDetect(c -> c.searchForLong(1000L) && c.searchForLong(2001L) && c.searchForLong(2000L) ) .thenDeclareRequired(LegacySymbolicNames.CLASS_GEN_LAYER) // one if the initializeAllBiomeGenerators-methods is required! .optionalMethod(METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_1, "a").real("long").end() .optionalMethod(METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_2, "a").real("long").symbolic(CLASS_WORLD_TYPE).end() .optionalMethod(METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_3, "a").real("long").symbolic(CLASS_WORLD_TYPE).real("String").end() .optionalMethod(METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_4, "a").real("long").symbolic(CLASS_WORLD_TYPE).symbolic(CLASS_GEN_OPTIONS).end() .requiredMethod(METHOD_GEN_LAYER_GET_INTS, "a").real("int") .real("int") .real("int") .real("int").end() .next() .ifDetect(c -> c.getNumberOfConstructors() == 0 && c.getNumberOfMethods() == 6 && c.getNumberOfFields() >= 3 && c.getNumberOfFields() <= 4 && c.getField(0).hasFlags(AccessFlags.STATIC) && c.getField(1).hasFlags(AccessFlags.PRIVATE | AccessFlags.STATIC) && c.searchForUtf8EqualTo("isDebugEnabled") ) .thenDeclareOptional(CLASS_BLOCK_INIT) .requiredMethod(METHOD_BLOCK_INIT_INITIALIZE, "c").end() .next() .ifDetect(c -> // some leeway in case Mojang adds or removes fields in the future c.getNumberOfFields() > 70 && c.getNumberOfFields() < 100 && c.getNumberOfMethods() == 0 ) .thenDeclareOptional(CLASS_GEN_OPTIONS) .next() .ifDetect(c -> // some leeway in case Mojang adds or removes fields in the future c.getNumberOfFields() > 70 && c.getNumberOfFields() < 100 && c.getField(0).hasFlags(AccessFlags.STATIC | AccessFlags.FINAL) && c.getField(1).hasFlags(AccessFlags.PUBLIC) && (!c.getField(1).hasFlags(AccessFlags.STATIC)) ) .thenDeclareOptional(CLASS_GEN_OPTIONS_FACTORY) .requiredMethod(METHOD_GEN_OPTIONS_FACTORY_BUILD, "b").end() .requiredMethod(METHOD_GEN_OPTIONS_FACTORY_JSON_TO_FACTORY, "a").real("java.lang.String").end() .construct(); } private int[] createIntCacheWildcardBytes() { return new int[] { 0x11, 0x01, 0x00, 0xB3, 0x00, WILDCARD, 0xBB, 0x00, WILDCARD, 0x59, 0xB7, 0x00, WILDCARD, 0xB3, 0x00, WILDCARD, 0xBB, 0x00, WILDCARD, 0x59, 0xB7, 0x00, WILDCARD, 0xB3, 0x00, WILDCARD, 0xBB, 0x00, WILDCARD, 0x59, 0xB7, 0x00, WILDCARD, 0xB3, 0x00, WILDCARD, 0xBB, 0x00, WILDCARD, 0x59, 0xB7, 0x00, WILDCARD, 0xB3, 0x00, WILDCARD, 0xB1 }; } // @formatter:on }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\legacy\LegacyMinecraftInterface.java
package amidst.mojangapi.minecraftinterface.legacy; import java.lang.invoke.MethodHandle; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.function.Function; import amidst.clazz.symbolic.SymbolicClass; import amidst.clazz.symbolic.SymbolicObject; import amidst.documentation.ThreadSafe; import amidst.mojangapi.minecraftinterface.MinecraftInterface; import amidst.mojangapi.minecraftinterface.MinecraftInterfaceException; import amidst.mojangapi.minecraftinterface.RecognisedVersion; import amidst.mojangapi.minecraftinterface.ReflectionUtils; import amidst.mojangapi.minecraftinterface.UnsupportedDimensionException; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.WorldOptions; import amidst.mojangapi.world.WorldType; @ThreadSafe /** * This is the MinecraftInterface used for versions older than 18w06a, before the 1.13 refactoring */ public class LegacyMinecraftInterface implements MinecraftInterface { public static final RecognisedVersion LAST_COMPATIBLE_VERSION = RecognisedVersion._18w05a; private final SymbolicClass intCacheClass; private final SymbolicClass blockInitClass; private final SymbolicClass genLayerClass; private final SymbolicClass worldTypeClass; private final SymbolicClass genOptionsFactoryClass; private final RecognisedVersion recognisedVersion; private boolean isInitialized = false; private MethodHandle resetIntCacheMethod; private MethodHandle getIntsMethod; LegacyMinecraftInterface( SymbolicClass intCacheClass, SymbolicClass blockInitClass, SymbolicClass genLayerClass, SymbolicClass worldTypeClass, SymbolicClass genOptionsFactoryClass, RecognisedVersion recognisedVersion) { this.intCacheClass = intCacheClass; this.blockInitClass = blockInitClass; this.genLayerClass = genLayerClass; this.worldTypeClass = worldTypeClass; this.genOptionsFactoryClass = genOptionsFactoryClass; this.recognisedVersion = recognisedVersion; } public LegacyMinecraftInterface(Map<String, SymbolicClass> symbolicClassMap, RecognisedVersion recognisedVersion) { this( symbolicClassMap.get(LegacySymbolicNames.CLASS_INT_CACHE), symbolicClassMap.get(LegacySymbolicNames.CLASS_BLOCK_INIT), symbolicClassMap.get(LegacySymbolicNames.CLASS_GEN_LAYER), symbolicClassMap.get(LegacySymbolicNames.CLASS_WORLD_TYPE), symbolicClassMap.get(LegacySymbolicNames.CLASS_GEN_OPTIONS_FACTORY), recognisedVersion); } @Override public synchronized WorldAccessor createWorldAccessor(WorldOptions worldOptions) throws MinecraftInterfaceException { initializeIfNeeded(); try { Object[] genLayers = getGenLayers(worldOptions.getWorldSeed().getLong(), worldOptions.getWorldType(), worldOptions.getGeneratorOptions()); return new WorldAccessor(genLayers[0], genLayers[1]); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new MinecraftInterfaceException("unable to create world", e); } } // Only one thread can manipulate the Minecraft int cache at a time private synchronized<T> T getBiomeData(int x, int y, int width, int height, Object biomeGenerator, Function<int[], T> biomeDataMapper) throws MinecraftInterfaceException { try { resetIntCacheMethod.invokeExact(); int[] biomeInts = (int[]) getIntsMethod.invokeExact(biomeGenerator, x, y, width, height); // we have to map the array inside the synchronized method so we don't // using a reference to an array that's still in the IntCache return biomeDataMapper.apply(biomeInts); } catch (Throwable e) { throw new MinecraftInterfaceException("unable to get biome data", e); } } private synchronized void initializeIfNeeded() throws MinecraftInterfaceException { if (isInitialized) { return; } try { // Minecraft 1.8 and higher require block initialization to be called before // creating a biome generator. if (blockInitClass != null) { blockInitClass.callStaticMethod(LegacySymbolicNames.METHOD_BLOCK_INIT_INITIALIZE); } resetIntCacheMethod = ReflectionUtils.getMethodHandle(intCacheClass, LegacySymbolicNames.METHOD_INT_CACHE_RESET_INT_CACHE); getIntsMethod = ReflectionUtils.getMethodHandle(genLayerClass, LegacySymbolicNames.METHOD_GEN_LAYER_GET_INTS); } catch(IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { throw new MinecraftInterfaceException("unable to initialize the MinecraftInterface", e); } isInitialized = true; } private Object[] getGenLayers(long seed, WorldType worldType, String generatorOptions) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (worldTypeClass == null) { return (Object[]) genLayerClass .callStaticMethod(LegacySymbolicNames.METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_1, seed); } else if (genLayerClass.hasMethod(LegacySymbolicNames.METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_4)) { return (Object[]) genLayerClass.callStaticMethod( LegacySymbolicNames.METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_4, seed, getWorldType(worldType).getObject(), getGeneratorOptions(generatorOptions).getObject()); } else if (genLayerClass.hasMethod(LegacySymbolicNames.METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_3)) { return (Object[]) genLayerClass.callStaticMethod( LegacySymbolicNames.METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_3, seed, getWorldType(worldType).getObject(), generatorOptions); } else { return (Object[]) genLayerClass.callStaticMethod( LegacySymbolicNames.METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_2, seed, getWorldType(worldType).getObject()); } } private SymbolicObject getGeneratorOptions(String generatorOptions) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { SymbolicObject factory = (SymbolicObject) genOptionsFactoryClass .callStaticMethod(LegacySymbolicNames.METHOD_GEN_OPTIONS_FACTORY_JSON_TO_FACTORY, generatorOptions); return (SymbolicObject) factory.callMethod(LegacySymbolicNames.METHOD_GEN_OPTIONS_FACTORY_BUILD); } private SymbolicObject getWorldType(WorldType worldType) throws IllegalArgumentException, IllegalAccessException { return (SymbolicObject) worldTypeClass.getStaticFieldValue(worldType.getSymbolicFieldName()); } @Override public RecognisedVersion getRecognisedVersion() { return recognisedVersion; } private class WorldAccessor implements MinecraftInterface.WorldAccessor { private final Object quarterResolutionBiomeGenerator; private final Object fullResolutionBiomeGenerator; private WorldAccessor(Object quarterResolutionGen, Object fullResolutionGen) { this.quarterResolutionBiomeGenerator = quarterResolutionGen; this.fullResolutionBiomeGenerator = fullResolutionGen; } @Override public<T> T getBiomeData(Dimension dimension, int x, int y, int width, int height, boolean useQuarterResolution, Function<int[], T> biomeDataMapper) throws MinecraftInterfaceException { if (dimension != Dimension.OVERWORLD) throw new UnsupportedDimensionException(dimension); Object biomeGenerator = useQuarterResolution ? quarterResolutionBiomeGenerator : fullResolutionBiomeGenerator; return LegacyMinecraftInterface.this.getBiomeData(x, y, width, height, biomeGenerator, biomeDataMapper); } @Override public Set<Dimension> supportedDimensions() { return Collections.singleton(Dimension.OVERWORLD); } } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\legacy\LegacySymbolicNames.java
package amidst.mojangapi.minecraftinterface.legacy; import amidst.documentation.Immutable; @Immutable public enum LegacySymbolicNames { ; public static final String CLASS_INT_CACHE = "IntCache"; public static final String METHOD_INT_CACHE_RESET_INT_CACHE = "resetIntCache"; public static final String CLASS_WORLD_TYPE = _1_15SymbolicNames.CLASS_WORLD_TYPE; public static final String FIELD_WORLD_TYPE_DEFAULT = _1_15SymbolicNames.FIELD_WORLD_TYPE_DEFAULT; public static final String FIELD_WORLD_TYPE_FLAT = _1_15SymbolicNames.FIELD_WORLD_TYPE_FLAT; public static final String FIELD_WORLD_TYPE_LARGE_BIOMES = _1_15SymbolicNames.FIELD_WORLD_TYPE_LARGE_BIOMES; public static final String FIELD_WORLD_TYPE_AMPLIFIED = _1_15SymbolicNames.FIELD_WORLD_TYPE_AMPLIFIED; public static final String FIELD_WORLD_TYPE_CUSTOMIZED = _1_15SymbolicNames.FIELD_WORLD_TYPE_CUSTOMIZED; public static final String CLASS_GEN_LAYER = "GenLayer"; public static final String METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_1 = "initializeAllBiomeGenerators1"; public static final String METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_2 = "initializeAllBiomeGenerators2"; public static final String METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_3 = "initializeAllBiomeGenerators3"; public static final String METHOD_GEN_LAYER_INITIALIZE_ALL_BIOME_GENERATORS_4 = "initializeAllBiomeGenerators4"; public static final String METHOD_GEN_LAYER_GET_INTS = "getInts"; public static final String CLASS_BLOCK_INIT = "BlockInit"; public static final String METHOD_BLOCK_INIT_INITIALIZE = "initialize"; public static final String CLASS_GEN_OPTIONS = "ChunkProviderSettings"; public static final String CLASS_GEN_OPTIONS_FACTORY = "ChunkProviderSettingsFactory"; public static final String METHOD_GEN_OPTIONS_FACTORY_JSON_TO_FACTORY = "jsonToFactory"; public static final String METHOD_GEN_OPTIONS_FACTORY_BUILD = "build"; }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\legacy\_1_13ClassTranslator.java
package amidst.mojangapi.minecraftinterface.legacy; import static amidst.mojangapi.minecraftinterface.legacy._1_13SymbolicNames.*; import amidst.clazz.real.AccessFlags; import amidst.clazz.translator.ClassTranslator; public enum _1_13ClassTranslator { INSTANCE; private final ClassTranslator classTranslator = createClassTranslator(); public static ClassTranslator get() { return INSTANCE.classTranslator; } // @formatter:off private ClassTranslator createClassTranslator() { return ClassTranslator .builder() .ifDetect(c -> c.searchForStringContaining("default_1_1")) .thenDeclareRequired(CLASS_WORLD_TYPE) .requiredField(FIELD_WORLD_TYPE_DEFAULT, "b") .requiredField(FIELD_WORLD_TYPE_FLAT, "c") .requiredField(FIELD_WORLD_TYPE_LARGE_BIOMES, "d") .requiredField(FIELD_WORLD_TYPE_AMPLIFIED, "e") .requiredField(FIELD_WORLD_TYPE_CUSTOMIZED, "f") .next() .ifDetect(c -> c.getNumberOfConstructors() == 0 && c.getNumberOfMethods() >= 6 && c.getNumberOfMethods() <= 11 && c.getNumberOfFields() >= 3 && c.getNumberOfFields() <= 4 && c.getField(0).hasFlags(AccessFlags.STATIC) && c.getField(1).hasFlags(AccessFlags.PRIVATE | AccessFlags.STATIC) && c.searchForUtf8EqualTo("isDebugEnabled") ) .thenDeclareRequired(CLASS_BOOTSTRAP) .optionalMethod(METHOD_BOOTSTRAP_REGISTER, "c").end() .optionalMethod(METHOD_BOOTSTRAP_REGISTER2, "b").end() // the name changed in 18w43c .optionalMethod(METHOD_BOOTSTRAP_REGISTER3, "a").end() // the name changed again in 19w07a .next() .ifDetect(c -> c.searchForLong(1000L) && c.searchForLong(2001L) && c.searchForLong(2000L) ) .thenDeclareRequired(CLASS_LAYER_UTIL) .requiredMethod(METHOD_LAYER_UTIL_INITIALIZE_ALL, "a").real("long").symbolic(CLASS_WORLD_TYPE).symbolic(CLASS_GEN_SETTINGS).end() .next() .ifDetect(c -> ( // before 18w46a c.getNumberOfConstructors() == 1 && c.getNumberOfFields() >= 15 && c.getNumberOfMethods() >= 19 && c.searchForFloat(684.412F) ) || ( // from 18w46a !c.getRealClassName().contains("$") && !c.getRealSuperClassName().equals("java/lang/Object") && c.getNumberOfFields() >= 4 && c.getNumberOfMethods() == c.getNumberOfFields() && c.getNumberOfConstructors() >= 1 && c.getField(0).hasFlags(AccessFlags.FINAL | AccessFlags.PRIVATE) && !c.getField(0).hasFlags(AccessFlags.STATIC) && c.getField(2).hasFlags(AccessFlags.FINAL | AccessFlags.PRIVATE) && !c.searchForStringContaining("textures") && c.hasMethodWithRealArgsReturning(new String[]{ null }) && !c.hasMethodWithRealArgsReturning(null, null) && !c.hasMethodWithRealArgsReturning(null, null, null) && !c.hasMethodWithRealArgsReturning(null, null, null, null) && !c.hasMethodWithRealArgsReturning(null, null, null, null, null) ) ).thenDeclareRequired(CLASS_GEN_SETTINGS) .requiredConstructor(CONSTRUCTOR_GEN_SETTINGS).end() .next() .ifDetect(c -> !c.getRealClassName().contains("$") && c.getRealSuperClassName().equals("java/lang/Object") && c.getNumberOfConstructors() == 1 && (c.getNumberOfMethods() >= 1 && c.getNumberOfMethods() <= 4) && (c.getNumberOfFields() == 1 || c.getNumberOfFields() == 2) && c.getField(0).hasFlags(AccessFlags.PRIVATE | AccessFlags.FINAL) && (c.hasMethodWithRealArgsReturning("int", "int", "int", "int", null, null) || c.hasMethodWithRealArgsReturning("int", "int", "int", "int", null)) ) .thenDeclareRequired(CLASS_GEN_LAYER) .optionalMethod(METHOD_GEN_LAYER_GET_BIOME_DATA, "a").real("int").real("int").real("int").real("int").symbolic(CLASS_BIOME).end() .optionalMethod(METHOD_GEN_LAYER_GET_BIOME_DATA2, "a").real("int").real("int").real("int").real("int").end() //changed in 18w47b .next() .ifDetect(c -> c.getNumberOfConstructors() == 1 && c.getNumberOfFields() > 0 && c.getField(0).hasFlags(AccessFlags.STATIC | AccessFlags.FINAL) && c.searchForFloat(0.62222224F) ) .thenDeclareRequired(CLASS_BIOME) .optionalMethod(METHOD_BIOME_GET_ID, "a").symbolic(CLASS_BIOME).end() .next() .ifDetect(c -> c.getNumberOfConstructors() == 3 && c.getNumberOfFields() == 3 && c.getField(0).hasFlags(AccessFlags.PRIVATE | AccessFlags.STATIC | AccessFlags.FINAL) && c.searchForUtf8EqualTo("argument.id.invalid") && c.searchForUtf8EqualTo("minecraft") ) .thenDeclareOptional(CLASS_REGISTRY_KEY) .requiredConstructor(CONSTRUCTOR_REGISTRY_KEY).real("java.lang.String").end() .next() .ifDetect(c -> c.getNumberOfConstructors() <= 1 && c.getNumberOfFields() > 15 && c.searchForUtf8EqualTo("block") && c.searchForUtf8EqualTo("potion") && c.searchForUtf8EqualTo("biome") && c.searchForUtf8EqualTo("item") ) .thenDeclareOptional(CLASS_REGISTRY) .requiredField(FIELD_REGISTRY_META_REGISTRY, "f") .requiredMethod(METHOD_REGISTRY_GET_ID, "a").real("java.lang.Object").end() .optionalMethod(METHOD_REGISTRY_GET_BY_KEY, "b").symbolic(CLASS_REGISTRY_KEY).end() .optionalMethod(METHOD_REGISTRY_GET_BY_KEY2, "a").symbolic(CLASS_REGISTRY_KEY).end() // the name changed in 18w43c .next() .ifDetect(c -> c.searchForStringContaining("Server-Worker-") && c.searchForStringContaining("os.name") && c.searchForLong(1000000L) ) .thenDeclareOptional(CLASS_UTIL) .optionalField(FIELD_UTIL_SERVER_EXECUTOR, "c") .construct(); } // @formatter:on }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\legacy\_1_13MinecraftInterface.java
package amidst.mojangapi.minecraftinterface.legacy; import java.lang.invoke.MethodHandle; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.function.Function; import amidst.clazz.symbolic.SymbolicClass; import amidst.clazz.symbolic.SymbolicObject; import amidst.logging.AmidstLogger; import amidst.mojangapi.minecraftinterface.MinecraftInterface; import amidst.mojangapi.minecraftinterface.MinecraftInterfaceException; import amidst.mojangapi.minecraftinterface.RecognisedVersion; import amidst.mojangapi.minecraftinterface.ReflectionUtils; import amidst.mojangapi.minecraftinterface.UnsupportedDimensionException; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.WorldOptions; import amidst.mojangapi.world.WorldType; import amidst.util.ArrayCache; public class _1_13MinecraftInterface implements MinecraftInterface { public static final RecognisedVersion LAST_COMPATIBLE_VERSION = RecognisedVersion._19w35a; private final SymbolicClass bootstrapClass; private final SymbolicClass worldTypeClass; private final SymbolicClass genSettingsClass; private final SymbolicClass layerUtilClass; private final SymbolicClass genLayerClass; private final SymbolicClass biomeClass; private final SymbolicClass registryClass; private final SymbolicClass registryKeyClass; private final SymbolicClass utilClass; private boolean isInitialized = false; private final RecognisedVersion recognisedVersion; /** * The Biome.getId method handle. If version < 18w33a, the signature is: int * getId(Biome) If version >= 18w33a, the signature is: int * getId(Registry<Biome>, Biome) */ private MethodHandle biomeGetIdMethod; /** * A MethodHandle for getting the quarter resolution * biome data. */ private MethodHandle getBiomesMethod; /** * A boolean that is later set to provide whether the * 1.13 method parameters should be used to invoke the * method. We make it its own boolean so we don't * have to check the SymbolicClass every time. */ private boolean use113GetBiomesMethod; /** * The biome registry, for use with versions >= 18w33a */ private Object biomeRegistry; /** * An array used to return biome data */ private final ArrayCache<int[]> dataArray = ArrayCache.makeIntArrayCache(256); public _1_13MinecraftInterface( SymbolicClass bootstrapClass, SymbolicClass worldTypeClass, SymbolicClass genSettingsClass, SymbolicClass genLayerClass, SymbolicClass layerUtilClass, SymbolicClass biomeClass, SymbolicClass registryClass, SymbolicClass registryKeyClass, SymbolicClass utilClass, RecognisedVersion recognisedVersion) { this.bootstrapClass = bootstrapClass; this.worldTypeClass = worldTypeClass; this.genSettingsClass = genSettingsClass; this.genLayerClass = genLayerClass; this.layerUtilClass = layerUtilClass; this.biomeClass = biomeClass; this.registryClass = registryClass; this.registryKeyClass = registryKeyClass; this.utilClass = utilClass; this.recognisedVersion = recognisedVersion; } public _1_13MinecraftInterface(Map<String, SymbolicClass> symbolicClassMap, RecognisedVersion recognisedVersion) { this( symbolicClassMap.get(_1_13SymbolicNames.CLASS_BOOTSTRAP), symbolicClassMap.get(_1_13SymbolicNames.CLASS_WORLD_TYPE), symbolicClassMap.get(_1_13SymbolicNames.CLASS_GEN_SETTINGS), symbolicClassMap.get(_1_13SymbolicNames.CLASS_GEN_LAYER), symbolicClassMap.get(_1_13SymbolicNames.CLASS_LAYER_UTIL), symbolicClassMap.get(_1_13SymbolicNames.CLASS_BIOME), symbolicClassMap.get(_1_13SymbolicNames.CLASS_REGISTRY), symbolicClassMap.get(_1_13SymbolicNames.CLASS_REGISTRY_KEY), symbolicClassMap.get(_1_13SymbolicNames.CLASS_UTIL), recognisedVersion); } @Override public synchronized MinecraftInterface.WorldAccessor createWorldAccessor(WorldOptions worldOptions) throws MinecraftInterfaceException { initializeIfNeeded(); try { // @formatter:off Object[] genLayers = (Object[]) layerUtilClass.callStaticMethod( _1_13SymbolicNames.METHOD_LAYER_UTIL_INITIALIZE_ALL, worldOptions.getWorldSeed().getLong(), getWorldType(worldOptions.getWorldType()).getObject(), getGenSettings(worldOptions.getGeneratorOptions()).getObject() ); // @formatter:on return new WorldAccessor(genLayers[0], genLayers[1]); } catch ( IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) { throw new MinecraftInterfaceException("unable to create world", e); } } private synchronized void initializeIfNeeded() throws MinecraftInterfaceException { if (isInitialized) { return; } try { String register = _1_13SymbolicNames.METHOD_BOOTSTRAP_REGISTER; if(RecognisedVersion.isNewer(recognisedVersion, RecognisedVersion._1_13_2)) { if(bootstrapClass.getMethod(_1_13SymbolicNames.METHOD_BOOTSTRAP_REGISTER3).hasModifiers(Modifier.PUBLIC)) { register = _1_13SymbolicNames.METHOD_BOOTSTRAP_REGISTER3; } else if (bootstrapClass.getMethod(register).hasModifiers(Modifier.PRIVATE)) { register = _1_13SymbolicNames.METHOD_BOOTSTRAP_REGISTER2; } } initBiomeGetIdHandle(); if(genLayerClass.hasMethod(_1_13SymbolicNames.METHOD_GEN_LAYER_GET_BIOME_DATA)) { getBiomesMethod = ReflectionUtils.getMethodHandle(genLayerClass, _1_13SymbolicNames.METHOD_GEN_LAYER_GET_BIOME_DATA); use113GetBiomesMethod = true; } else { getBiomesMethod = ReflectionUtils.getMethodHandle(genLayerClass, _1_13SymbolicNames.METHOD_GEN_LAYER_GET_BIOME_DATA2); } bootstrapClass.callStaticMethod(register); // Minecraft's datafixers have been created during the initialization // of the DataFixesManager class since 1.13 (I think). In our case, // the class gets initialized during the bootstrapping stage. For our // use case of the minecraft code, the datafixers are useless. The // creation of the datafixers take valuable processor time and memory, // so it's best to disable them in any way we can. Unfortunately, the // only way to do this is to just shut down the thread pool that creates // them. This doesn't work for versions before 1.14 because they use // ForkJoinPool.commonPool(), which is unaffected by shutdown() and // shutdownNow(). if(RecognisedVersion.isNewer(recognisedVersion, RecognisedVersion._1_13_2)) { try { ((ExecutorService) utilClass.getStaticFieldValue(_1_13SymbolicNames.FIELD_UTIL_SERVER_EXECUTOR)).shutdownNow(); } catch (NullPointerException e) { AmidstLogger.warn("Unable to shut down Server-Worker threads"); } } isInitialized = true; } catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new MinecraftInterfaceException("unable to initialize the MinecraftInterface", e); } } private synchronized void initBiomeGetIdHandle() throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException { if (biomeGetIdMethod != null) { return; } boolean biomeGetIdMethodReturnsInt = biomeClass.getMethod(_1_13SymbolicNames.METHOD_BIOME_GET_ID) .getRawMethod().getReturnType().equals(Integer.TYPE); if (registryKeyClass != null && !biomeGetIdMethodReturnsInt) { biomeRegistry = getBiomeRegistry(); biomeGetIdMethod = ReflectionUtils.getMethodHandle(registryClass, _1_13SymbolicNames.METHOD_REGISTRY_GET_ID); } else { biomeGetIdMethod = ReflectionUtils.getMethodHandle(biomeClass, _1_13SymbolicNames.METHOD_BIOME_GET_ID); } } private Object getBiomeRegistry() throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException { SymbolicObject metaRegistry = (SymbolicObject) registryClass .getStaticFieldValue(_1_13SymbolicNames.FIELD_REGISTRY_META_REGISTRY); Object biomeRegistryKey = registryKeyClass .callConstructor(_1_13SymbolicNames.CONSTRUCTOR_REGISTRY_KEY, "biome") .getObject(); String getByKey = _1_13SymbolicNames.METHOD_REGISTRY_GET_BY_KEY; if (!registryClass.getMethod(getByKey).hasReturnType(Object.class)) { getByKey = _1_13SymbolicNames.METHOD_REGISTRY_GET_BY_KEY2; } Object biomeRegistryObj = metaRegistry.callMethod(getByKey, biomeRegistryKey); return biomeRegistryObj; } private SymbolicObject getWorldType(WorldType worldType) throws IllegalArgumentException, IllegalAccessException { return (SymbolicObject) worldTypeClass.getStaticFieldValue(worldType.getSymbolicFieldName()); } private SymbolicObject getGenSettings(String generatorOptions) throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException { if (!generatorOptions.isEmpty()) { AmidstLogger.warn("Custom generator options aren't supported in this version"); } return genSettingsClass.callConstructor(_1_13SymbolicNames.CONSTRUCTOR_GEN_SETTINGS); } @Override public RecognisedVersion getRecognisedVersion() { return recognisedVersion; } private class WorldAccessor implements MinecraftInterface.WorldAccessor { /** * A GenLayer instance, at quarter scale to the final biome layer (i.e. both * axis are divided by 4). Minecraft calculates biomes at * quarter-resolution, then noisily interpolates the biome-map up to 1:1 * resolution when needed, this is the biome GenLayer before it is * interpolated. */ private final Object quarterResolutionBiomeGenerator; /** * A GenLayer instance, the biome layer. (1:1 scale) Minecraft calculates * biomes at quarter-resolution, then noisily interpolates the biome-map up * to 1:1 resolution when needed, this is the interpolated biome GenLayer. */ private final Object fullResolutionBiomeGenerator; private WorldAccessor(Object quarterResolutionGen, Object fullResolutionGen) { this.quarterResolutionBiomeGenerator = quarterResolutionGen; this.fullResolutionBiomeGenerator = fullResolutionGen; } @Override public<T> T getBiomeData(Dimension dimension, int x, int y, int width, int height, boolean useQuarterResolution, Function<int[], T> biomeDataMapper) throws MinecraftInterfaceException { if (dimension != Dimension.OVERWORLD) throw new UnsupportedDimensionException(dimension); Object biomeGenerator = useQuarterResolution ? quarterResolutionBiomeGenerator : fullResolutionBiomeGenerator; int size = width * height; return dataArray.withArrayFaillible(size, data -> { try { if(size <= 16) { data[0] = getBiomeId(getBiomeData(x, y, width, height, biomeGenerator)); return biomeDataMapper.apply(data); } /** * We break the region in 16x16 chunks, to get better performance out * of the LazyArea used by the game. This gives a ~2x improvement. * * In the period of time between 18w16a to 18w47a, this caused the * performance to be worse, so we exclude those versions here. */ if (RecognisedVersion.isNewerOrEqualTo(recognisedVersion, RecognisedVersion._18w16a) && RecognisedVersion.isOlder(recognisedVersion, RecognisedVersion._18w47b)) { Object[] biomes = getBiomeData(x, y, width, height, biomeGenerator); for (int i = 0; i < biomes.length; i++) { data[i] = getBiomeId(biomes[i]); } } else { int chunkSize = 16; for (int x0 = 0; x0 < width; x0 += chunkSize) { int w = Math.min(chunkSize, width - x0); for (int y0 = 0; y0 < height; y0 += chunkSize) { int h = Math.min(chunkSize, height - y0); Object[] biomes = getBiomeData(x + x0, y + y0, w, h, biomeGenerator); for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { int idx = i + j * w; int trueIdx = (x0 + i) + (y0 + j) * width; data[trueIdx] = getBiomeId(biomes[idx]); } } } } } } catch (Throwable e) { throw new MinecraftInterfaceException("unable to get biome data", e); } return biomeDataMapper.apply(data); }); } private Object[] getBiomeData(int x, int y, int width, int height, Object biomeGen) throws Throwable { if(use113GetBiomesMethod) { return (Object[]) getBiomesMethod.invokeExact(biomeGen, x, y, width, height, (Object) null); } else { return (Object[]) getBiomesMethod.invokeExact(biomeGen, x, y, width, height); } } private int getBiomeId(Object biome) throws MinecraftInterfaceException { try { if (biomeRegistry != null) { return (int) biomeGetIdMethod.invokeExact(biomeRegistry, biome); } else { return (int) biomeGetIdMethod.invokeExact(biome); } } catch (Throwable e) { e.printStackTrace(); throw new MinecraftInterfaceException("unable to get biome data", e); } } @Override public Set<Dimension> supportedDimensions() { return Collections.singleton(Dimension.OVERWORLD); } } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\legacy\_1_13SymbolicNames.java
package amidst.mojangapi.minecraftinterface.legacy; import amidst.documentation.Immutable; @Immutable public enum _1_13SymbolicNames { ; public static final String CLASS_WORLD_TYPE = _1_15SymbolicNames.CLASS_WORLD_TYPE; public static final String FIELD_WORLD_TYPE_DEFAULT = _1_15SymbolicNames.FIELD_WORLD_TYPE_DEFAULT; public static final String FIELD_WORLD_TYPE_FLAT = _1_15SymbolicNames.FIELD_WORLD_TYPE_FLAT; public static final String FIELD_WORLD_TYPE_LARGE_BIOMES = _1_15SymbolicNames.FIELD_WORLD_TYPE_LARGE_BIOMES; public static final String FIELD_WORLD_TYPE_AMPLIFIED = _1_15SymbolicNames.FIELD_WORLD_TYPE_AMPLIFIED; public static final String FIELD_WORLD_TYPE_CUSTOMIZED = _1_15SymbolicNames.FIELD_WORLD_TYPE_CUSTOMIZED; public static final String CLASS_BOOTSTRAP = "Bootstrap"; public static final String METHOD_BOOTSTRAP_REGISTER = "register"; public static final String METHOD_BOOTSTRAP_REGISTER2 = "register2"; public static final String METHOD_BOOTSTRAP_REGISTER3 = "register3"; public static final String CLASS_UTIL = "Util"; public static final String FIELD_UTIL_SERVER_EXECUTOR = "SERVER_EXECUTOR"; public static final String CLASS_LAYER_UTIL = "LayerUtil"; public static final String METHOD_LAYER_UTIL_INITIALIZE_ALL = "initializeAll"; public static final String CLASS_GEN_SETTINGS = "OverworldGenSettings"; public static final String CONSTRUCTOR_GEN_SETTINGS = "<init>"; public static final String CLASS_GEN_LAYER = "GenLayer"; public static final String METHOD_GEN_LAYER_GET_BIOME_DATA = "getBiomeData"; public static final String METHOD_GEN_LAYER_GET_BIOME_DATA2 = "getBiomeData2"; public static final String CLASS_BIOME = "Biome"; public static final String METHOD_BIOME_GET_ID = "getBiomeId"; public static final String CLASS_REGISTRY = "Registry"; public static final String FIELD_REGISTRY_META_REGISTRY = "metaRegistry"; public static final String METHOD_REGISTRY_GET_BY_KEY = "getByKey"; public static final String METHOD_REGISTRY_GET_BY_KEY2 = "getByKey2"; public static final String METHOD_REGISTRY_GET_ID = "getId"; public static final String CLASS_REGISTRY_KEY = "RegistryKey"; public static final String CONSTRUCTOR_REGISTRY_KEY = "<init>"; }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\legacy\_1_15ClassTranslator.java
package amidst.mojangapi.minecraftinterface.legacy; import static amidst.mojangapi.minecraftinterface.legacy._1_15SymbolicNames.*; import amidst.clazz.real.AccessFlags; import amidst.clazz.translator.ClassTranslator; public enum _1_15ClassTranslator { INSTANCE; private final ClassTranslator classTranslator = createClassTranslator(); public static ClassTranslator get() { return INSTANCE.classTranslator; } // @formatter:off private ClassTranslator createClassTranslator() { return ClassTranslator .builder() .ifDetect(c -> c.getNumberOfConstructors() == 3 && c.getNumberOfFields() == 3 && c.getField(0).hasFlags(AccessFlags.PRIVATE | AccessFlags.STATIC | AccessFlags.FINAL) && c.searchForUtf8EqualTo("argument.id.invalid") && c.searchForUtf8EqualTo("minecraft") ) .thenDeclareOptional(CLASS_REGISTRY_KEY) .requiredConstructor(CONSTRUCTOR_REGISTRY_KEY).real("java.lang.String").end() .next() .ifDetect(c -> c.getNumberOfConstructors() <= 1 && c.getNumberOfFields() > 15 && c.searchForUtf8EqualTo("block") && c.searchForUtf8EqualTo("potion") && c.searchForUtf8EqualTo("biome") && c.searchForUtf8EqualTo("item") ) .thenDeclareOptional(CLASS_REGISTRY) .requiredField(FIELD_REGISTRY_META_REGISTRY, "f") .requiredMethod(METHOD_REGISTRY_GET_ID, "a").real("java.lang.Object").end() .requiredMethod(METHOD_REGISTRY_GET_BY_KEY, "a").symbolic(CLASS_REGISTRY_KEY).end() .next() .ifDetect(c -> c.searchForStringContaining("default_1_1")) .thenDeclareRequired(CLASS_WORLD_TYPE) .requiredField(FIELD_WORLD_TYPE_DEFAULT, "b") .requiredField(FIELD_WORLD_TYPE_FLAT, "c") .requiredField(FIELD_WORLD_TYPE_LARGE_BIOMES, "d") .requiredField(FIELD_WORLD_TYPE_AMPLIFIED, "e") .requiredField(FIELD_WORLD_TYPE_CUSTOMIZED, "f") .next() .ifDetect(c -> c.getRealSuperClassName().equals("java/lang/Enum") && c.searchForUtf8EqualTo("gameMode.") ) .thenDeclareRequired(CLASS_GAME_TYPE) .next() .ifDetect(c -> !c.getRealClassName().contains("$") && c.getRealSuperClassName().equals("java/lang/Object") && c.isFinal() && c.getNumberOfConstructors() <= 2 && c.getNumberOfFields() >= 5 && c.getNumberOfFields() <= 10 && c.getField(1).hasFlags(AccessFlags.PRIVATE | AccessFlags.FINAL) ) .thenDeclareRequired(CLASS_WORLD_SETTINGS) .optionalConstructor(CONSTRUCTOR_WORLD_SETTINGS).real("long").symbolic(CLASS_GAME_TYPE).real("boolean").real("boolean").symbolic(CLASS_WORLD_TYPE).end() .next() .ifDetect(c -> c.getNumberOfFields() > 30 && c.searchForUtf8EqualTo("SizeOnDisk") && c.searchForUtf8EqualTo("DifficultyLocked") ) .thenDeclareRequired(CLASS_WORLD_DATA) .optionalConstructor(CONSTRUCTOR_WORLD_DATA).symbolic(CLASS_WORLD_SETTINGS).real("java.lang.String").end() .optionalConstructor(CONSTRUCTOR_WORLD_DATA2).symbolic(CLASS_WORLD_SETTINGS).end() // after 20w17a .next() .ifDetect(c -> c.getRealClassName().contains("$") && c.isInterface() && c.getNumberOfMethods() == 1 && c.hasMethodWithRealArgsReturning("int", "int", "int", null) && !c.hasMethodWithRealArgsReturning("int", "int", "int", "boolean") ) .thenDeclareRequired(CLASS_NOISE_BIOME_PROVIDER) .requiredMethod(METHOD_NOISE_BIOME_PROVIDER_GET_BIOME, "b").real("int").real("int").real("int").end() .next() .ifDetect(c -> !c.getRealClassName().contains("$") && c.getRealSuperClassName().equals("java/lang/Enum") && c.hasMethodWithRealArgsReturning("long", "int", "int", "int", null, null) && c.getNumberOfMethods() == 4 ) .thenDeclareRequired(CLASS_OVERWORLD_BIOME_ZOOMER) .requiredMethod(METHOD_BIOME_ZOOMER_GET_BIOME, "a").real("long").real("int").real("int").real("int").symbolic(CLASS_NOISE_BIOME_PROVIDER).end() .next() .ifDetect(c -> c.getNumberOfConstructors() == 1 && c.getNumberOfFields() > 0 && c.getField(0).hasFlags(AccessFlags.STATIC | AccessFlags.FINAL) && (c.searchForFloat(0.62222224F) || c.searchForUtf8EqualTo("Feature placement")) ) .thenDeclareRequired(CLASS_BIOME) .next() .ifDetect(c -> c.hasConstructorWithRealArgs("long") && (c.hasMethodWithRealArgsReturning("java/util/Set", c.getRealClassName()) || c.hasMethodWithRealArgsReturning("java/util/List", c.getRealClassName())) ) .thenDeclareOptional(CLASS_NETHER_BIOME_SETTINGS) .requiredConstructor(CONSTRUCTOR_NETHER_BIOME_SETTINGS).real("long").end() .optionalMethod(METHOD_NETHER_BIOME_SETTINGS_SET_BIOMES1, "a").real("java.util.Set").end() .optionalMethod(METHOD_NETHER_BIOME_SETTINGS_SET_BIOMES2, "a").real("java.util.List").end() .next() .ifDetect(c -> c.searchForLong(2L) && c.searchForLong(3L) && c.getNumberOfConstructors() == 1 && c.getNumberOfMethods() == 2 ) .thenDeclareOptional(CLASS_NETHER_BIOME_PROVIDER) .requiredConstructor(CONSTRUCTOR_NETHER_BIOME_PROVIDER).symbolic(CLASS_NETHER_BIOME_SETTINGS).end() .next() .ifDetect(c -> (c.searchForStringContaining("Server-Worker-") || c.searchForStringContaining("Worker-")) && c.searchForStringContaining("os.name") && c.searchForLong(1000000L) ) .thenDeclareOptional(CLASS_UTIL) .construct(); } // @formatter:on }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\legacy\_1_15MinecraftInterface.java
package amidst.mojangapi.minecraftinterface.legacy; import java.lang.invoke.MethodHandle; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.function.Function; import amidst.clazz.symbolic.SymbolicClass; import amidst.clazz.symbolic.SymbolicObject; import amidst.logging.AmidstLogger; import amidst.mojangapi.minecraftinterface.MinecraftInterface; import amidst.mojangapi.minecraftinterface.MinecraftInterfaceException; import amidst.mojangapi.minecraftinterface.RecognisedVersion; import amidst.mojangapi.minecraftinterface.ReflectionUtils; import amidst.mojangapi.minecraftinterface.UnsupportedDimensionException; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.WorldOptions; import amidst.mojangapi.world.WorldType; import amidst.util.ArrayCache; public class _1_15MinecraftInterface implements MinecraftInterface { public static final RecognisedVersion LAST_COMPATIBLE_VERSION = RecognisedVersion._20w19a; private static final List<String> NETHER_BIOME_NAMES = Arrays.asList( "nether_wastes", "soul_sand_valley", "crimson_forest", "warped_forest", "basalt_deltas" ); private boolean isInitialized = false; private final RecognisedVersion recognisedVersion; private final SymbolicClass registryClass; private final SymbolicClass registryKeyClass; private final SymbolicClass worldTypeClass; private final SymbolicClass gameTypeClass; private final SymbolicClass worldSettingsClass; private final SymbolicClass worldDataClass; private final SymbolicClass noiseBiomeProviderClass; private final SymbolicClass overworldBiomeZoomerClass; private final SymbolicClass netherBiomeProviderClass; private final SymbolicClass netherBiomeSettingsClass; private final SymbolicClass utilClass; private MethodHandle registryGetIdMethod; private MethodHandle biomeProviderGetBiomeMethod; private MethodHandle biomeZoomerGetBiomeMethod; private Object biomeRegistry; private Object biomeProviderRegistry; /** * An array used to return biome data */ private final ArrayCache<int[]> dataArray = ArrayCache.makeIntArrayCache(256); public _1_15MinecraftInterface(Map<String, SymbolicClass> symbolicClassMap, RecognisedVersion recognisedVersion) { this.recognisedVersion = recognisedVersion; this.registryClass = symbolicClassMap.get(_1_15SymbolicNames.CLASS_REGISTRY); this.registryKeyClass = symbolicClassMap.get(_1_15SymbolicNames.CLASS_REGISTRY_KEY); this.worldTypeClass = symbolicClassMap.get(_1_15SymbolicNames.CLASS_WORLD_TYPE); this.gameTypeClass = symbolicClassMap.get(_1_15SymbolicNames.CLASS_GAME_TYPE); this.worldSettingsClass = symbolicClassMap.get(_1_15SymbolicNames.CLASS_WORLD_SETTINGS); this.worldDataClass = symbolicClassMap.get(_1_15SymbolicNames.CLASS_WORLD_DATA); this.noiseBiomeProviderClass = symbolicClassMap.get(_1_15SymbolicNames.CLASS_NOISE_BIOME_PROVIDER); this.overworldBiomeZoomerClass = symbolicClassMap.get(_1_15SymbolicNames.CLASS_OVERWORLD_BIOME_ZOOMER); this.netherBiomeProviderClass = symbolicClassMap.get(_1_15SymbolicNames.CLASS_NETHER_BIOME_PROVIDER); this.netherBiomeSettingsClass = symbolicClassMap.get(_1_15SymbolicNames.CLASS_NETHER_BIOME_SETTINGS); this.utilClass = symbolicClassMap.get(_1_15SymbolicNames.CLASS_UTIL); } @Override public synchronized MinecraftInterface.WorldAccessor createWorldAccessor(WorldOptions worldOptions) throws MinecraftInterfaceException { initializeIfNeeded(); try { long seed = worldOptions.getWorldSeed().getLong(); Object overworldBiomeProvider = createBiomeProviderObject(seed, worldOptions.getWorldType(), worldOptions.getGeneratorOptions()); Object netherBiomeProvider = manuallyCreateNetherBiomeProvider(seed); Object biomeZoomer = overworldBiomeZoomerClass.getClazz().getEnumConstants()[0]; long seedForBiomeZoomer = makeSeedForBiomeZoomer(seed); return new WorldAccessor(overworldBiomeProvider, netherBiomeProvider, biomeZoomer, seedForBiomeZoomer); } catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new MinecraftInterfaceException("unable to create world", e); } } private static long makeSeedForBiomeZoomer(long seed) throws MinecraftInterfaceException { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); ByteBuffer buf = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN); buf.putLong(seed); byte[] bytes = digest.digest(buf.array()); long result = 0; for (int i = 0; i < 8; i++) { result |= (bytes[i] & 0xffL) << (i*8L); } return result; } catch (NoSuchAlgorithmException e) { throw new MinecraftInterfaceException("unable to hash seed", e); } } private Object createWorldDataObject(long seed, WorldType worldType, String generatorOptions) throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, MinecraftInterfaceException { if (!generatorOptions.isEmpty()) { AmidstLogger.warn("Custom generator options aren't supported in this version"); } if (!worldSettingsClass.hasConstructor(_1_15SymbolicNames.CONSTRUCTOR_WORLD_SETTINGS)) { throw new MinecraftInterfaceException("unable to create world settings"); } // We don't care which GameType we pick Object gameType = gameTypeClass.getClazz().getEnumConstants()[0]; SymbolicObject worldSettings = worldSettingsClass.callConstructor(_1_15SymbolicNames.CONSTRUCTOR_WORLD_SETTINGS, seed, gameType, false, false, getWorldTypeObject(worldType)); SymbolicObject worldData; if(worldDataClass.hasConstructor(_1_15SymbolicNames.CONSTRUCTOR_WORLD_DATA)) { worldData = worldDataClass.callConstructor(_1_15SymbolicNames.CONSTRUCTOR_WORLD_DATA, worldSettings.getObject(), "<amidst-world>"); } else { worldData = worldDataClass.callConstructor(_1_15SymbolicNames.CONSTRUCTOR_WORLD_DATA, worldSettings.getObject()); } return worldData.getObject(); } private Object createBiomeProviderObject(long seed, WorldType worldType, String generatorOptions) throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, MinecraftInterfaceException { Object providerType = getFromRegistryByKey(biomeProviderRegistry, "vanilla_layered"); /* * The BiomeProviderType class is hard to properly detect with the ClassTranslator, so * we prefer working with it directly with the Java reflection API. */ Method createMethod = null; // BiomeProvider create(BiomeProviderSettings settings) Method createSettingsMethod = null; // BiomeProviderSettings createSettings(WorldData world) Method createSettingsWithSeedMethod = null; // BiomeProviderSettings createSettings(long seed) for (Method meth: providerType.getClass().getDeclaredMethods()) { if (!meth.isSynthetic() && meth.getParameterCount() == 1) { Class<?> param = meth.getParameterTypes()[0]; if(param.equals(worldDataClass.getClazz())) { createSettingsMethod = meth; } else if(param.equals(Long.TYPE)) { createSettingsWithSeedMethod = meth; } else if (noiseBiomeProviderClass.getClazz().isAssignableFrom(meth.getReturnType())) { createMethod = meth; } } } Object providerSettings; if (createSettingsMethod != null) { Object worldData = createWorldDataObject(seed, worldType, generatorOptions); providerSettings = createSettingsMethod.invoke(providerType, worldData); } else if (createSettingsWithSeedMethod != null) { providerSettings = createSettingsWithSeedMethod.invoke(providerType, seed); populateBiomeProviderSettings(providerSettings, worldType, generatorOptions); } else { throw new MinecraftInterfaceException("unable to create biome provider settings"); } return createMethod.invoke(providerType, providerSettings); } private void populateBiomeProviderSettings(Object providerSettings, WorldType worldType, String generatorOptions) throws IllegalArgumentException, IllegalAccessException, MinecraftInterfaceException { if (!generatorOptions.isEmpty()) { // TODO: fix me AmidstLogger.warn("Custom generator options aren't supported in this version"); } Object worldTypeObj = getWorldTypeObject(worldType); /* * We don't want to depend on a specific class, so we manually * set the WorldType field with reflection. */ boolean worldTypeSet = false; for (Field field: providerSettings.getClass().getDeclaredFields()) { if (field.getType().isAssignableFrom(worldTypeObj.getClass())) { field.setAccessible(true); field.set(providerSettings, worldTypeObj); worldTypeSet = true; break; } } if (!worldTypeSet) { throw new MinecraftInterfaceException("unable to populate biome provider settings"); } } private Object getWorldTypeObject(WorldType worldType) throws IllegalArgumentException, IllegalAccessException { SymbolicObject worldTypeObj = (SymbolicObject) worldTypeClass .getStaticFieldValue(worldType.getSymbolicFieldName()); return worldTypeObj.getObject(); } private Object manuallyCreateNetherBiomeProvider(long seed) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, MinecraftInterfaceException { // Minecraft doesn't give us an easy way to create the Nether biome provider, so we do it ourselves. if (netherBiomeProviderClass == null) { return null; } SymbolicObject biomeSettings = netherBiomeSettingsClass.callConstructor( _1_15SymbolicNames.CONSTRUCTOR_NETHER_BIOME_SETTINGS, seed); if (netherBiomeSettingsClass.hasMethod(_1_15SymbolicNames.METHOD_NETHER_BIOME_SETTINGS_SET_BIOMES1)) { Set<Object> biomes = new HashSet<>(); addNetherBiomesToCollection(biomes); biomeSettings.callMethod(_1_15SymbolicNames.METHOD_NETHER_BIOME_SETTINGS_SET_BIOMES1, biomes); } else if (netherBiomeSettingsClass.hasMethod(_1_15SymbolicNames.METHOD_NETHER_BIOME_SETTINGS_SET_BIOMES2)) { List<Object> biomes = new ArrayList<>(); addNetherBiomesToCollection(biomes); biomeSettings.callMethod(_1_15SymbolicNames.METHOD_NETHER_BIOME_SETTINGS_SET_BIOMES2, biomes); } else { throw new MinecraftInterfaceException("couldn't create nether biomes"); } return netherBiomeProviderClass.callConstructor( _1_15SymbolicNames.CONSTRUCTOR_NETHER_BIOME_PROVIDER, biomeSettings.getObject()).getObject(); } private void addNetherBiomesToCollection(Collection<Object> biomes) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { for (String biomeName: NETHER_BIOME_NAMES) { Object biome = getFromRegistryByKey(biomeRegistry, biomeName); if (biome != null) { biomes.add(biome); } } } @Override public RecognisedVersion getRecognisedVersion() { return recognisedVersion; } private synchronized void initializeIfNeeded() throws MinecraftInterfaceException { if (isInitialized) { return; } try { Object metaRegistry = ((SymbolicObject) registryClass .getStaticFieldValue(_1_15SymbolicNames.FIELD_REGISTRY_META_REGISTRY)).getObject(); stopAllExecutors(); biomeRegistry = Objects.requireNonNull(getFromRegistryByKey(metaRegistry, "biome")); biomeProviderRegistry = Objects.requireNonNull(getFromRegistryByKey(metaRegistry, "biome_source_type")); registryGetIdMethod = ReflectionUtils.getMethodHandle(registryClass, _1_15SymbolicNames.METHOD_REGISTRY_GET_ID); biomeProviderGetBiomeMethod = ReflectionUtils.getMethodHandle(noiseBiomeProviderClass, _1_15SymbolicNames.METHOD_NOISE_BIOME_PROVIDER_GET_BIOME); biomeZoomerGetBiomeMethod = ReflectionUtils.getMethodHandle(overworldBiomeZoomerClass, _1_15SymbolicNames.METHOD_BIOME_ZOOMER_GET_BIOME); } catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new MinecraftInterfaceException("unable to initialize the MinecraftInterface", e); } isInitialized = true; } private void stopAllExecutors() throws IllegalArgumentException, IllegalAccessException { Class<?> clazz = utilClass.getClazz(); for (Field field: clazz.getDeclaredFields()) { if ((field.getModifiers() & Modifier.STATIC) > 0 && field.getType().equals(ExecutorService.class)) { field.setAccessible(true); ExecutorService exec = (ExecutorService) field.get(null); exec.shutdownNow(); } } } private Object getFromRegistryByKey(Object registry, String key) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Object registryKey = registryKeyClass .callConstructor(_1_15SymbolicNames.CONSTRUCTOR_REGISTRY_KEY, key) .getObject(); Method getByKey = registryClass.getMethod(_1_15SymbolicNames.METHOD_REGISTRY_GET_BY_KEY).getRawMethod(); return getByKey.invoke(registry, registryKey); } private class WorldAccessor implements MinecraftInterface.WorldAccessor { /** * A BiomeProvider instance for the current overworld, giving * access to the quarter-scale biome data. */ private final Object overworldBiomeProvider; /** * A Biome provider instance for the current nether. */ private final Object netherBiomeProvider; /** * The BiomeZoomer instance for the current world, which * interpolates the quarter-scale BiomeProvider to give * full-scale biome data. */ private final Object biomeZoomer; /** * The seed used by the BiomeZoomer during interpolation. * It is derived from the world seed. */ private final long seedForBiomeZoomer; private final Set<Dimension> supportedDimensions; private WorldAccessor(Object overworldBiomeProvider, Object netherBiomeProvider, Object biomeZoomer, long seedForBiomeZoomer) { this.overworldBiomeProvider = overworldBiomeProvider; this.netherBiomeProvider = netherBiomeProvider; this.biomeZoomer = biomeZoomer; this.seedForBiomeZoomer = seedForBiomeZoomer; Set<Dimension> supportedDimensions = EnumSet.of(Dimension.OVERWORLD); if (netherBiomeProvider != null) { supportedDimensions.add(Dimension.NETHER); } this.supportedDimensions = Collections.unmodifiableSet(supportedDimensions); } @Override public<T> T getBiomeData( Dimension dimension, int x, int y, int width, int height, boolean useQuarterResolution, Function<int[], T> biomeDataMapper) throws MinecraftInterfaceException { Object biomeProvider; int biomeHeight; switch (dimension) { case OVERWORLD: biomeProvider = this.overworldBiomeProvider; biomeHeight = 0; // The overworld uses y=0 for all heights break; case NETHER: if (this.netherBiomeProvider != null) { biomeProvider = this.netherBiomeProvider; biomeHeight = 63; // Pick an arbitrary value break; } default: throw new UnsupportedDimensionException(dimension); } int size = width * height; return dataArray.withArrayFaillible(size, data -> { try { if(size == 1) { data[0] = getBiomeIdAt(biomeProvider, biomeHeight, x, y, useQuarterResolution); return biomeDataMapper.apply(data); } /** * We break the region in 16x16 chunks, to get better performance out * of the LazyArea used by the game. This gives a ~2x improvement. */ int chunkSize = 16; for (int x0 = 0; x0 < width; x0 += chunkSize) { int w = Math.min(chunkSize, width - x0); for (int y0 = 0; y0 < height; y0 += chunkSize) { int h = Math.min(chunkSize, height - y0); for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { int trueIdx = (x0 + i) + (y0 + j) * width; data[trueIdx] = getBiomeIdAt(biomeProvider, biomeHeight, x + x0 + i, y + y0 + j, useQuarterResolution); } } } } } catch (Throwable e) { throw new MinecraftInterfaceException("unable to get biome data", e); } return biomeDataMapper.apply(data); }); } private int getBiomeIdAt(Object biomeProvider, int biomeHeight, int x, int y, boolean useQuarterResolution) throws Throwable { Object biome; if(useQuarterResolution) { biome = biomeProviderGetBiomeMethod.invokeExact(biomeProvider, x, biomeHeight, y); } else { biome = biomeZoomerGetBiomeMethod.invokeExact(biomeZoomer, seedForBiomeZoomer, x, biomeHeight, y, biomeProvider); } return (int) registryGetIdMethod.invokeExact(biomeRegistry, biome); } @Override public Set<Dimension> supportedDimensions() { return supportedDimensions; } } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\legacy\_1_15SymbolicNames.java
package amidst.mojangapi.minecraftinterface.legacy; import amidst.documentation.Immutable; @Immutable public enum _1_15SymbolicNames { ; public static final String CLASS_REGISTRY = "Registry"; public static final String FIELD_REGISTRY_META_REGISTRY = "metaRegistry"; public static final String METHOD_REGISTRY_GET_BY_KEY = "getByKey"; public static final String METHOD_REGISTRY_GET_ID = "getId"; public static final String CLASS_REGISTRY_KEY = "RegistryKey"; public static final String CONSTRUCTOR_REGISTRY_KEY = "<init>"; public static final String CLASS_UTIL = "Util"; // TODO: correctly manage world types; remove duplication with legacy SymbolicNames public static final String CLASS_WORLD_TYPE = "WorldType"; public static final String FIELD_WORLD_TYPE_DEFAULT = "default"; public static final String FIELD_WORLD_TYPE_FLAT = "flat"; public static final String FIELD_WORLD_TYPE_LARGE_BIOMES = "largeBiomes"; public static final String FIELD_WORLD_TYPE_AMPLIFIED = "amplified"; public static final String FIELD_WORLD_TYPE_CUSTOMIZED = "customized"; public static final String CLASS_WORLD_DATA = "WorldData"; public static final String CONSTRUCTOR_WORLD_DATA = "<init>"; public static final String CONSTRUCTOR_WORLD_DATA2 = "<init2>"; public static final String CLASS_WORLD_SETTINGS = "WorldSettings"; public static final String CONSTRUCTOR_WORLD_SETTINGS = "<init>"; public static final String CLASS_GAME_TYPE = "GameType"; public static final String CLASS_NOISE_BIOME_PROVIDER = "NoiseBiomeProvider"; public static final String CLASS_NETHER_BIOME_PROVIDER = "NetherBiomeProvider"; public static final String CONSTRUCTOR_NETHER_BIOME_PROVIDER = "<init>"; public static final String METHOD_NOISE_BIOME_PROVIDER_GET_BIOME = "getBiome"; public static final String CLASS_NETHER_BIOME_SETTINGS = "NetherBiomeSettings"; public static final String CONSTRUCTOR_NETHER_BIOME_SETTINGS = "<init>"; public static final String METHOD_NETHER_BIOME_SETTINGS_SET_BIOMES1 = "setBiomes1"; public static final String METHOD_NETHER_BIOME_SETTINGS_SET_BIOMES2 = "setBiomes2"; public static final String CLASS_OVERWORLD_BIOME_ZOOMER = "OverworldBiomeZoomer"; public static final String METHOD_BIOME_ZOOMER_GET_BIOME = "getBiome"; public static final String CLASS_BIOME = "Biome"; }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\local\DefaultClassTranslator.java
package amidst.mojangapi.minecraftinterface.local; import static amidst.mojangapi.minecraftinterface.local.SymbolicNames.*; import amidst.clazz.real.AccessFlags; import amidst.clazz.translator.ClassTranslator; public enum DefaultClassTranslator { INSTANCE; private final ClassTranslator classTranslator = createClassTranslator(); public static ClassTranslator get() { return INSTANCE.classTranslator; } // @formatter:off private ClassTranslator createClassTranslator() { return ClassTranslator .builder() .ifDetect(c -> c.getNumberOfFields() == 3 && c.searchForUtf8EqualTo("Unable to load registries") && c.getField(1).hasFlags(AccessFlags.STATIC) ) .thenDeclareRequired(CLASS_BOOTSTRAP) .requiredField(FIELD_BOOTSTRAP_IS_BOOTSTRAPPED, "b") .next() .ifDetect(c -> c.searchForUtf8EqualTo("Game version not set")) .thenDeclareOptional(CLASS_SHARED_CONSTANTS) .requiredMethod(METHOD_SHARED_CONSTANTS_DETECT_VERSION, "a").end() .next() .ifDetect(c -> c.getNumberOfConstructors() == 3 && (c.getNumberOfFields() >= 3 && c.getNumberOfFields() <= 7) && c.getField(0).hasFlags(AccessFlags.STATIC | AccessFlags.FINAL) && c.searchForUtf8EqualTo("minecraft") && c.searchForUtf8EqualTo("argument.id.invalid") ) .thenDeclareRequired(CLASS_RESOURCE_KEY) .requiredConstructor(CONSTRUCTOR_RESOURCE_KEY).real("java.lang.String").end() .next() .ifDetect(c -> c.searchForStringContaining("ResourceKey[")) .thenDeclareOptional(CLASS_REGISTRY_ACCESS_KEY) // since 20w21a .next() .ifDetect(c -> c.getNumberOfConstructors() <= 1 && c.getNumberOfFields() > 15 && c.searchForUtf8EqualTo("block") && c.searchForUtf8EqualTo("potion") && (c.searchForUtf8EqualTo("biome") || c.searchForUtf8EqualTo("worldgen/biome")) && c.searchForUtf8EqualTo("item") ) .thenDeclareRequired(CLASS_REGISTRY) .requiredField(FIELD_REGISTRY_META_REGISTRY, "f") .requiredField(FIELD_REGISTRY_META_REGISTRY2, "i") .requiredField(FIELD_REGISTRY_META_REGISTRY3, "h") .optionalMethod(METHOD_REGISTRY_CREATE_KEY, "a").real("java.lang.String").end() .requiredMethod(METHOD_REGISTRY_GET_ID, "a").real("java.lang.Object").end() .requiredMethod(METHOD_REGISTRY_GET_BY_KEY, "a").symbolic(CLASS_RESOURCE_KEY).end() .next() .ifDetect(c -> c.searchForStringContaining("Missing registry: ")) // since 20w28a .thenDeclareOptional(CLASS_REGISTRY_ACCESS) .optionalMethod(METHOD_REGISTRY_ACCESS_BUILTIN, "b").end() .optionalMethod(METHOD_REGISTRY_ACCESS_BUILTIN2, "a").end() // since 20w51a .requiredMethod(METHOD_REGISTRY_ACCESS_GET_REGISTRY, "b").symbolic(CLASS_REGISTRY_ACCESS_KEY).end() .next() .ifDetect(c -> c.searchForUtf8EqualTo("level-seed") && c.searchForUtf8EqualTo("generator-settings") ) .thenDeclareRequired(CLASS_WORLD_GEN_SETTINGS) .optionalMethod(METHOD_WORLD_GEN_SETTINGS_CREATE, "a").real("java.util.Properties").end() .optionalMethod(METHOD_WORLD_GEN_SETTINGS_CREATE2, "a").symbolic(CLASS_REGISTRY_ACCESS).real("java.util.Properties").end() .next() .ifDetect(c -> c.getNumberOfFields() == 7 && c.searchForUtf8EqualTo("overworld") && c.searchForUtf8EqualTo("the_nether") && c.searchForUtf8EqualTo("the_end") && c.searchForUtf8EqualTo("generator")) .thenDeclareOptional(CLASS_DIMENSION_SETTINGS) .requiredField(FIELD_DIMENSION_SETTINGS_GENERATOR, "g") .next() .ifDetect(c -> c.getRealClassName().contains("$") && c.getRealClassName().length() < 10 && c.isInterface() && (c.getNumberOfMethods() == 1 || c.getNumberOfMethods() == 2) && c.hasMethodWithRealArgsReturning("int", "int", "int", null) && !c.hasMethodWithRealArgsReturning("int", "int", "int", "boolean") ) .thenDeclareRequired(CLASS_NOISE_BIOME_PROVIDER) .requiredMethod(METHOD_NOISE_BIOME_PROVIDER_GET_BIOME, "b").real("int").real("int").real("int").end() .next() .ifDetect(c -> !c.getRealClassName().contains("$") && c.getRealSuperClassName().equals("java/lang/Enum") && c.hasMethodWithRealArgsReturning("long", "int", "int", "int", null, null) && !c.hasMethodWithRealArgsReturning("double", "double") ) .thenDeclareRequired(CLASS_BIOME_ZOOMER) .requiredMethod(METHOD_BIOME_ZOOMER_GET_BIOME, "a").real("long").real("int").real("int").real("int").symbolic(CLASS_NOISE_BIOME_PROVIDER).end() .next() .ifDetect(c -> (c.getNumberOfConstructors() == 1 || c.getNumberOfConstructors() == 2) && c.getNumberOfFields() > 0 && c.getField(0).hasFlags(AccessFlags.STATIC | AccessFlags.FINAL) && (c.searchForFloat(0.62222224F) || c.searchForUtf8EqualTo("Feature placement")) ) .thenDeclareRequired(CLASS_BIOME) .next() .ifDetect(c -> (c.searchForStringContaining("Server-Worker-") || c.searchForStringContaining("Worker-")) && c.searchForStringContaining("os.name") && c.searchForLong(1000000L) ) .thenDeclareOptional(CLASS_UTIL) .construct(); } // @formatter:on }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\local\LocalMinecraftInterface.java
package amidst.mojangapi.minecraftinterface.local; import java.lang.invoke.MethodHandle; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.EnumSet; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.function.Function; import amidst.clazz.symbolic.SymbolicClass; import amidst.clazz.symbolic.SymbolicObject; import amidst.logging.AmidstLogger; import amidst.mojangapi.minecraftinterface.MinecraftInterface; import amidst.mojangapi.minecraftinterface.MinecraftInterfaceException; import amidst.mojangapi.minecraftinterface.RecognisedVersion; import amidst.mojangapi.minecraftinterface.ReflectionUtils; import amidst.mojangapi.minecraftinterface.UnsupportedDimensionException; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.WorldOptions; import amidst.mojangapi.world.WorldType; import amidst.util.ArrayCache; public class LocalMinecraftInterface implements MinecraftInterface { private static final String STRING_WITH_ZERO_HASHCODE = "drumwood boulderhead"; private static final Set<Dimension> SUPPORTED_DIMENSIONS = Collections.unmodifiableSet(EnumSet.of(Dimension.OVERWORLD, Dimension.NETHER)); private boolean isInitialized = false; private final RecognisedVersion recognisedVersion; private final SymbolicClass registryClass; private final SymbolicClass registryAccessClass; private final SymbolicClass resourceKeyClass; private final SymbolicClass worldGenSettingsClass; private final SymbolicClass dimensionSettingsClass; private final SymbolicClass noiseBiomeProviderClass; private final SymbolicClass biomeZoomerClass; private final SymbolicClass utilClass; private final SymbolicClass bootstrapClass; private final SymbolicClass sharedConstantsClass; private MethodHandle registryGetIdMethod; private MethodHandle biomeProviderGetBiomeMethod; private MethodHandle biomeZoomerGetBiomeMethod; private Object registryAccess; // Default registry to use when creating worlds (after 20w28a) private Object biomeRegistry; private Object overworldResourceKey; private Object netherResourceKey; /** * An array used to return biome data */ private final ArrayCache<int[]> dataArray = ArrayCache.makeIntArrayCache(256); public LocalMinecraftInterface(Map<String, SymbolicClass> symbolicClassMap, RecognisedVersion recognisedVersion) { this.recognisedVersion = recognisedVersion; this.registryClass = symbolicClassMap.get(SymbolicNames.CLASS_REGISTRY); this.registryAccessClass = symbolicClassMap.get(SymbolicNames.CLASS_REGISTRY_ACCESS); this.resourceKeyClass = symbolicClassMap.get(SymbolicNames.CLASS_RESOURCE_KEY); this.worldGenSettingsClass = symbolicClassMap.get(SymbolicNames.CLASS_WORLD_GEN_SETTINGS); this.dimensionSettingsClass = symbolicClassMap.get(SymbolicNames.CLASS_DIMENSION_SETTINGS); this.noiseBiomeProviderClass = symbolicClassMap.get(SymbolicNames.CLASS_NOISE_BIOME_PROVIDER); this.biomeZoomerClass = symbolicClassMap.get(SymbolicNames.CLASS_BIOME_ZOOMER); this.utilClass = symbolicClassMap.get(SymbolicNames.CLASS_UTIL); this.bootstrapClass = symbolicClassMap.get(SymbolicNames.CLASS_BOOTSTRAP); this.sharedConstantsClass = symbolicClassMap.get(SymbolicNames.CLASS_SHARED_CONSTANTS); } @Override public synchronized MinecraftInterface.WorldAccessor createWorldAccessor(WorldOptions worldOptions) throws MinecraftInterfaceException { initializeIfNeeded(); try { long seed = worldOptions.getWorldSeed().getLong(); Object worldSettings = createWorldSettingsObject(seed, worldOptions.getWorldType(), worldOptions.getGeneratorOptions()).getObject(); Object overworldBiomeProvider; Object netherBiomeProvider; if (dimensionSettingsClass == null) { Map<?, ?> generators = (Map<?, ?>) ReflectionUtils.callParameterlessMethodReturning(worldSettings, Map.class); overworldBiomeProvider = getBiomesFromGeneratorsMap(generators, overworldResourceKey); netherBiomeProvider = getBiomesFromGeneratorsMap(generators, netherResourceKey); } else { Object dimensions = ReflectionUtils.callParameterlessMethodReturning(worldSettings, registryClass.getClazz()); overworldBiomeProvider = getBiomesFromDimensionRegistry(dimensions, overworldResourceKey); netherBiomeProvider = getBiomesFromDimensionRegistry(dimensions, netherResourceKey); } long seedForBiomeZoomer = makeSeedForBiomeZoomer(seed); Object biomeZoomer = biomeZoomerClass.getClazz().getEnumConstants()[0]; return new WorldAccessor(overworldBiomeProvider, netherBiomeProvider, biomeZoomer, seedForBiomeZoomer); } catch(RuntimeException | IllegalAccessException | InvocationTargetException e) { throw new MinecraftInterfaceException("unable to create world", e); } } private static long makeSeedForBiomeZoomer(long seed) throws MinecraftInterfaceException { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); ByteBuffer buf = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN); buf.putLong(seed); byte[] bytes = digest.digest(buf.array()); long result = 0; for (int i = 0; i < 8; i++) { result |= (bytes[i] & 0xffL) << (i*8L); } return result; } catch (NoSuchAlgorithmException e) { throw new MinecraftInterfaceException("unable to hash seed for biome zoomer", e); } } private SymbolicObject createWorldSettingsObject(long seed, WorldType worldType, String generatorOptions) throws IllegalAccessException, InvocationTargetException, MinecraftInterfaceException { Properties worldProperties = new Properties(); // Minecraft interprets "0" as a random seed, so provide a string hashing to 0 instead worldProperties.setProperty("level-seed", seed == 0 ? STRING_WITH_ZERO_HASHCODE : Long.toString(seed)); worldProperties.setProperty("level-type", getTrueWorldTypeName(worldType)); worldProperties.setProperty("generator-settings", generatorOptions); if (worldGenSettingsClass.hasMethod(SymbolicNames.METHOD_WORLD_GEN_SETTINGS_CREATE)) { return (SymbolicObject) worldGenSettingsClass.callStaticMethod( SymbolicNames.METHOD_WORLD_GEN_SETTINGS_CREATE, worldProperties); } else { Objects.requireNonNull(registryAccess); return (SymbolicObject) worldGenSettingsClass.callStaticMethod( SymbolicNames.METHOD_WORLD_GEN_SETTINGS_CREATE2, registryAccess, worldProperties); } } private Object getBiomesFromDimensionRegistry(Object dimensionRegistry, Object key) throws IllegalAccessException, InvocationTargetException, MinecraftInterfaceException { SymbolicObject registry = new SymbolicObject(registryClass, dimensionRegistry); SymbolicObject dimension = new SymbolicObject( dimensionSettingsClass, registry.callMethod(SymbolicNames.METHOD_REGISTRY_GET_BY_KEY, key) ); Object generator = dimension.getFieldValue(SymbolicNames.FIELD_DIMENSION_SETTINGS_GENERATOR); return ReflectionUtils.callParameterlessMethodReturning(generator, noiseBiomeProviderClass.getClazz()); } private Object getBiomesFromGeneratorsMap(Map<?, ?> generators, Object key) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, MinecraftInterfaceException { String stringKey = key.toString(); for (Map.Entry<?, ?> entry: generators.entrySet()) { if(stringKey.equals(entry.getKey().toString())) { return ReflectionUtils.callParameterlessMethodReturning(entry.getValue(), noiseBiomeProviderClass.getClazz()); } } return null; } private static String getTrueWorldTypeName(WorldType worldType) { switch (worldType) { case DEFAULT: return "default"; case FLAT: return "flat"; case AMPLIFIED: return "amplified"; case LARGE_BIOMES: return "largeBiomes"; case CUSTOMIZED: return "customized"; default: AmidstLogger.warn("Unsupported world type for this version: " + worldType); return ""; } } @Override public RecognisedVersion getRecognisedVersion() { return recognisedVersion; } private synchronized void initializeIfNeeded() throws MinecraftInterfaceException { if (isInitialized) { return; } try { // Since 21w14a, the registry classes check that the game is bootstrapped, // so toggle the relevant flag to make it so. // If this cause issues, we may need to actually bootstrap the game instead of faking it. bootstrapClass.getField(SymbolicNames.FIELD_BOOTSTRAP_IS_BOOTSTRAPPED) .getRawField().setBoolean(null, true); // Also since 21w14a, the Minecraft version needs to be detected manually. if (sharedConstantsClass != null) { sharedConstantsClass.callStaticMethod(SymbolicNames.METHOD_SHARED_CONSTANTS_DETECT_VERSION); } if (registryAccessClass == null) { registryAccess = null; biomeRegistry = getLegacyBiomeRegistry(); } else { Object key = ((SymbolicObject) registryClass .callStaticMethod(SymbolicNames.METHOD_REGISTRY_CREATE_KEY, "worldgen/biome")) .getObject(); // We don't use symbolic calls, because they are inconsistently wrapped in SymbolicObject. if (registryAccessClass.hasMethod(SymbolicNames.METHOD_REGISTRY_ACCESS_BUILTIN)) { registryAccess = registryAccessClass.getMethod(SymbolicNames.METHOD_REGISTRY_ACCESS_BUILTIN) .getRawMethod().invoke(null); } else { registryAccess = registryAccessClass.getMethod(SymbolicNames.METHOD_REGISTRY_ACCESS_BUILTIN2) .getRawMethod().invoke(null); } biomeRegistry = registryAccessClass.getMethod(SymbolicNames.METHOD_REGISTRY_ACCESS_GET_REGISTRY) .getRawMethod().invoke(registryAccess, key); biomeRegistry = Objects.requireNonNull(biomeRegistry); } stopAllExecutors(); registryGetIdMethod = ReflectionUtils.getMethodHandle(registryClass, SymbolicNames.METHOD_REGISTRY_GET_ID); biomeProviderGetBiomeMethod = ReflectionUtils.getMethodHandle(noiseBiomeProviderClass, SymbolicNames.METHOD_NOISE_BIOME_PROVIDER_GET_BIOME); biomeZoomerGetBiomeMethod = ReflectionUtils.getMethodHandle(biomeZoomerClass, SymbolicNames.METHOD_BIOME_ZOOMER_GET_BIOME); overworldResourceKey = createResourceKey("overworld"); netherResourceKey = createResourceKey("the_nether"); } catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new MinecraftInterfaceException("unable to initialize the MinecraftInterface", e); } isInitialized = true; } private Object getLegacyBiomeRegistry() throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, MinecraftInterfaceException { Object metaRegistry = registryClass.getStaticFieldValue(SymbolicNames.FIELD_REGISTRY_META_REGISTRY); if (!(metaRegistry instanceof SymbolicObject && ((SymbolicObject) metaRegistry).getType().equals(registryClass))) { // Oops, we called the wrong method String name = RecognisedVersion.isOlder(recognisedVersion, RecognisedVersion._1_16_pre1) ? SymbolicNames.FIELD_REGISTRY_META_REGISTRY2 : SymbolicNames.FIELD_REGISTRY_META_REGISTRY3; metaRegistry = registryClass.getStaticFieldValue(name); } return ((SymbolicObject) metaRegistry).callMethod( SymbolicNames.METHOD_REGISTRY_GET_BY_KEY, createResourceKey("biome")); } private void stopAllExecutors() throws IllegalArgumentException, IllegalAccessException { Class<?> clazz = utilClass.getClazz(); for (Field field: clazz.getDeclaredFields()) { if ((field.getModifiers() & Modifier.STATIC) > 0 && field.getType().equals(ExecutorService.class)) { field.setAccessible(true); ExecutorService exec = (ExecutorService) field.get(null); exec.shutdownNow(); } } } private Object createResourceKey(String key) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, MinecraftInterfaceException { return resourceKeyClass.callConstructor(SymbolicNames.CONSTRUCTOR_RESOURCE_KEY, key).getObject(); } private class WorldAccessor implements MinecraftInterface.WorldAccessor { /** * A BiomeProvider instance for the current overworld, giving * access to the quarter-scale biome data. */ private final Object overworldBiomeProvider; /** * A Biome provider instance for the current nether. */ private final Object netherBiomeProvider; /** * The BiomeZoomer instance for the current world, which * interpolates the quarter-scale BiomeProvider to give * full-scale biome data. */ private final Object biomeZoomer; /** * The seed used by the BiomeZoomer during interpolation. * It is derived from the world seed. */ private final long seedForBiomeZoomer; private WorldAccessor(Object overworldBiomeProvider, Object netherBiomeProvider, Object biomeZoomer, long seedForBiomeZoomer) { this.seedForBiomeZoomer = seedForBiomeZoomer; this.overworldBiomeProvider = Objects.requireNonNull(overworldBiomeProvider); this.netherBiomeProvider = Objects.requireNonNull(netherBiomeProvider); this.biomeZoomer = Objects.requireNonNull(biomeZoomer); } @Override public<T> T getBiomeData( Dimension dimension, int x, int y, int width, int height, boolean useQuarterResolution, Function<int[], T> biomeDataMapper) throws MinecraftInterfaceException { Object biomeProvider; int biomeHeight; switch (dimension) { case OVERWORLD: biomeProvider = this.overworldBiomeProvider; biomeHeight = 0; // The overworld uses y=0 for all heights break; case NETHER: biomeProvider = this.netherBiomeProvider; biomeHeight = 63; // Pick an arbitrary value break; default: throw new UnsupportedDimensionException(dimension); } int size = width * height; return dataArray.withArrayFaillible(size, data -> { try { if(size == 1) { data[0] = getBiomeIdAt(biomeProvider, biomeHeight, x, y, useQuarterResolution); return biomeDataMapper.apply(data); } /** * We break the region in 16x16 chunks, to get better performance out * of the LazyArea used by the game. This gives a ~2x improvement. */ int chunkSize = 16; for (int x0 = 0; x0 < width; x0 += chunkSize) { int w = Math.min(chunkSize, width - x0); for (int y0 = 0; y0 < height; y0 += chunkSize) { int h = Math.min(chunkSize, height - y0); for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { int trueIdx = (x0 + i) + (y0 + j) * width; data[trueIdx] = getBiomeIdAt(biomeProvider, biomeHeight, x + x0 + i, y + y0 + j, useQuarterResolution); } } } } } catch (Throwable e) { throw new MinecraftInterfaceException("unable to get biome data", e); } return biomeDataMapper.apply(data); }); } @Override public Set<Dimension> supportedDimensions() { return SUPPORTED_DIMENSIONS; } private int getBiomeIdAt(Object biomeProvider, int biomeHeight, int x, int y, boolean useQuarterResolution) throws Throwable { Object biome; if(useQuarterResolution) { biome = biomeProviderGetBiomeMethod.invokeExact(biomeProvider, x, biomeHeight, y); } else { biome = biomeZoomerGetBiomeMethod.invokeExact(biomeZoomer, seedForBiomeZoomer, x, biomeHeight, y, biomeProvider); } return (int) registryGetIdMethod.invokeExact(biomeRegistry, biome); } } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\local\SymbolicNames.java
package amidst.mojangapi.minecraftinterface.local; import amidst.documentation.Immutable; @Immutable public enum SymbolicNames { ; public static final String CLASS_SHARED_CONSTANTS = "SharedConstants"; public static final String METHOD_SHARED_CONSTANTS_DETECT_VERSION = "detectVersion"; public static final String CLASS_BOOTSTRAP = "Bootstrap"; public static final String FIELD_BOOTSTRAP_IS_BOOTSTRAPPED = "isBootstrapped"; public static final String CLASS_REGISTRY = "Registry"; public static final String FIELD_REGISTRY_META_REGISTRY = "metaRegistry"; public static final String FIELD_REGISTRY_META_REGISTRY2 = "metaRegistry2"; public static final String FIELD_REGISTRY_META_REGISTRY3 = "metaRegistry3"; public static final String METHOD_REGISTRY_CREATE_KEY = "createRegistryKey"; public static final String METHOD_REGISTRY_GET_BY_KEY = "getByKey"; public static final String METHOD_REGISTRY_GET_ID = "getId"; public static final String CLASS_REGISTRY_ACCESS = "RegistryAccess"; public static final String METHOD_REGISTRY_ACCESS_BUILTIN = "builtin"; public static final String METHOD_REGISTRY_ACCESS_BUILTIN2 = "builtin2"; public static final String METHOD_REGISTRY_ACCESS_GET_REGISTRY = "getRegistry"; public static final String CLASS_RESOURCE_KEY = "ResourceKey"; public static final String CONSTRUCTOR_RESOURCE_KEY = "<init>"; public static final String CLASS_REGISTRY_ACCESS_KEY = "RegistryKey"; public static final String CLASS_UTIL = "Util"; public static final String CLASS_WORLD_GEN_SETTINGS = "WorldGenSettings"; public static final String METHOD_WORLD_GEN_SETTINGS_CREATE = "create"; public static final String METHOD_WORLD_GEN_SETTINGS_CREATE2 = "create2"; public static final String CLASS_DIMENSION_SETTINGS = "DimensionSettings"; public static final String FIELD_DIMENSION_SETTINGS_GENERATOR = "generator"; public static final String CLASS_NOISE_BIOME_PROVIDER = "NoiseBiomeProvider"; public static final String METHOD_NOISE_BIOME_PROVIDER_GET_BIOME = "getBiome"; public static final String CLASS_BIOME_ZOOMER = "BiomeZoomer"; public static final String METHOD_BIOME_ZOOMER_GET_BIOME = "getBiome"; public static final String CLASS_BIOME = "Biome"; }
amidst
src\main\java\amidst\mojangapi\world\biome\Biome.java
package amidst.mojangapi.world.biome; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import amidst.documentation.Immutable; @Immutable public class Biome { public static final int SPECIAL_BIOMES_START = 128; public static List<Biome> getBiomeListFromIdList(BiomeList biomeList, List<Integer> idList) { return idList.stream().map(i -> biomeList.getByIdOrNull(i)).collect(Collectors.toList()); } public static Comparator<Integer> biomeIdComparator() { return (a,b) -> Integer.compare(Math.abs(a), Math.abs(b)); } private final int id; private final String name; private final BiomeType type; private final boolean isSpecialBiome; public Biome(String name, int baseId, BiomeType baseType) { this(baseId + SPECIAL_BIOMES_START, name, baseType.strengthen(), true); } public Biome(int id, String name, BiomeType type) { this(id, name, type, false); } public Biome(int id, String name, BiomeType type, boolean isSpecialBiome) { this.id = id; this.name = name; this.type = type; this.isSpecialBiome = isSpecialBiome; } public int getId() { return id; } public String getName() { return name; } public BiomeType getType() { return type; } public boolean isSpecialBiome() { return isSpecialBiome; } @Override public String toString() { return "[Biome " + name + "]"; } }
amidst
src\main\java\amidst\mojangapi\world\biome\BiomeColor.java
package amidst.mojangapi.world.biome; import java.awt.Color; import amidst.documentation.Immutable; import amidst.settings.biomeprofile.BiomeColorJson; @Immutable public class BiomeColor { public static BiomeColor from(int r, int g, int b) { return new BiomeColor(r, g, b); } public static BiomeColor unknown() { return UNKNOWN_BIOME_COLOR; } private static final BiomeColor UNKNOWN_BIOME_COLOR = new BiomeColor(0, 0, 0); private static final int HIDDEN_NUMBER = 30; private static final int LIGHTEN_BRIGHTNESS = 40; private final int r; private final int g; private final int b; private final int rgb; private final int hiddenRGB; private final Color color; private BiomeColor(int r, int g, int b) { this.r = r; this.g = g; this.b = b; this.rgb = createRGB(r, g, b); this.hiddenRGB = createHiddenRGB(r, g, b); this.color = new Color(r, g, b); } private int createRGB(int r, int g, int b) { int result = 0xFF000000; result |= 0xFF0000 & (r << 16); result |= 0xFF00 & (g << 8); result |= 0xFF & b; return result; } private int createHiddenRGB(int r, int g, int b) { int sum = r + g + b; return createRGB(hide(r, sum), hide(g, sum), hide(b, sum)); } private int hide(int x, int average) { return (x + average) / HIDDEN_NUMBER; } public int getR() { return r; } public int getG() { return g; } public int getB() { return b; } public int getRGB() { return rgb; } public int getHiddenRGB() { return hiddenRGB; } public Color getColor() { return color; } public BiomeColorJson createBiomeColorJson() { return new BiomeColorJson(r, g, b); } public BiomeColor createLightenedBiomeColor() { return BiomeColor.from(lighten(r), lighten(g), lighten(b)); } private int lighten(int x) { return Math.min(x + LIGHTEN_BRIGHTNESS, 0xFF); } }
amidst
src\main\java\amidst\mojangapi\world\biome\BiomeList.java
package amidst.mojangapi.world.biome; import java.util.Collection; import java.util.TreeMap; public class BiomeList { private TreeMap<Integer, Biome> biomes = new TreeMap<Integer, Biome>(Biome.biomeIdComparator()); private boolean isModifiable; public BiomeList() { this.isModifiable = true; } public BiomeList(Collection<Biome> biomes) { this(); for(Biome b : biomes) { this.biomes.put(b.getId(), b); } } public BiomeList(BiomeList other) { this(); this.biomes.putAll(other.biomes); } public Biome getByIdOrNull(int id) { return biomes.get(id); } public Biome getById(int id) throws UnknownBiomeIdException { Biome b = biomes.get(id); if (b != null) { return b; } throw new UnknownBiomeIdException("couldn't find biome with id " + id); } public Biome getBiomeFromName(String name) throws UnknownBiomeNameException { for (Biome biome : biomes.values()) { if (biome.getName().equals(name)) { return biome; } } throw new UnknownBiomeNameException("couldn't find biome with name " + name); } public boolean doesNameExist(String name) { for (Biome biome : biomes.values()) { if (biome.getName().equals(name)) { return true; } } return false; } public boolean doesIdExist(int id) { try { getById(id); return true; } catch (UnknownBiomeIdException e) { return false; } } public void add(Biome newBiome) { if (isModifiable) { biomes.put(newBiome.getId(), newBiome); } else { throw new UnsupportedOperationException("List is locked"); } } public Iterable<Biome> iterable() { return biomes.values(); } public int size() { return biomes.values().size(); } public static BiomeList construct(BiomeList biomeList) { biomeList.isModifiable = false; return biomeList; } }
amidst
src\main\java\amidst\mojangapi\world\biome\BiomeType.java
package amidst.mojangapi.world.biome; import amidst.documentation.Immutable; @Immutable public class BiomeType { // @formatter:off public static final BiomeType PLAINS = new BiomeType( 0.1F, 0.2F); public static final BiomeType RIVER = new BiomeType(-0.5F, 0.0F); public static final BiomeType OCEAN = new BiomeType(-1.0F, 0.1F); public static final BiomeType DEEP_OCEAN = new BiomeType(-1.8F, 0.1F); public static final BiomeType PLAINS_FLAT = new BiomeType( 0.125F, 0.05F); public static final BiomeType PLAINS_TAIGA = new BiomeType( 0.2F, 0.2F); public static final BiomeType HILLS = new BiomeType( 0.45F, 0.3F); public static final BiomeType PLATEAU = new BiomeType( 1.5F, 0.025F); public static final BiomeType MOUNTAINS = new BiomeType( 1.0F, 0.5F); public static final BiomeType BEACH = new BiomeType( 0.0F, 0.025F); public static final BiomeType BEACH_CLIFFS = new BiomeType( 0.1F, 0.8F); public static final BiomeType ISLAND = new BiomeType( 0.2F, 0.3F); public static final BiomeType SWAMPLAND = new BiomeType(-0.2F, 0.1F); // @formatter:on private final float biomeDepth; private final float biomeFactor; public BiomeType(float biomeDepth, float biomeFactor) { this.biomeDepth = biomeDepth; this.biomeFactor = biomeFactor; } public BiomeType weaken() { return new BiomeType(biomeDepth * 0.8F, biomeFactor * 0.6F); } public BiomeType strengthen() { return new BiomeType(biomeDepth + 0.1F, biomeFactor + 0.2F); } public float getBiomeDepth() { return biomeDepth; } public float getBiomeFactor() { return biomeFactor; } }
amidst
src\main\java\amidst\mojangapi\world\biome\UnknownBiomeIdException.java
package amidst.mojangapi.world.biome; import amidst.documentation.Immutable; @Immutable public class UnknownBiomeIdException extends Exception { private static final long serialVersionUID = -1477769755204737332L; public UnknownBiomeIdException(String message) { super(message); } }
amidst
src\main\java\amidst\mojangapi\world\biome\UnknownBiomeNameException.java
package amidst.mojangapi.world.biome; import amidst.documentation.Immutable; @Immutable public class UnknownBiomeNameException extends Exception { private static final long serialVersionUID = 3034394814256519917L; public UnknownBiomeNameException(String message) { super(message); } }
amidst
src\main\java\amidst\mojangapi\world\coordinates\CoordinatesInWorld.java
package amidst.mojangapi.world.coordinates; import java.awt.Point; import amidst.documentation.Immutable; @Immutable public class CoordinatesInWorld implements Comparable<CoordinatesInWorld> { public static CoordinatesInWorld tryParse(String coordinates) { String[] parsedCoordinates = coordinates.replaceAll(" ", "").split(","); if (parsedCoordinates.length != 2) { return null; } try { return CoordinatesInWorld.from(Long.parseLong(parsedCoordinates[0]), Long.parseLong(parsedCoordinates[1])); } catch (NumberFormatException e) { return null; } } public static CoordinatesInWorld from(long xInWorld, long yInWorld) { return new CoordinatesInWorld(xInWorld, yInWorld); } public static CoordinatesInWorld from(long xAsResolution, long yAsResolution, Resolution resolution) { return new CoordinatesInWorld( resolution.convertFromThisToWorld(xAsResolution), resolution.convertFromThisToWorld(yAsResolution)); } private static CoordinatesInWorld from(CoordinatesInWorld base, long deltaXInWorld, long deltaYInWorld) { return new CoordinatesInWorld(base.xInWorld + deltaXInWorld, base.yInWorld + deltaYInWorld); } public static CoordinatesInWorld origin() { return ORIGIN; } private static final CoordinatesInWorld ORIGIN = CoordinatesInWorld.from(0, 0); private final long xInWorld; private final long yInWorld; public CoordinatesInWorld(long xInWorld, long yInWorld) { this.xInWorld = xInWorld; this.yInWorld = yInWorld; } public long getX() { return xInWorld; } public long getY() { return yInWorld; } public long getXAs(Resolution targetResolution) { return targetResolution.convertFromWorldToThis(xInWorld); } public long getYAs(Resolution targetResolution) { return targetResolution.convertFromWorldToThis(yInWorld); } public long getXCornerOfFragment() { return CoordinateUtils.toFragmentCorner(xInWorld); } public long getYCornerOfFragment() { return CoordinateUtils.toFragmentCorner(yInWorld); } public long getXCornerOfFragmentAs(Resolution targetResolution) { return targetResolution.convertFromWorldToThis(CoordinateUtils.toFragmentCorner(xInWorld)); } public long getYCornerOfFragmentAs(Resolution targetResolution) { return targetResolution.convertFromWorldToThis(CoordinateUtils.toFragmentCorner(yInWorld)); } public long getXRelativeToFragment() { return CoordinateUtils.toFragmentRelative(xInWorld); } public long getYRelativeToFragment() { return CoordinateUtils.toFragmentRelative(yInWorld); } public long getXRelativeToFragmentAs(Resolution targetResolution) { return targetResolution.convertFromWorldToThis(CoordinateUtils.toFragmentRelative(xInWorld)); } public long getYRelativeToFragmentAs(Resolution targetResolution) { return targetResolution.convertFromWorldToThis(CoordinateUtils.toFragmentRelative(yInWorld)); } public CoordinatesInWorld toFragmentCorner() { return from(getXCornerOfFragment(), getYCornerOfFragment()); } public double getDistance(CoordinatesInWorld other) { return Point.distance(xInWorld, yInWorld, other.xInWorld, other.yInWorld); } public double getDistance(long xInWorld, long yInWorld) { return Point.distance(this.xInWorld, this.yInWorld, xInWorld, yInWorld); } public double getDistanceSq(CoordinatesInWorld other) { return Point.distanceSq(xInWorld, yInWorld, other.xInWorld, other.yInWorld); } public double getDistanceSq(long xInWorld, long yInWorld) { return Point.distanceSq(this.xInWorld, this.yInWorld, xInWorld, yInWorld); } public long getDistanceChebyshev(CoordinatesInWorld other) { return Math.max(Math.abs(xInWorld - other.xInWorld), Math.abs(yInWorld - other.yInWorld)); } public long getDistanceChebyshev(long xInWorld, long yInWorld) { return Math.max(Math.abs(this.xInWorld - xInWorld), Math.abs(this.yInWorld - yInWorld)); } public CoordinatesInWorld add(CoordinatesInWorld other) { return add(other.xInWorld, other.yInWorld); } public CoordinatesInWorld add(long xInWorld, long yInWorld) { return from(this, xInWorld, yInWorld); } public CoordinatesInWorld substract(CoordinatesInWorld other) { return substract(other.xInWorld, other.yInWorld); } public CoordinatesInWorld substract(long xInWorld, long yInWorld) { return from(this, -xInWorld, -yInWorld); } public boolean isInBoundsOf(CoordinatesInWorld corner, long size) { return CoordinateUtils.isInBounds(xInWorld, yInWorld, corner.xInWorld, corner.yInWorld, size, size); } @Override public int compareTo(CoordinatesInWorld o) { if (this == o) { return 0; } else if (this.xInWorld < o.xInWorld) { return -1; } else if (this.xInWorld > o.xInWorld) { return 1; } else if (this.yInWorld < o.yInWorld) { return -1; } else if (this.yInWorld > o.yInWorld) { return 1; } else { return 0; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (xInWorld ^ (xInWorld >>> 32)); result = prime * result + (int) (yInWorld ^ (yInWorld >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof CoordinatesInWorld)) { return false; } CoordinatesInWorld other = (CoordinatesInWorld) obj; if (xInWorld != other.xInWorld) { return false; } if (yInWorld != other.yInWorld) { return false; } return true; } @Override public String toString() { return "[" + xInWorld + ", " + yInWorld + "]"; } public String toString(Resolution resolution) { return "[" + getXAs(resolution) + ", " + getYAs(resolution) + "]"; } }
amidst
src\main\java\amidst\mojangapi\world\coordinates\CoordinateUtils.java
package amidst.mojangapi.world.coordinates; import amidst.documentation.Immutable; import amidst.fragment.Fragment; @Immutable public enum CoordinateUtils { ; public static boolean isInBounds(long x, long y, long offsetX, long offsetY, long width, long height) { return x >= offsetX && x < offsetX + width && y >= offsetY && y < offsetY + height; } /** * @return world coordinates relative to its fragment corner (corrected * modulo) */ public static long toFragmentRelative(long inWorld) { return modulo(inWorld, Fragment.SIZE); } /** * @return world coordinates (addition) */ public static long toWorld(long inWorldOfFragment, long inFragment) { return inWorldOfFragment + inFragment; } /** * @return world coordinates of the corner of the given coordinates fragment */ public static long toFragmentCorner(long inWorld) { return inWorld - modulo(inWorld, Fragment.SIZE); } private static long modulo(long a, long b) { return ((a % b) + b) % b; } }
amidst
src\main\java\amidst\mojangapi\world\coordinates\Resolution.java
package amidst.mojangapi.world.coordinates; import amidst.documentation.Immutable; @Immutable public enum Resolution { WORLD(0), QUARTER(2), NETHER(3), CHUNK(4), NETHER_CHUNK(7), FRAGMENT(9); public static Resolution from(boolean useQuarterResolution) { if (useQuarterResolution) { return Resolution.QUARTER; } else { return Resolution.WORLD; } } private final int shift; private Resolution(int shift) { this.shift = shift; } public int getStep() { return 1 << shift; } public int getStepsPerFragment() { return 1 << (FRAGMENT.shift - shift); } public long convertFromWorldToThis(long coordinateInWorld) { return coordinateInWorld >> shift; } public long convertFromThisToWorld(long coordinateInThisResolution) { return coordinateInThisResolution << shift; } }
amidst
src\main\java\amidst\mojangapi\world\filter\WorldFilter.java
package amidst.mojangapi.world.filter; import amidst.documentation.Immutable; import amidst.fragment.Fragment; import amidst.mojangapi.world.World; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.coordinates.Resolution; @Immutable public abstract class WorldFilter { protected final long worldFilterSize; protected final long quarterFilterSize; protected final CoordinatesInWorld corner; public WorldFilter(long worldFilterSize) { ensureIsMultipleOfFragmentSize(worldFilterSize); this.worldFilterSize = worldFilterSize; this.quarterFilterSize = Resolution.QUARTER.convertFromWorldToThis(this.worldFilterSize); this.corner = new CoordinatesInWorld(-this.worldFilterSize, -this.worldFilterSize); } /** * Structure filters check spaces in fragment size, so filter distance not a * multiple of fragment size will include more area in the filter than * expected */ private void ensureIsMultipleOfFragmentSize(long worldFilterSize) { if (worldFilterSize % Fragment.SIZE != 0) { throw new IllegalArgumentException("World filter size must be a multiple of " + Fragment.SIZE); } } public abstract boolean isValid(World world); }
amidst
src\main\java\amidst\mojangapi\world\filter\WorldFilter_Biome.java
package amidst.mojangapi.world.filter; import java.util.Set; import amidst.documentation.NotThreadSafe; import amidst.mojangapi.world.World; @NotThreadSafe public class WorldFilter_Biome extends WorldFilter { private final Set<Short> validBiomeIndexes; public WorldFilter_Biome(long worldFilterSize, Set<Short> validBiomeIndexes) { super(worldFilterSize); this.validBiomeIndexes = validBiomeIndexes; } @Override public boolean isValid(World world) { int size = (int) (this.quarterFilterSize * 2); return world.getOverworldBiomeDataOracle().getBiomeData(corner, size, size, true, data -> { for (int biome: data) { if (validBiomeIndexes.contains((short) biome)) { return true; } } return false; }, () -> false); } }
amidst
src\main\java\amidst\mojangapi\world\filter\WorldFilter_MatchAll.java
package amidst.mojangapi.world.filter; import java.util.List; import amidst.documentation.Immutable; import amidst.mojangapi.world.World; @Immutable public class WorldFilter_MatchAll extends WorldFilter { private final List<WorldFilter> filters; public WorldFilter_MatchAll(long worldFilterSize, List<WorldFilter> filters) { super(worldFilterSize); this.filters = filters; } @Override public boolean isValid(World world) { for (WorldFilter filter : filters) { if (!filter.isValid(world)) { return false; } } return true; } }
amidst
src\main\java\amidst\mojangapi\world\filter\WorldFilter_Structure.java
package amidst.mojangapi.world.filter; import amidst.documentation.Immutable; import amidst.mojangapi.world.World; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.icon.producer.NameFilteredWorldIconCollector; import amidst.mojangapi.world.icon.producer.WorldIconCollector; import amidst.mojangapi.world.icon.producer.WorldIconProducer; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; @Immutable public class WorldFilter_Structure extends WorldFilter { private final DefaultWorldIconTypes structure; private final int count; public WorldFilter_Structure(long worldFilterSize, DefaultWorldIconTypes structure, int count) { super(worldFilterSize); this.structure = structure; this.count = count; } @Override public boolean isValid(World world) { WorldIconCollector structureCollector = getCollector(); procudeAndCollect(getProducer(world), structureCollector); return structureCollector.get().size() > count; } private void procudeAndCollect(WorldIconProducer<Void> structureProducer, WorldIconCollector structureCollector) { for (long x = 0; x < 2 * worldFilterSize; x += 512) { for (long y = 0; y < 2 * worldFilterSize; y += 512) { structureProducer.produce(CoordinatesInWorld.from(x, y).add(corner), structureCollector, null); } } } private WorldIconProducer<Void> getProducer(World world) { switch (structure) { case JUNGLE: case DESERT: case IGLOO: case WITCH: return world.getTempleProducer(); case STRONGHOLD: return world.getStrongholdProducer(); case VILLAGE: return world.getVillageProducer(); case OCEAN_MONUMENT: return world.getOceanMonumentProducer(); case MINESHAFT: return world.getMineshaftProducer(); default: throw new IllegalArgumentException("Unsupported structure type: " + structure.getName()); } } private WorldIconCollector getCollector() { switch (structure) { case JUNGLE: case DESERT: case IGLOO: case WITCH: return new NameFilteredWorldIconCollector(structure.getName()); case STRONGHOLD: case VILLAGE: case OCEAN_MONUMENT: case MINESHAFT: return new WorldIconCollector(); default: throw new IllegalArgumentException("Unsupported structure type: " + structure.getName()); } } }
amidst
src\main\java\amidst\mojangapi\world\icon\WorldIcon.java
package amidst.mojangapi.world.icon; import amidst.documentation.Immutable; import amidst.documentation.NotNull; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.coordinates.Resolution; @Immutable public class WorldIcon { private final CoordinatesInWorld coordinates; private final String name; private final WorldIconImage image; private final Dimension dimension; private final boolean displayDimension; public WorldIcon( CoordinatesInWorld coordinates, String name, WorldIconImage image, Dimension dimension, boolean displayDimension) { this.coordinates = coordinates; this.name = name; this.image = image; this.dimension = dimension; this.displayDimension = displayDimension; } public CoordinatesInWorld getCoordinates() { return coordinates; } public String getName() { return name; } public WorldIconImage getImage() { return image; } public Dimension getDimension() { return dimension; } @Override @NotNull public String toString() { return toString(false); } @NotNull public String toString(boolean multiline) { if (dimension.getResolution() != Resolution.WORLD) { if (multiline) { // @formatter:off return name + "\n in the " + dimension.getDisplayName() + " " + coordinates.toString(dimension.getResolution()) + "\n in the Overworld " + coordinates.toString(); // @formatter:on } else { return name + " in the " + dimension.getDisplayName() + " " + coordinates.toString(dimension.getResolution()) + " -> " + coordinates.toString() + " in the Overworld"; } } else if (displayDimension) { return name + " in the " + dimension.getDisplayName() + " " + coordinates.toString(); } else { return name + " " + coordinates.toString(); } } }
amidst
src\main\java\amidst\mojangapi\world\icon\WorldIconImage.java
package amidst.mojangapi.world.icon; import java.awt.image.BufferedImage; import amidst.documentation.Immutable; /** * Provides the "frame" information for images employing an "Out of Frame" * visual effect (see http://www.google.com.au/search?q=out+of+frame&tbm=isch) * such as the question mark in the Possible End City icon, or the chin of the * Village icon. */ @Immutable public class WorldIconImage { public static WorldIconImage from(BufferedImage image) { return new WorldIconImage(image, 0, 0, image.getWidth(), image.getHeight()); } /** * Use pixel transparency along the left edge of the icon to automatically * determine the vertical frame position. Assumes the image has no * horizontal out of frame effects. * * If you want transparency on the left side of the image without adjusting * its frame, or if you want to control where the frame starts, use a pixel * that is mostly transparent. (Spawn.png and Witch.png do this) */ public static WorldIconImage fromPixelTransparency(BufferedImage image) { int imageMarginTop = findFirstSolidPixelFromTop(image); int imageMarginBottom = findFirstSolidPixelFromBottom(image); int frameHeight = Math.max(0, image.getHeight() - imageMarginTop - imageMarginBottom); return new WorldIconImage(image, 0, imageMarginTop, image.getWidth(), frameHeight); } private static int findFirstSolidPixelFromTop(BufferedImage image) { int height = image.getHeight(); return findFirstSolidPixel(image, height, 0, 1); } private static int findFirstSolidPixelFromBottom(BufferedImage image) { int height = image.getHeight(); return findFirstSolidPixel(image, height, height - 1, -1); } private static int findFirstSolidPixel(BufferedImage image, int height, int initialY, int deltaY) { int y = initialY; for (int i = 0; i < height; i++) { if (isNonTransparent(image, 0, y)) { return i; } y += deltaY; } // icon is not full width, it may be using a padded image size to // indicate its effective size instead. return 0; } private static boolean isNonTransparent(BufferedImage image, int x, int y) { return (image.getRGB(x, y) >>> 24) > 0; } private final BufferedImage image; private final int frameOffsetX; private final int frameOffsetY; private final int frameWidth; private final int frameHeight; public WorldIconImage(BufferedImage image, int frameOffsetX, int frameOffsetY, int frameWidth, int frameHeight) { this.image = image; this.frameOffsetX = frameOffsetX; this.frameOffsetY = frameOffsetY; this.frameWidth = frameWidth; this.frameHeight = frameHeight; } public BufferedImage getImage() { return image; } /** * Returns 0 if nothing is extending left or right of the frame. */ public int getFrameOffsetX() { return frameOffsetX; } /** * Returns 0 if nothing is extending above or below the frame. */ public int getFrameOffsetY() { return frameOffsetY; } /** * Returns the width of the icon "frame", ignoring any parts of the icon * which might extend beyond the icon's border for an "Out of Frame" visual * effect. Returns the image width if nothing is extending left or right of * the frame. */ public int getFrameWidth() { return frameWidth; } /** * Returns the height of the icon "frame", ignoring any parts of the icon * which might extend beyond the icon's border for an "Out of Frame" visual * effect. Returns the image height if nothing is extending above or below * the frame. */ public int getFrameHeight() { return frameHeight; } }
amidst
src\main\java\amidst\mojangapi\world\oracle\BiomeDataOracle.java
package amidst.mojangapi.world.oracle; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import amidst.documentation.ThreadSafe; import amidst.logging.AmidstLogger; import amidst.logging.AmidstMessageBox; import amidst.mojangapi.minecraftinterface.MinecraftInterface; import amidst.mojangapi.minecraftinterface.MinecraftInterfaceException; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.biome.BiomeList; import amidst.mojangapi.world.biome.UnknownBiomeIdException; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.coordinates.Resolution; import amidst.util.FastRand; @ThreadSafe public class BiomeDataOracle { private final MinecraftInterface.WorldAccessor worldAccessor; private final Dimension dimension; private final BiomeList biomeList; private final boolean quarterResOverride; private final int middleOfChunkOffset; private final boolean accurateLocationCount; public static class Config { public boolean quarterResOverride = true; public int middleOfChunkOffset = 9; public boolean accurateLocationCount = true; } public BiomeDataOracle(MinecraftInterface.WorldAccessor worldAccessor, Dimension dimension, BiomeList biomeList, Config config) { this.worldAccessor = worldAccessor; this.dimension = dimension; this.biomeList = biomeList; this.quarterResOverride = config.quarterResOverride; this.middleOfChunkOffset = config.middleOfChunkOffset; this.accurateLocationCount = config.accurateLocationCount; } public void getBiomeData(CoordinatesInWorld corner, int width, int height, boolean useQuarterResolution, Consumer<int[]> biomeDataConsumer) { getBiomeData(corner, width, height, useQuarterResolution, data -> { biomeDataConsumer.accept(data); return null; }, () -> null); } // Pass biome data to the mapper as a row-major int array; or return the default value if an error occured. // width and height represent the number of samples, NOT the size of the region in the world. public<T> T getBiomeData(CoordinatesInWorld corner, int width, int height, boolean useQuarterResolution, Function<int[], T> biomeDataMapper, Supplier<T> defaultValue) { Resolution resolution = Resolution.from(useQuarterResolution); int left = (int) corner.getXAs(resolution); int top = (int) corner.getYAs(resolution); try { return worldAccessor.getBiomeData(dimension, left, top, width, height, useQuarterResolution, biomeDataMapper); } catch (MinecraftInterfaceException e) { AmidstLogger.error(e); AmidstMessageBox.displayError("Error", e); return defaultValue.get(); } } public boolean isValidBiomeAtMiddleOfChunk(int chunkX, int chunkY, List<Biome> validBiomes) { return isValidBiome(getMiddleOfChunk(chunkX), getMiddleOfChunk(chunkY), validBiomes); } private boolean isValidBiome(int x, int y, List<Biome> validBiomes) { try { if(quarterResOverride) { return validBiomes.contains(getBiomeAt(x >> 2, y >> 2, true)); } else { return validBiomes.contains(getBiomeAt(x, y, false)); } } catch (UnknownBiomeIdException | MinecraftInterfaceException e) { AmidstLogger.error(e); AmidstMessageBox.displayError("Error", e); return false; } } public boolean isValidBiomeForStructureAtMiddleOfChunk(int chunkX, int chunkY, int size, List<Biome> validBiomes) { //FIXME: 1.16 changed to quarter res? return isValidBiomeForStructure(getMiddleOfChunk(chunkX), getMiddleOfChunk(chunkY), size, validBiomes); } public boolean isValidBiomeForStructure(int x, int y, int size, List<Biome> validBiomes) { int left = x - size >> 2; int top = y - size >> 2; int right = x + size >> 2; int bottom = y + size >> 2; int width = right - left + 1; int height = bottom - top + 1; try { return getQuarterResolutionBiomeData(left, top, width, height, biomeData -> { for (int i = 0; i < width * height; i++) { Biome biome = biomeList.getByIdOrNull(biomeData[i]); if (!validBiomes.contains(biome)) { return false; } } return true; }); } catch (MinecraftInterfaceException e) { AmidstLogger.error(e); AmidstMessageBox.displayError("Error", e); return false; } } public CoordinatesInWorld findValidLocationAtMiddleOfChunk( int chunkX, int chunkY, int size, List<Biome> validBiomes, FastRand random) { return findValidLocation(getMiddleOfChunk(chunkX), getMiddleOfChunk(chunkY), size, validBiomes, random); } public CoordinatesInWorld findValidLocation(int x, int y, int size, List<Biome> validBiomes, FastRand random) { return doFindValidLocation(x, y, size, validBiomes, random, accurateLocationCount); } // This algorithm slightly changed in the 1.13 snapshots: before, // numberOfValidLocations was only incremented if the random check // succeeded; it is now always incremented. private CoordinatesInWorld doFindValidLocation( int x, int y, int size, List<Biome> validBiomes, FastRand random, boolean accurateLocationCount) { int left = x - size >> 2; int top = y - size >> 2; int right = x + size >> 2; int bottom = y + size >> 2; int width = right - left + 1; int height = bottom - top + 1; try { return getQuarterResolutionBiomeData(left, top, width, height, biomeData -> { CoordinatesInWorld result = null; int numberOfValidLocations = 0; for (int i = 0; i < width * height; i++) { Biome biome = biomeList.getByIdOrNull(biomeData[i]); if (validBiomes.contains(biome)) { boolean updateResult = result == null || random.nextInt(numberOfValidLocations + 1) == 0; result = updateResult ? createCoordinates(left, top, width, i) : result; if(accurateLocationCount || updateResult) { numberOfValidLocations++; } } } return result; }); } catch (MinecraftInterfaceException e) { AmidstLogger.error(e); AmidstMessageBox.displayError("Error", e); return null; } } private CoordinatesInWorld createCoordinates(int left, int top, int width, int i) { int x = left + i % width << 2; int y = top + i / width << 2; return CoordinatesInWorld.from(x, y); } private int getMiddleOfChunk(int chunkCoord) { return (chunkCoord << 4) + middleOfChunkOffset; } public Biome getBiomeAtMiddleOfChunk(int chunkX, int chunkY) throws UnknownBiomeIdException, MinecraftInterfaceException { return getBiomeAt(getMiddleOfChunk(chunkX), getMiddleOfChunk(chunkY), quarterResOverride); } public Biome getBiomeAt(int x, int y, boolean useQuarterResolution) throws UnknownBiomeIdException, MinecraftInterfaceException { int biomeIndex = worldAccessor.getBiomeData(dimension, x, y, 1, 1, useQuarterResolution, biomeData -> biomeData[0]); return biomeList.getById(biomeIndex); } private<T> T getQuarterResolutionBiomeData(int x, int y, int width, int height, Function<int[], T> biomeDataMapper) throws MinecraftInterfaceException { return worldAccessor.getBiomeData(dimension, x, y, width, height, true, biomeDataMapper); } }
amidst
src\main\java\amidst\mojangapi\world\oracle\EndIsland.java
package amidst.mojangapi.world.oracle; import amidst.documentation.Immutable; // TODO: check sign of differences ... (this.chunkX - chunkX) vs (chunkX - this.chunkX) @Immutable public class EndIsland { private static final int X_ADJUSTMENT = 1; private static final int Y_ADJUSTMENT = 1; private final int chunkX; private final int chunkY; private final float erosionFactor; protected EndIsland(int chunkX, int chunkY, float erosionFactor) { this.chunkX = chunkX; this.chunkY = chunkY; this.erosionFactor = erosionFactor; } /** * Retuns a value between 80 and -100 which indicates this island's * influence at the block coordindates given. A non-negative value indicates * there will be solid ground, while a negative value indicates the * rocky-island-shore, which might be solid ground (but that becomes less * likely the lower the value). */ public float influenceAtBlock(int x, int y) { // Add 8 blocks to both axis because all the Minecraft calculations are // done using chunk coordinates and are converted as being the center of // the chunk whenever translated to block coordinates, whereas Amidst // treats chunk coords as blockCoordinates >> 4. // This function also does a floating point divide by 16 instead of // shifting by 4 in order to maintain sub-chunk accuracy with x & y. float chunkX = (x + 8) / 16.0f; float chunkY = (y + 8) / 16.0f; float adjustedX = (this.chunkX - chunkX) * 2 + X_ADJUSTMENT; float adjustedY = (this.chunkY - chunkY) * 2 + Y_ADJUSTMENT; return getResult(adjustedX * adjustedX + adjustedY * adjustedY); } /** * A version of influenceAt() that more exactly adheres to Minecraft's * algorithm, for use in testing for End Cities. */ public float influenceAtChunk(int chunkX, int chunkY) { int adjustedX = (chunkX - this.chunkX) * 2 + X_ADJUSTMENT; int adjustedY = (chunkY - this.chunkY) * 2 + Y_ADJUSTMENT; return getResult(adjustedX * adjustedX + adjustedY * adjustedY); } private float getResult(double squared) { float result = 100.0f - (float) Math.sqrt(squared) * erosionFactor; if (result > 80.0f) { return 80.0f; } else if (result < -100.0f) { return -100.0f; } else { return result; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + chunkX; result = prime * result + chunkY; result = prime * result + Float.floatToIntBits(erosionFactor); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof EndIsland)) { return false; } EndIsland other = (EndIsland) obj; if (chunkX != other.chunkX) { return false; } if (chunkY != other.chunkY) { return false; } if (Float.floatToIntBits(erosionFactor) != Float.floatToIntBits(other.erosionFactor)) { return false; } return true; } }
amidst
src\main\java\amidst\mojangapi\world\oracle\EndIslandOracle.java
package amidst.mojangapi.world.oracle; import java.util.LinkedList; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.coordinates.Resolution; import amidst.util.FastRand; @ThreadSafe public class EndIslandOracle { public static EndIslandOracle from(long seed) { return new EndIslandOracle(createNoiseFunction(seed)); } /** * Returns the noise function using the current seed. */ private static SimplexNoise createNoiseFunction(long seed) { FastRand random = new FastRand(seed); fakePerlin3dOctavesConstructor(random, 16); fakePerlin3dOctavesConstructor(random, 16); fakePerlin3dOctavesConstructor(random, 8); fakePerlin3dOctavesConstructor(random, 10); fakePerlin3dOctavesConstructor(random, 16); return new SimplexNoise(random); } /** * Mimics the side-effects to the random number generator caused by * constructing a Perlin3dOctaves instance. */ private static void fakePerlin3dOctavesConstructor(FastRand random, int octaveCount) { for (int i = 0; i < octaveCount; i++) { fakePerlin3dConstructor(random); } } /** * Mimics the side-effects to the random number generator caused by * constructing a Perlin3d instance. */ private static void fakePerlin3dConstructor(FastRand random) { random.nextDouble(); random.nextDouble(); random.nextDouble(); for (int i = 0; i < 256; i++) { random.nextInt(256 - i); } } /** * Minecraft checks 12 chunks either side of a chunk when assessing island * influence. */ private static final int SURROUNDING_CHUNKS = 12; /** * When cast to double, -0.9 will become -0.8999999761581421, which is why * you might see that value in Minecraft's .jar */ private static final float ISLAND_DENSITY_THRESHOLD = -0.9f; /** * The distance from (0;0) at which islands start to generated */ private static final int OUTER_LANDS_DISTANCE_IN_CHUNKS = 64; private final SimplexNoise noiseFunction; public EndIslandOracle(SimplexNoise noiseFunction) { this.noiseFunction = noiseFunction; } public List<EndIsland> getAt(CoordinatesInWorld corner) { int steps = Resolution.CHUNK.getStepsPerFragment(); return findSurroundingIslands( (int) corner.getXAs(Resolution.CHUNK), (int) corner.getYAs(Resolution.CHUNK), steps, steps); } /** * Returns a list of all islands that might be touching a chunk-area. */ private List<EndIsland> findSurroundingIslands( int chunkX, int chunkY, int chunksPerFragmentX, int chunksPerFragmentY) { List<EndIsland> result = new LinkedList<>(); for (int y = -SURROUNDING_CHUNKS; y <= chunksPerFragmentY + SURROUNDING_CHUNKS; y++) { for (int x = -SURROUNDING_CHUNKS; x <= chunksPerFragmentX + SURROUNDING_CHUNKS; x++) { EndIsland island = tryCreateEndIsland(chunkX + x, chunkY + y); if (island != null) { result.add(island); } } } return result; } /** * Returns an EndIsland if one has 'grown out' from the chunk, otherwise * null */ private EndIsland tryCreateEndIsland(int chunkX, int chunkY) { if (chunkX == 0 && chunkY == 0) { return createMainEndIsland(chunkX, chunkY); } else if (!isInRange(chunkX, chunkY, OUTER_LANDS_DISTANCE_IN_CHUNKS)) { return tryCreateEndIslandInOuterLands(chunkX, chunkY); } else { return null; } } /** * The main island grows from the origin, with a hard-coded erosion factor * of 8 */ private EndIsland createMainEndIsland(int chunkX, int chunkY) { return new EndIsland(chunkX, chunkY, 8.0f); } /** * The chunk is in the outer-islands band */ // TODO: check for threading, do we need synchonized or is the SimplexNoise // class thread safe? private synchronized EndIsland tryCreateEndIslandInOuterLands(int chunkX, int chunkY) { if (noiseFunction.noise(chunkX, chunkY) < ISLAND_DENSITY_THRESHOLD) { return new EndIsland(chunkX, chunkY, getErosionFactor(chunkX, chunkY)); } else { return null; } } /** * An island (or part of an island) grows out from this chunk, with an * erosion factor between 9 and 21 (i.e. they will be smaller than the main * island). */ private int getErosionFactor(int chunkX, int chunkY) { // Convert coordinates to long to guard against overflow return (int) ((Math.abs((long) chunkX) * 3439 + Math.abs((long) chunkY) * 147) % 13 + 9); } /** * Is the point (x, y) inside the disk of radius d centered at the origin? */ private boolean isInRange(int x, int y, int d) { // Guard against overflow if (x < -d || x > d || y < -d || y > d) return false; return x * x + y * y <= d * d; } }
amidst
src\main\java\amidst\mojangapi\world\oracle\HeuristicWorldSpawnOracle.java
package amidst.mojangapi.world.oracle; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.util.FastRand; @ThreadSafe public class HeuristicWorldSpawnOracle implements WorldSpawnOracle { private final long seed; private final BiomeDataOracle biomeDataOracle; private final List<Biome> validBiomes; public HeuristicWorldSpawnOracle(long seed, BiomeDataOracle biomeDataOracle, List<Biome> validBiomes) { this.seed = seed; this.biomeDataOracle = biomeDataOracle; this.validBiomes = validBiomes; } @Override public CoordinatesInWorld get() { return biomeDataOracle.findValidLocation(0, 0, 256, validBiomes, new FastRand(seed)); } }
amidst
src\main\java\amidst\mojangapi\world\oracle\ImmutableWorldSpawnOracle.java
package amidst.mojangapi.world.oracle; import amidst.documentation.Immutable; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; @Immutable public class ImmutableWorldSpawnOracle implements WorldSpawnOracle { private final CoordinatesInWorld worldSpawn; public ImmutableWorldSpawnOracle(CoordinatesInWorld worldSpawn) { this.worldSpawn = worldSpawn; } @Override public CoordinatesInWorld get() { return worldSpawn; } }
amidst
src\main\java\amidst\mojangapi\world\oracle\SimplexNoise.java
package amidst.mojangapi.world.oracle; import amidst.documentation.ThreadSafe; import amidst.util.FastRand; /** * A speed-improved simplex noise algorithm for 2D, 3D and 4D in Java. * * Based on example code by Stefan Gustavson (stegu@itn.liu.se). Optimisations * by Peter Eastman (peastman@drizzle.stanford.edu). Better rank ordering method * by Stefan Gustavson in 2012. * * This could be speeded up even further, but it's useful as it is. * * Version 2012-03-09 * * This code was placed in the public domain by its original author, Stefan * Gustavson. You may use it as you see fit, but attribution is appreciated. * * This file has been adapted for use in AmidstExporter/Amidst, it *should* be * compatible with the SimplexNoise generator Minecraft uses. The original * SimplexNoise code by Stefan and Peter, and related documents can be found at: * http://webstaff.itn.liu.se/~stegu/simplexnoise/ */ @ThreadSafe public class SimplexNoise { // @formatter:off private static final Grad[] GRAD_3 = { new Grad(1,1,0), new Grad(-1,1,0), new Grad(1,-1,0), new Grad(-1,-1,0), new Grad(1,0,1), new Grad(-1,0,1), new Grad(1,0,-1), new Grad(-1,0,-1), new Grad(0,1,1), new Grad(0,-1,1), new Grad(0,1,-1), new Grad(0,-1,-1) }; private static final Grad[] GRAD_4 = { new Grad(0,1,1,1), new Grad(0,1,1,-1), new Grad(0,1,-1,1), new Grad(0,1,-1,-1), new Grad(0,-1,1,1), new Grad(0,-1,1,-1), new Grad(0,-1,-1,1), new Grad(0,-1,-1,-1), new Grad(1,0,1,1), new Grad(1,0,1,-1), new Grad(1,0,-1,1), new Grad(1,0,-1,-1), new Grad(-1,0,1,1), new Grad(-1,0,1,-1), new Grad(-1,0,-1,1), new Grad(-1,0,-1,-1), new Grad(1,1,0,1), new Grad(1,1,0,-1), new Grad(1,-1,0,1), new Grad(1,-1,0,-1), new Grad(-1,1,0,1), new Grad(-1,1,0,-1), new Grad(-1,-1,0,1), new Grad(-1,-1,0,-1), new Grad(1,1,1,0), new Grad(1,1,-1,0), new Grad(1,-1,1,0), new Grad(1,-1,-1,0), new Grad(-1,1,1,0), new Grad(-1,1,-1,0), new Grad(-1,-1,1,0), new Grad(-1,-1,-1,0) }; // @formatter:on // To remove the need for index wrapping, double the permutation table // length private short perm[]; private short permMod12[]; // Skewing and unskewing factors for 2, 3, and 4 dimensions private static final double F2 = 0.5 * (Math.sqrt(3.0) - 1.0); private static final double G2 = (3.0 - Math.sqrt(3.0)) / 6.0; private static final double F3 = 1.0 / 3.0; private static final double G3 = 1.0 / 6.0; private static final double F4 = (Math.sqrt(5.0) - 1.0) / 4.0; private static final double G4 = (5.0 - Math.sqrt(5.0)) / 20.0; public SimplexNoise(FastRand random) { // To remove the need for index wrapping, double the permutation table // length perm = new short[512]; permMod12 = new short[512]; // Minecraft uses the PRNG 3 times before building the // permutation table. random.nextDouble(); random.nextDouble(); random.nextDouble(); // Build a permutation table using our seeded PRNG for (short i = 0; i < 256; ++i) { perm[i] = i; } for (int i = 0; i < 256; ++i) { final int swapIndex = random.nextInt(256 - i) + i; final short temp = perm[i]; perm[i] = perm[swapIndex]; perm[swapIndex] = temp; perm[i + 256] = perm[i]; permMod12[i] = permMod12[i + 256] = (short) (perm[i] % 12); } } // This method is a *lot* faster than using (int)Math.floor(x) private static int fastfloor(double x) { int xi = (int) x; return x < xi ? xi - 1 : xi; } private static double dot(Grad g, double x, double y) { return g.x * x + g.y * y; } private static double dot(Grad g, double x, double y, double z) { return g.x * x + g.y * y + g.z * z; } private static double dot(Grad g, double x, double y, double z, double w) { return g.x * x + g.y * y + g.z * z + g.w * w; } // 2D simplex noise public double noise(double xin, double yin) { double n0, n1, n2; // Noise contributions from the three corners // Skew the input space to determine which simplex cell we're in double s = (xin + yin) * F2; // Hairy factor for 2D int i = fastfloor(xin + s); int j = fastfloor(yin + s); double t = (i + j) * G2; double X0 = i - t; // Unskew the cell origin back to (x,y) space double Y0 = j - t; double x0 = xin - X0; // The x,y distances from the cell origin double y0 = yin - Y0; // For the 2D case, the simplex shape is an equilateral triangle. // Determine which simplex we are in. int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) // coords if (x0 > y0) { i1 = 1; j1 = 0; } // lower triangle, XY order: (0,0)->(1,0)->(1,1) else { i1 = 0; j1 = 1; } // upper triangle, YX order: (0,0)->(0,1)->(1,1) // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-sqrt(3))/6 double x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed // coords double y1 = y0 - j1 + G2; double x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) // unskewed coords double y2 = y0 - 1.0 + 2.0 * G2; // Work out the hashed gradient indices of the three simplex corners int ii = i & 255; int jj = j & 255; int gi0 = permMod12[ii + perm[jj]]; int gi1 = permMod12[ii + i1 + perm[jj + j1]]; int gi2 = permMod12[ii + 1 + perm[jj + 1]]; // Calculate the contribution from the three corners double t0 = 0.5 - x0 * x0 - y0 * y0; if (t0 < 0) { n0 = 0.0; } else { t0 *= t0; n0 = t0 * t0 * dot(GRAD_3[gi0], x0, y0); // (x,y) of grad3 used for // 2D gradient } double t1 = 0.5 - x1 * x1 - y1 * y1; if (t1 < 0) { n1 = 0.0; } else { t1 *= t1; n1 = t1 * t1 * dot(GRAD_3[gi1], x1, y1); } double t2 = 0.5 - x2 * x2 - y2 * y2; if (t2 < 0) { n2 = 0.0; } else { t2 *= t2; n2 = t2 * t2 * dot(GRAD_3[gi2], x2, y2); } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. return 70.0 * (n0 + n1 + n2); } // 3D simplex noise public double noise(double xin, double yin, double zin) { double n0, n1, n2, n3; // Noise contributions from the four corners // Skew the input space to determine which simplex cell we're in // Very nice and simple skew factor for 3D double s = (xin + yin + zin) * F3; int i = fastfloor(xin + s); int j = fastfloor(yin + s); int k = fastfloor(zin + s); double t = (i + j + k) * G3; double X0 = i - t; // Unskew the cell origin back to (x,y,z) space double Y0 = j - t; double Z0 = k - t; double x0 = xin - X0; // The x,y,z distances from the cell origin double y0 = yin - Y0; double z0 = zin - Z0; // For the 3D case, the simplex shape is a slightly irregular // tetrahedron. // Determine which simplex we are in. // Offsets for second corner of simplex in (i,j,k) coords int i1, j1, k1; // Offsets for third corner of simplex in (i,j,k) coords int i2, j2, k2; if (x0 >= y0) { if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // X Y Z order else if (x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; } // X Z Y order else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; } // Z X Y order } else { // x0<y0 if (y0 < z0) { i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1; } // Z Y X order else if (x0 < z0) { i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1; } // Y Z X order else { i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // Y X Z order } // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z), // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), // and // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), // where // c = 1/6. double x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords double y1 = y0 - j1 + G3; double z1 = z0 - k1 + G3; double x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) // coords double y2 = y0 - j2 + 2.0 * G3; double z2 = z0 - k2 + 2.0 * G3; double x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) // coords double y3 = y0 - 1.0 + 3.0 * G3; double z3 = z0 - 1.0 + 3.0 * G3; // Work out the hashed gradient indices of the four simplex corners int ii = i & 255; int jj = j & 255; int kk = k & 255; int gi0 = permMod12[ii + perm[jj + perm[kk]]]; int gi1 = permMod12[ii + i1 + perm[jj + j1 + perm[kk + k1]]]; int gi2 = permMod12[ii + i2 + perm[jj + j2 + perm[kk + k2]]]; int gi3 = permMod12[ii + 1 + perm[jj + 1 + perm[kk + 1]]]; // Calculate the contribution from the four corners double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0; if (t0 < 0) { n0 = 0.0; } else { t0 *= t0; n0 = t0 * t0 * dot(GRAD_3[gi0], x0, y0, z0); } double t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1; if (t1 < 0) { n1 = 0.0; } else { t1 *= t1; n1 = t1 * t1 * dot(GRAD_3[gi1], x1, y1, z1); } double t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2; if (t2 < 0) { n2 = 0.0; } else { t2 *= t2; n2 = t2 * t2 * dot(GRAD_3[gi2], x2, y2, z2); } double t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3; if (t3 < 0) { n3 = 0.0; } else { t3 *= t3; n3 = t3 * t3 * dot(GRAD_3[gi3], x3, y3, z3); } // Add contributions from each corner to get the final noise value. // The result is scaled to stay just inside [-1,1] return 32.0 * (n0 + n1 + n2 + n3); } // 4D simplex noise, better simplex rank ordering method 2012-03-09 public double noise(double x, double y, double z, double w) { double n0, n1, n2, n3, n4; // Noise contributions from the five corners // Skew the (x,y,z,w) space to determine which cell of 24 simplices // we're in double s = (x + y + z + w) * F4; // Factor for 4D skewing int i = fastfloor(x + s); int j = fastfloor(y + s); int k = fastfloor(z + s); int l = fastfloor(w + s); double t = (i + j + k + l) * G4; // Factor for 4D unskewing double X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space double Y0 = j - t; double Z0 = k - t; double W0 = l - t; double x0 = x - X0; // The x,y,z,w distances from the cell origin double y0 = y - Y0; double z0 = z - Z0; double w0 = w - W0; // For the 4D case, the simplex is a 4D shape I won't even try to // describe. // To find out which of the 24 possible simplices we're in, we need to // determine the magnitude ordering of x0, y0, z0 and w0. // Six pair-wise comparisons are performed between each possible pair // of the four coordinates, and the results are used to rank the // numbers. int rankx = 0; int ranky = 0; int rankz = 0; int rankw = 0; if (x0 > y0) { rankx++; } else { ranky++; } if (x0 > z0) { rankx++; } else { rankz++; } if (x0 > w0) { rankx++; } else { rankw++; } if (y0 > z0) { ranky++; } else { rankz++; } if (y0 > w0) { ranky++; } else { rankw++; } if (z0 > w0) { rankz++; } else { rankw++; } int i1, j1, k1, l1; // The integer offsets for the second simplex corner int i2, j2, k2, l2; // The integer offsets for the third simplex corner int i3, j3, k3, l3; // The integer offsets for the fourth simplex corner // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some // order. // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w // and x<w // impossible. Only the 24 indices which have non-zero entries make any // sense. // We use a thresholding to set the coordinates in turn from the largest // magnitude. // Rank 3 denotes the largest coordinate. i1 = rankx >= 3 ? 1 : 0; j1 = ranky >= 3 ? 1 : 0; k1 = rankz >= 3 ? 1 : 0; l1 = rankw >= 3 ? 1 : 0; // Rank 2 denotes the second largest coordinate. i2 = rankx >= 2 ? 1 : 0; j2 = ranky >= 2 ? 1 : 0; k2 = rankz >= 2 ? 1 : 0; l2 = rankw >= 2 ? 1 : 0; // Rank 1 denotes the second smallest coordinate. i3 = rankx >= 1 ? 1 : 0; j3 = ranky >= 1 ? 1 : 0; k3 = rankz >= 1 ? 1 : 0; l3 = rankw >= 1 ? 1 : 0; // The fifth corner has all coordinate offsets = 1, so no need to // compute that. double x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) // coords double y1 = y0 - j1 + G4; double z1 = z0 - k1 + G4; double w1 = w0 - l1 + G4; double x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) // coords double y2 = y0 - j2 + 2.0 * G4; double z2 = z0 - k2 + 2.0 * G4; double w2 = w0 - l2 + 2.0 * G4; double x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in // (x,y,z,w) coords double y3 = y0 - j3 + 3.0 * G4; double z3 = z0 - k3 + 3.0 * G4; double w3 = w0 - l3 + 3.0 * G4; double x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) // coords double y4 = y0 - 1.0 + 4.0 * G4; double z4 = z0 - 1.0 + 4.0 * G4; double w4 = w0 - 1.0 + 4.0 * G4; // Work out the hashed gradient indices of the five simplex corners int ii = i & 255; int jj = j & 255; int kk = k & 255; int ll = l & 255; int gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; int gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; int gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32; int gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32; int gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; // Calculate the contribution from the five corners double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; if (t0 < 0) { n0 = 0.0; } else { t0 *= t0; n0 = t0 * t0 * dot(GRAD_4[gi0], x0, y0, z0, w0); } double t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; if (t1 < 0) { n1 = 0.0; } else { t1 *= t1; n1 = t1 * t1 * dot(GRAD_4[gi1], x1, y1, z1, w1); } double t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; if (t2 < 0) { n2 = 0.0; } else { t2 *= t2; n2 = t2 * t2 * dot(GRAD_4[gi2], x2, y2, z2, w2); } double t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; if (t3 < 0) { n3 = 0.0; } else { t3 *= t3; n3 = t3 * t3 * dot(GRAD_4[gi3], x3, y3, z3, w3); } double t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; if (t4 < 0) { n4 = 0.0; } else { t4 *= t4; n4 = t4 * t4 * dot(GRAD_4[gi4], x4, y4, z4, w4); } // Sum up and scale the result to cover the range [-1,1] return 27.0 * (n0 + n1 + n2 + n3 + n4); } // Inner class to speed upp gradient computations // (array access is a lot slower than member access) private static class Grad { double x, y, z, w; Grad(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } Grad(double x, double y, double z, double w) { this.x = x; this.y = y; this.z = z; this.w = w; } } }
amidst
src\main\java\amidst\mojangapi\world\oracle\SlimeChunkOracle.java
package amidst.mojangapi.world.oracle; import amidst.documentation.Immutable; import amidst.util.FastRand; @Immutable public class SlimeChunkOracle { private final long seed; public SlimeChunkOracle(long seed) { this.seed = seed; } public boolean isSlimeChunk(long chunkX, long chunkY) { FastRand random = new FastRand(getSeed((int) chunkX, (int) chunkY)); return isSlimeChunk(random); } /** * Make sure this uses integers for the parameters chunkX and chunkY and * long for the seed. This ensure the overflow works as in Minecraft. */ private long getSeed(int chunkX, int chunkY) { return seed + chunkX * chunkX * 0x4c1906 + chunkX * 0x5ac0db + chunkY * chunkY * 0x4307a7L + chunkY * 0x5f24f ^ 0x3ad8025f; } private boolean isSlimeChunk(FastRand random) { return random.nextInt(10) == 0; } }
amidst
src\main\java\amidst\mojangapi\world\oracle\WorldSpawnOracle.java
package amidst.mojangapi.world.oracle; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; @ThreadSafe public interface WorldSpawnOracle { CoordinatesInWorld get(); }
amidst
src\main\java\amidst\mojangapi\world\player\MovablePlayerList.java
package amidst.mojangapi.world.player; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.ThreadSafe; import amidst.logging.AmidstLogger; import amidst.mojangapi.file.PlayerInformationProvider; import amidst.mojangapi.file.SaveGame; import amidst.mojangapi.file.SaveGamePlayer; import amidst.threading.WorkerExecutor; @ThreadSafe public class MovablePlayerList implements Iterable<Player> { private static final MovablePlayerList DUMMY = new MovablePlayerList(null, null, false, WorldPlayerType.NONE); public static MovablePlayerList dummy() { return DUMMY; } private final PlayerInformationProvider playerInformationProvider; private final SaveGame saveGame; private final boolean isSaveEnabled; private volatile WorldPlayerType worldPlayerType; private volatile ConcurrentLinkedQueue<Player> players = new ConcurrentLinkedQueue<>(); public MovablePlayerList( PlayerInformationProvider playerInformationProvider, SaveGame saveGame, boolean isSaveEnabled, WorldPlayerType worldPlayerType) { this.playerInformationProvider = playerInformationProvider; this.saveGame = saveGame; this.isSaveEnabled = isSaveEnabled; this.worldPlayerType = worldPlayerType; } public WorldPlayerType getWorldPlayerType() { return worldPlayerType; } public void setWorldPlayerType(WorldPlayerType worldPlayerType) { this.worldPlayerType = worldPlayerType; } public boolean canLoad() { return saveGame != null; } public void load(WorkerExecutor workerExecutor, Runnable onPlayerFinishedLoading) { if (saveGame != null) { AmidstLogger.info("loading player locations"); ConcurrentLinkedQueue<Player> players = new ConcurrentLinkedQueue<>(); this.players = players; loadPlayersLater(players, workerExecutor, onPlayerFinishedLoading); } } private void loadPlayersLater( ConcurrentLinkedQueue<Player> players, WorkerExecutor workerExecutor, Runnable onPlayerFinishedLoading) { workerExecutor.run(() -> loadPlayers(workerExecutor, players, onPlayerFinishedLoading)); } @CalledOnlyBy(AmidstThread.WORKER) private void loadPlayers( WorkerExecutor workerExecutor, ConcurrentLinkedQueue<Player> players, Runnable onPlayerFinishedLoading) { for (SaveGamePlayer saveGamePlayer : worldPlayerType.tryReadPlayers(saveGame)) { workerExecutor.run(() -> loadPlayer(players, saveGamePlayer), onPlayerFinishedLoading); } } @CalledOnlyBy(AmidstThread.WORKER) private void loadPlayer(ConcurrentLinkedQueue<Player> players, SaveGamePlayer saveGamePlayer) { players.offer(new Player(saveGamePlayer.getPlayerInformation(playerInformationProvider), saveGamePlayer)); } public boolean canSave() { return isSaveEnabled; } public void save() { if (isSaveEnabled) { AmidstLogger.info("saving player locations"); for (Player player : players) { player.trySaveLocation(); } } else { AmidstLogger.info("not saving player locations, because it is disabled for this version"); } } @Override public Iterator<Player> iterator() { return players.iterator(); } }
amidst
src\main\java\amidst\mojangapi\world\player\Player.java
package amidst.mojangapi.world.player; import amidst.documentation.ThreadSafe; import amidst.logging.AmidstLogger; import amidst.mojangapi.file.SaveGamePlayer; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.icon.WorldIconImage; @ThreadSafe public class Player { private final PlayerInformation playerInformation; private final SaveGamePlayer saveGamePlayer; private volatile PlayerCoordinates savedCoordinates; private volatile PlayerCoordinates currentCoordinates; public Player(PlayerInformation playerInformation, SaveGamePlayer saveGamePlayer) { this.playerInformation = playerInformation; this.saveGamePlayer = saveGamePlayer; this.savedCoordinates = saveGamePlayer.getPlayerCoordinates(); this.currentCoordinates = savedCoordinates; } public String getPlayerName() { return playerInformation.getNameOrElseUUID(); } public WorldIconImage getHead() { return playerInformation.getHead(); } public PlayerCoordinates getPlayerCoordinates() { return currentCoordinates; } public void moveTo(CoordinatesInWorld coordinates, long height, Dimension dimension) { this.currentCoordinates = new PlayerCoordinates(coordinates, height, dimension); } /** * Returns true if the player was not moved or the new location was * successfully saved. */ public synchronized boolean trySaveLocation() { PlayerCoordinates currentCoordinates = this.currentCoordinates; if (savedCoordinates != currentCoordinates) { if (saveGamePlayer.tryBackupAndWritePlayerCoordinates(currentCoordinates)) { savedCoordinates = currentCoordinates; return true; } else { AmidstLogger.warn("error while writing player location for player: {}", getPlayerName()); return false; } } else { return true; } } }
amidst
src\main\java\amidst\mojangapi\world\player\PlayerCoordinates.java
package amidst.mojangapi.world.player; import amidst.documentation.Immutable; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; @Immutable public class PlayerCoordinates { public static PlayerCoordinates fromNBTFile(long x, long y, long z, Dimension dimension) { return new PlayerCoordinates(CoordinatesInWorld.from(x, z, dimension.getResolution()), y, dimension); } private final CoordinatesInWorld coordinates; private final long y; private final Dimension dimension; public PlayerCoordinates(CoordinatesInWorld coordinates, long y, Dimension dimension) { this.coordinates = coordinates; this.y = y; this.dimension = dimension; } public CoordinatesInWorld getCoordinatesInWorld() { return coordinates; } public long getY() { return y; } public Dimension getDimension() { return dimension; } public long getXForNBTFile() { return coordinates.getXAs(dimension.getResolution()); } public long getYForNBTFile() { return y; } public long getZForNBTFile() { return coordinates.getYAs(dimension.getResolution()); } }
amidst
src\main\java\amidst\mojangapi\world\player\PlayerInformation.java
package amidst.mojangapi.world.player; import amidst.documentation.Immutable; import amidst.documentation.NotNull; import amidst.mojangapi.world.icon.WorldIconImage; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; @Immutable public class PlayerInformation { private static final WorldIconImage DEFAULT_HEAD = DefaultWorldIconTypes.PLAYER.getImage(); private static final PlayerInformation THE_SINGLEPLAYER_PLAYER = new PlayerInformation( null, "The Singleplayer Player", DEFAULT_HEAD); @NotNull public static PlayerInformation theSingleplayerPlayer() { return THE_SINGLEPLAYER_PLAYER; } private final String uuid; private final String name; private final WorldIconImage head; public PlayerInformation(String uuid, String name, WorldIconImage head) { this.uuid = uuid; this.name = name; this.head = head; } public String getUUID() { return uuid; } public String getName() { return name; } public WorldIconImage getHead() { return head; } public String getNameOrElseUUID() { if (name != null) { return name; } else { return uuid; } } }
amidst
src\main\java\amidst\mojangapi\world\player\WorldPlayerType.java
package amidst.mojangapi.world.player; import java.util.Arrays; import java.util.Collections; import java.util.List; import amidst.documentation.Immutable; import amidst.documentation.NotNull; import amidst.mojangapi.file.SaveGame; import amidst.mojangapi.file.SaveGamePlayer; @Immutable public enum WorldPlayerType { // @formatter:off NONE ("None"), SINGLEPLAYER("Singleplayer"), MULTIPLAYER ("Multiplayer"), BOTH ("Both"); // @formatter:on private static final List<WorldPlayerType> SELECTABLE = Arrays.asList(SINGLEPLAYER, MULTIPLAYER, BOTH); public static List<WorldPlayerType> getSelectable() { return SELECTABLE; } public static WorldPlayerType from(SaveGame saveGame) { boolean hasSingleplayerPlayer = saveGame.hasSingleplayerPlayer(); boolean hasMultiplayerPlayers = saveGame.hasMultiplayerPlayers(); if (hasSingleplayerPlayer && hasMultiplayerPlayers) { return BOTH; } else if (hasSingleplayerPlayer) { return SINGLEPLAYER; } else if (hasMultiplayerPlayers) { return MULTIPLAYER; } else { return NONE; } } private final String name; private WorldPlayerType(String name) { this.name = name; } public String getName() { return name; } @NotNull public List<SaveGamePlayer> tryReadPlayers(SaveGame saveGame) { if (this == BOTH) { return saveGame.tryReadAllPlayers(); } else if (this == SINGLEPLAYER) { return saveGame .tryReadSingleplayerPlayer() .map(Collections::singletonList) .orElseGet(Collections::emptyList); } else if (this == MULTIPLAYER) { return saveGame.tryReadMultiplayerPlayers(); } else { return Collections.emptyList(); } } @Override public String toString() { return name; } }
amidst
src\main\java\amidst\mojangapi\world\versionfeatures\DefaultBiomes.java
package amidst.mojangapi.world.versionfeatures; import static amidst.mojangapi.world.biome.BiomeType.BEACH; import static amidst.mojangapi.world.biome.BiomeType.BEACH_CLIFFS; import static amidst.mojangapi.world.biome.BiomeType.DEEP_OCEAN; import static amidst.mojangapi.world.biome.BiomeType.HILLS; import static amidst.mojangapi.world.biome.BiomeType.ISLAND; import static amidst.mojangapi.world.biome.BiomeType.MOUNTAINS; import static amidst.mojangapi.world.biome.BiomeType.OCEAN; import static amidst.mojangapi.world.biome.BiomeType.PLAINS; import static amidst.mojangapi.world.biome.BiomeType.PLAINS_FLAT; import static amidst.mojangapi.world.biome.BiomeType.PLAINS_TAIGA; import static amidst.mojangapi.world.biome.BiomeType.PLATEAU; import static amidst.mojangapi.world.biome.BiomeType.RIVER; import static amidst.mojangapi.world.biome.BiomeType.SWAMPLAND; import amidst.mojangapi.minecraftinterface.RecognisedVersion; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.biome.BiomeList; public enum DefaultBiomes { ; // @formatter:off public static final int ocean = 0; public static final int plains = 1; public static final int desert = 2; public static final int extremeHills = 3; public static final int forest = 4; public static final int taiga = 5; public static final int swampland = 6; public static final int river = 7; public static final int hell = 8; public static final int theEnd = 9; public static final int frozenOcean = 10; public static final int frozenRiver = 11; public static final int icePlains = 12; public static final int iceMountains = 13; public static final int mushroomIsland = 14; public static final int mushroomIslandShore = 15; public static final int beach = 16; public static final int desertHills = 17; public static final int forestHills = 18; public static final int taigaHills = 19; public static final int extremeHillsEdge = 20; public static final int jungle = 21; public static final int jungleHills = 22; public static final int jungleEdge = 23; public static final int deepOcean = 24; public static final int stoneBeach = 25; public static final int coldBeach = 26; public static final int birchForest = 27; public static final int birchForestHills = 28; public static final int roofedForest = 29; public static final int coldTaiga = 30; public static final int coldTaigaHills = 31; public static final int megaTaiga = 32; public static final int megaTaigaHills = 33; public static final int extremeHillsPlus = 34; public static final int savanna = 35; public static final int savannaPlateau = 36; public static final int mesa = 37; public static final int mesaPlateauF = 38; public static final int mesaPlateau = 39; public static final int theEndLow = 40; public static final int theEndMedium = 41; public static final int theEndHigh = 42; public static final int theEndBarren = 43; public static final int warmOcean = 44; public static final int lukewarmOcean = 45; public static final int coldOcean = 46; public static final int warmDeepOcean = 47; public static final int lukewarmDeepOcean = 48; public static final int coldDeepOcean = 49; public static final int frozenDeepOcean = 50; public static final int theVoid = 127; public static final int sunflowerPlains = plains + Biome.SPECIAL_BIOMES_START; public static final int desertM = desert + Biome.SPECIAL_BIOMES_START; public static final int extremeHillsM = extremeHills + Biome.SPECIAL_BIOMES_START; public static final int flowerForest = forest + Biome.SPECIAL_BIOMES_START; public static final int taigaM = taiga + Biome.SPECIAL_BIOMES_START; public static final int swamplandM = swampland + Biome.SPECIAL_BIOMES_START; public static final int icePlainsSpikes = icePlains + Biome.SPECIAL_BIOMES_START; public static final int jungleM = jungle + Biome.SPECIAL_BIOMES_START; public static final int jungleEdgeM = jungleEdge + Biome.SPECIAL_BIOMES_START; public static final int birchForestM = birchForest + Biome.SPECIAL_BIOMES_START; public static final int birchForestHillsM = birchForestHills + Biome.SPECIAL_BIOMES_START; public static final int roofedForestM = roofedForest + Biome.SPECIAL_BIOMES_START; public static final int coldTaigaM = coldTaiga + Biome.SPECIAL_BIOMES_START; public static final int megaSpruceTaiga = megaTaiga + Biome.SPECIAL_BIOMES_START; public static final int megaSpruceTaigaHills = megaTaigaHills + Biome.SPECIAL_BIOMES_START; public static final int extremeHillsPlusM = extremeHillsPlus + Biome.SPECIAL_BIOMES_START; public static final int savannaM = savanna + Biome.SPECIAL_BIOMES_START; public static final int savannaPlateauM = savannaPlateau + Biome.SPECIAL_BIOMES_START; public static final int mesaBryce = mesa + Biome.SPECIAL_BIOMES_START; public static final int mesaPlateauFM = mesaPlateauF + Biome.SPECIAL_BIOMES_START; public static final int mesaPlateauM = mesaPlateau + Biome.SPECIAL_BIOMES_START; public static final int bambooJungle = 168; public static final int bambooJungleHills = 169; public static final int soulSandValley = 170; public static final int crimsonForest = 171; public static final int warpedForest = 172; public static final int basaltDeltas = 173; public static final VersionFeature<BiomeList> DEFAULT_BIOMES = VersionFeature.<Biome> listBuilder() .init( // Starts at alpha 1.2.0 new Biome(jungle, "Rainforest", PLAINS), new Biome(forestHills, "Seasonal Forest", PLAINS), new Biome(forest, "Forest", PLAINS), new Biome(savannaM, "Shrubland", PLAINS), new Biome(savanna, "Savanna", PLAINS), new Biome(plains, "Plains", PLAINS), new Biome(desert, "Desert", PLAINS), new Biome(taiga, "Taiga", PLAINS), new Biome(icePlains, "Tundra", PLAINS), new Biome(swampland, "Swampland", PLAINS), // Just in case we implement that 4 year old idea for ocean gen: new Biome(ocean, "Ocean", OCEAN), new Biome(coldOcean, "Frozen Ocean", OCEAN), // For completeness: new Biome(desertM, "Ice Desert", PLAINS), new Biome(hell, "Hell", PLAINS), new Biome(theEnd, "Sky", PLAINS) ).since(RecognisedVersion._b1_8_1, new Biome(0, "Ocean", OCEAN), new Biome(1, "Plains", PLAINS), new Biome(2, "Desert", PLAINS_FLAT), new Biome(3, "Extreme Hills", MOUNTAINS), new Biome(4, "Forest", PLAINS), new Biome(5, "Taiga", PLAINS_TAIGA), new Biome(6, "Swampland", SWAMPLAND), new Biome(7, "River", RIVER), new Biome(8, "Hell", PLAINS), new Biome(9, "Sky", PLAINS) ).sinceExtend(RecognisedVersion._b1_9_pre1, new Biome(10, "Frozen Ocean", OCEAN), new Biome(11, "Frozen River", RIVER), new Biome(12, "Ice Plains", PLAINS_FLAT), new Biome(13, "Ice Mountains", HILLS), // There was a bug causing this biome to not be generated until the next version new Biome(14, "Mushroom Island", ISLAND), new Biome(15, "Mushroom Island Shore", BEACH) ).sinceExtend(RecognisedVersion._12w01a, new Biome(16, "Beach", BEACH), new Biome(17, "Desert Hills", HILLS), new Biome(18, "Forest Hills", HILLS), new Biome(19, "Taiga Hills", HILLS), new Biome(20, "Extreme Hills Edge", MOUNTAINS.weaken()) ).sinceExtend(RecognisedVersion._12w03a, new Biome(21, "Jungle", PLAINS), new Biome(22, "Jungle Hills", HILLS) ).sinceExtend(RecognisedVersion._13w36a, new Biome(23, "Jungle Edge", PLAINS), new Biome(24, "Deep Ocean", DEEP_OCEAN), new Biome(25, "Stone Beach", BEACH_CLIFFS), new Biome(26, "Cold Beach", BEACH), new Biome(27, "Birch Forest", PLAINS), new Biome(28, "Birch Forest Hills", HILLS), new Biome(29, "Roofed Forest", PLAINS), new Biome(30, "Cold Taiga", PLAINS_TAIGA), new Biome(31, "Cold Taiga Hills", HILLS), new Biome(32, "Mega Taiga", PLAINS_TAIGA), new Biome(33, "Mega Taiga Hills", HILLS), new Biome(34, "Extreme Hills+", MOUNTAINS), new Biome(35, "Savanna", PLAINS_FLAT), new Biome(36, "Savanna Plateau", PLATEAU), new Biome(37, "Mesa", PLAINS), new Biome(38, "Mesa Plateau F", PLATEAU), new Biome(39, "Mesa Plateau", PLATEAU), // All of the modified biomes in this version just had an M after their original biome name new Biome("Plains M", 1, PLAINS), new Biome("Desert M", 2, PLAINS_FLAT), new Biome("Extreme Hills M", 3, MOUNTAINS), new Biome("Forest M", 4, PLAINS), new Biome("Taiga M", 5, PLAINS_TAIGA), new Biome("Swampland M", 6, SWAMPLAND), new Biome("Ice Plains M", 12, PLAINS_FLAT), new Biome("Jungle M", 21, PLAINS), new Biome("Jungle Edge M", 23, PLAINS), new Biome("Birch Forest M", 27, PLAINS), new Biome("Birch Forest Hills M", 28, HILLS), new Biome("Roofed Forest M", 29, PLAINS), new Biome("Cold Taiga M", 30, PLAINS_TAIGA), new Biome("Mega Taiga M", 32, PLAINS_TAIGA), new Biome(161, "Mega Taiga Hills M", PLAINS_TAIGA.strengthen(), true), new Biome("Extreme Hills+ M", 34, MOUNTAINS), new Biome("Savanna M", 35, PLAINS_FLAT), new Biome("Savanna Plateau M", 36, PLATEAU), new Biome("Mesa M", 37, PLAINS), new Biome("Mesa Plateau F M", 38, PLATEAU), new Biome("Mesa Plateau M", 39, PLATEAU) ).sinceExtend(RecognisedVersion._14w02a, // Need confirmation on version; this was changed sometime after 1.7.10 and before 1.8.8 new Biome(161,"Redwood Taiga Hills M", PLAINS_TAIGA.strengthen(), true) ).sinceExtend(RecognisedVersion._14w17a, new Biome(9, "The End", PLAINS) ).sinceExtend(RecognisedVersion._15w31c, // Need confirmation on this version. Was after 1.8.8 and before 1.9.4 new Biome("Sunflower Plains", 1, PLAINS), new Biome("Flower Forest", 4, PLAINS), new Biome("Ice Plains Spikes", 12, PLAINS_FLAT), new Biome("Mega Spruce Taiga", 32, PLAINS_TAIGA), new Biome("Mesa (Bryce)", 37, PLAINS) ).sinceExtend(RecognisedVersion._15w40b, // Is actually 15w37a, but magic strings are identical new Biome(127,"The Void", PLAINS) ).sinceExtend(RecognisedVersion._18w06a, new Biome(40, "The End - Floating Island", PLAINS), new Biome(41, "The End - Medium Island", PLAINS), new Biome(42, "The End - High Island", PLAINS), new Biome(43, "The End - Barren Island", PLAINS) ).sinceExtend(RecognisedVersion._18w08a, new Biome(44, "Warm Ocean", OCEAN), new Biome(45, "Lukewarm Ocean", OCEAN), new Biome(46, "Cold Ocean", OCEAN), new Biome(47, "Warm Deep Ocean", OCEAN), new Biome(48, "Lukewarm Deep Ocean", OCEAN), new Biome(49, "Cold Deep Ocean", OCEAN), new Biome(50, "Frozen Deep Ocean", OCEAN) ).sinceExtend(RecognisedVersion._18w16a, new Biome(8, "Nether", PLAINS), new Biome(38, "Mesa Forest Plateu", PLATEAU), new Biome("Mutated Desert", 2, PLAINS_FLAT), new Biome("Mutated Extreme Hills", 3, MOUNTAINS), new Biome("Mutated Taiga", 5, PLAINS_TAIGA), new Biome("Mutated Swampland", 6, SWAMPLAND), new Biome("Mutated Jungle", 21, PLAINS), new Biome("Mutated Jungle Edge", 23, PLAINS), new Biome("Mutated Birch Forest", 27, PLAINS), new Biome("Mutated Birch Forest Hills", 28, HILLS), new Biome("Mutated Roofed Forest", 29, PLAINS), new Biome("Mutated Cold Taiga", 30, PLAINS_TAIGA), new Biome("Mutated Extreme Hills+", 34, MOUNTAINS), new Biome("Mutated Savanna", 35, PLAINS_FLAT), new Biome("Mutated Savanna Plateau", 36, PLATEAU), new Biome("Mutated Mesa Forest Plateau", 38, PLATEAU), new Biome("Mutated Mesa Plateau", 39, PLATEAU) ).sinceExtend(RecognisedVersion._18w19a, new Biome(3, "Mountains", MOUNTAINS), new Biome(6, "Swamp", SWAMPLAND), new Biome(12, "Snowy Tundra", PLAINS_FLAT), new Biome(13, "Snowy Mountains", HILLS), new Biome(14, "Mushroom Fields", ISLAND), new Biome(15, "Mushroom Field Shore", BEACH), new Biome(18, "Wooded Hills", HILLS), new Biome(20, "Mountain Edge", MOUNTAINS.weaken()), new Biome(25, "Stone Shore", BEACH_CLIFFS), new Biome(26, "Snowy Beach", BEACH), new Biome(29, "Dark Forest", PLAINS), new Biome(30, "Snowy Taiga", PLAINS_TAIGA), new Biome(31, "Snowy Taiga Hills", HILLS), new Biome(32, "Giant Tree Taiga", PLAINS_TAIGA), new Biome(33, "Giant Tree Taiga Hills", HILLS), new Biome(34, "Wooded Mountains", MOUNTAINS), new Biome(37, "Badlands", PLAINS), new Biome(38, "Wooded Badlands Plateau", PLATEAU), new Biome(39, "Badlands Plateau", PLATEAU), new Biome(40, "Small End Islands", PLAINS), new Biome(41, "End Midlands", PLAINS), new Biome(42, "End Highlands", PLAINS), new Biome(43, "End Barrens", PLAINS), new Biome(47, "Deep Warm Ocean", OCEAN), new Biome(48, "Deep Lukewarm Ocean", OCEAN), new Biome(49, "Deep Cold Ocean", OCEAN), new Biome(50, "Deep Frozen Ocean", OCEAN), new Biome("Desert Lakes", 2, PLAINS_FLAT), new Biome("Gravelly Mountains", 3, MOUNTAINS), new Biome("Taiga Mountains", 5, PLAINS_TAIGA), new Biome("Swamp Hills", 6, SWAMPLAND), new Biome("Ice Spikes", 12, PLAINS_FLAT), new Biome("Modified Jungle", 21, PLAINS), new Biome("Modified Jungle Edge", 23, PLAINS), new Biome("Tall Birch Forest", 27, PLAINS), new Biome("Tall Birch Hills", 28, HILLS), new Biome("Dark Forest Hills", 29, PLAINS), new Biome("Snowy Taiga Mountains", 30, PLAINS_TAIGA), new Biome("Giant Spruce Taiga", 32, PLAINS_TAIGA), new Biome(161, "Giant Spruce Taiga Hills", PLAINS_TAIGA, true), // Don't strengthen this in newer versions (might be wrong here) new Biome("Gravelly Mountains+", 34, MOUNTAINS), new Biome("Shattered Savanna", 35, PLAINS_FLAT), new Biome("Shattered Savanna Plateau", 36, PLATEAU), new Biome("Eroded Badlands", 37, PLAINS), new Biome("Modified Wooded Badlands Plateau", 38, PLATEAU), new Biome("Modified Badlands Plateau", 39, PLATEAU) ).sinceExtend(RecognisedVersion._18w43a, new Biome(168, "Bamboo Jungle", PLAINS), new Biome(169, "Bamboo Jungle Hills", HILLS) ).sinceExtend(RecognisedVersion._20w06a, new Biome(8, "Nether Wastes", PLAINS), new Biome(170, "Soul Sand Valley", PLAINS), new Biome(171, "Crimson Forest", PLAINS), new Biome(172, "Warped Forest", PLAINS) ).sinceExtend(RecognisedVersion._20w15a, new Biome(173, "Basalt Deltas", PLAINS) ).construct().andThen(BiomeList::new); // @formatter:on }
amidst
src\main\java\amidst\mojangapi\world\versionfeatures\DefaultVersionFeatures.java
package amidst.mojangapi.world.versionfeatures; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import amidst.fragment.layer.LayerIds; import amidst.logging.AmidstLogger; import amidst.mojangapi.minecraftinterface.MinecraftInterface; import amidst.mojangapi.minecraftinterface.RecognisedVersion; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.WorldOptions; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.biome.BiomeList; import amidst.mojangapi.world.biome.UnknownBiomeIdException; import amidst.mojangapi.world.coordinates.Resolution; import amidst.mojangapi.world.icon.locationchecker.BuriedTreasureLocationChecker; import amidst.mojangapi.world.icon.locationchecker.LocationChecker; import amidst.mojangapi.world.icon.locationchecker.MineshaftAlgorithm_ChanceBased; import amidst.mojangapi.world.icon.locationchecker.MineshaftAlgorithm_Original; import amidst.mojangapi.world.icon.locationchecker.StructureBiomeLocationChecker; import amidst.mojangapi.world.icon.producer.BastionRemnantProducer; import amidst.mojangapi.world.icon.producer.CachedWorldIconProducer; import amidst.mojangapi.world.icon.producer.ChunkStructureProducer; import amidst.mojangapi.world.icon.producer.NetherFortressProducer_Original; import amidst.mojangapi.world.icon.producer.NetherFortressProducer_Scattered; import amidst.mojangapi.world.icon.producer.NoopProducer; import amidst.mojangapi.world.icon.producer.OceanMonumentProducer_Fixed; import amidst.mojangapi.world.icon.producer.OceanMonumentProducer_Original; import amidst.mojangapi.world.icon.producer.PillagerOutpostProducer; import amidst.mojangapi.world.icon.producer.RegionalStructureProducer; import amidst.mojangapi.world.icon.producer.ScatteredFeaturesProducer; import amidst.mojangapi.world.icon.producer.StrongholdProducer_128Algorithm; import amidst.mojangapi.world.icon.producer.StrongholdProducer_Buggy128Algorithm; import amidst.mojangapi.world.icon.producer.StrongholdProducer_Original; import amidst.mojangapi.world.icon.producer.VillageProducer; import amidst.mojangapi.world.icon.producer.WorldIconProducer; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.mojangapi.world.icon.type.EndCityWorldIconTypeProvider; import amidst.mojangapi.world.icon.type.ImmutableWorldIconTypeProvider; import amidst.mojangapi.world.oracle.BiomeDataOracle; import amidst.mojangapi.world.oracle.EndIsland; import amidst.mojangapi.world.oracle.EndIslandOracle; import amidst.mojangapi.world.oracle.HeuristicWorldSpawnOracle; import amidst.mojangapi.world.oracle.SlimeChunkOracle; import amidst.util.FastRand; public enum DefaultVersionFeatures { ; public static VersionFeatures.Builder builder(WorldOptions worldOptions, MinecraftInterface.WorldAccessor worldAccessor) { if (worldOptions == null || worldAccessor == null) { return FEATURES_BUILDER.clone(); } else { return FEATURES_BUILDER.clone() .withValue(FeatureKey.WORLD_OPTIONS, worldOptions) .withValue(WORLD_ACCESSOR, worldAccessor); } } // @formatter:off private static final FeatureKey<MinecraftInterface.WorldAccessor> WORLD_ACCESSOR = FeatureKey.make(); public static final FeatureKey<List<Biome>> SPAWN_VALID_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> STRONGHOLD_VALID_MIDDLE_CHUNK_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> VILLAGE_VALID_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> PILLAGER_OUTPOST_VALID_BIOMES = FeatureKey.make(); private static final FeatureKey<Boolean> DO_COMPLEX_VILLAGE_CHECK = FeatureKey.make(); private static final FeatureKey<Integer> OUTPOST_VILLAGE_AVOID_DISTANCE = FeatureKey.make(); private static final FeatureKey<Boolean> OUTPOST_USE_CHECKED_VILLAGES = FeatureKey.make(); private static final FeatureKey<List<Biome>> DESERT_TEMPLE_VALID_MIDDLE_CHUNK_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> IGLOO_VALID_MIDDLE_CHUNK_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> JUNGLE_TEMPLE_VALID_MIDDLE_CHUNK_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> WITCH_HUT_VALID_MIDDLE_CHUNK_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> OCEAN_RUINS_VALID_MIDDLE_CHUNK_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> SHIPWRECK_VALID_MIDDLE_CHUNK_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> OCEAN_MONUMENT_VALID_MIDDLE_CHUNK_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> BURIED_TREASURE_VALID_MIDDLE_CHUNK_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> BASTION_REMNANT_VALID_MIDDLE_CHUNK_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> OCEAN_MONUMENT_VALID_BIOMES = FeatureKey.make(); private static final FeatureKey<List<Biome>> WOODLAND_MANSION_VALID_BIOMES = FeatureKey.make(); private static final FeatureKey<LocationChecker> MINESHAFT_LOCATION_CHECKER = FeatureKey.make(); private static final FeatureKey<Long> DESERT_TEMPLE_SALT = FeatureKey.make(); private static final FeatureKey<Long> IGLOO_SALT = FeatureKey.make(); private static final FeatureKey<Long> JUNGLE_TEMPLE_SALT = FeatureKey.make(); private static final FeatureKey<Long> WITCH_HUT_SALT = FeatureKey.make(); private static final FeatureKey<Long> OCEAN_RUINS_SALT = FeatureKey.make(); private static final FeatureKey<Long> SHIPWRECK_SALT = FeatureKey.make(); private static final FeatureKey<Long> BURIED_TREASURE_SALT = FeatureKey.make(); private static final FeatureKey<Long> NETHER_BUILDING_SALT = FeatureKey.make(); private static final FeatureKey<Byte> SHIPWRECK_SPACING = FeatureKey.make(); private static final FeatureKey<Byte> SHIPWRECK_SEPARATION = FeatureKey.make(); private static final FeatureKey<Byte> OCEAN_RUINS_SPACING = FeatureKey.make(); private static final FeatureKey<Byte> OCEAN_RUINS_SEPARATION = FeatureKey.make(); private static final FeatureKey<Byte> NETHER_BUILDING_SPACING = FeatureKey.make(); private static final FeatureKey<Byte> NETHER_BUILDING_SEPARATION = FeatureKey.make(); private static final FeatureKey<Function<FastRand, Boolean>> NETHER_FORTRESS_FUNCTION = FeatureKey.make(); private static final FeatureKey<Function<FastRand, Boolean>> BASTION_REMNANT_FUNCTION = FeatureKey.make(); private static final FeatureKey<Boolean> BUGGY_STRUCTURE_COORDINATE_MATH = FeatureKey.make(); private static final FeatureKey<Boolean> BIOME_DATA_ORACLE_QUARTER_RES_OVERRIDE = FeatureKey.make(); private static final FeatureKey<Boolean> BIOME_DATA_ORACLE_ACCURATE_LOCATION_COUNT = FeatureKey.make(); private static final FeatureKey<Integer> BIOME_DATA_ORACLE_MIDDLE_OF_CHUNK_OFFSET = FeatureKey.make(); private static final VersionFeatures.Builder FEATURES_BUILDER = VersionFeatures.builder() .with(FeatureKey.OVERWORLD_BIOME_DATA_ORACLE, VersionFeature.fixed(features -> new BiomeDataOracle( features.get(WORLD_ACCESSOR), Dimension.OVERWORLD, features.get(FeatureKey.BIOME_LIST), getBiomeOracleConfig(features) )) ) .with(FeatureKey.NETHER_BIOME_DATA_ORACLE, VersionFeature.fixed(features -> { MinecraftInterface.WorldAccessor worldAccessor = features.get(WORLD_ACCESSOR); if (worldAccessor.supportedDimensions().contains(Dimension.NETHER)) { return Optional.of(new BiomeDataOracle( worldAccessor, Dimension.NETHER, features.get(FeatureKey.BIOME_LIST), getBiomeOracleConfig(features) )); } else { return Optional.empty(); } })) .with(BIOME_DATA_ORACLE_QUARTER_RES_OVERRIDE, VersionFeature.<Boolean> builder() .init( false ).since(RecognisedVersion._20w21a, true ).construct() ) .with(BIOME_DATA_ORACLE_ACCURATE_LOCATION_COUNT, VersionFeature.<Boolean> builder() .init( false ).since(RecognisedVersion._18w06a, true ).construct() ) .with(BIOME_DATA_ORACLE_MIDDLE_OF_CHUNK_OFFSET, VersionFeature.<Integer> builder() .init( 8 ).since(RecognisedVersion._18w06a, 9 ).construct() ) .with(FeatureKey.ENABLED_LAYERS, VersionFeature.<Integer> listBuilder() .init( LayerIds.ALPHA, LayerIds.BIOME_DATA, LayerIds.BACKGROUND, LayerIds.SLIME, LayerIds.GRID, LayerIds.SPAWN, LayerIds.PLAYER ).sinceExtend(RecognisedVersion._b1_8_1, // Actually b1.8, but the version strings are identical LayerIds.STRONGHOLD, LayerIds.VILLAGE, LayerIds.MINESHAFT ).sinceExtend(RecognisedVersion._b1_9_pre1, LayerIds.NETHER_FEATURES ).sinceExtend(RecognisedVersion._12w21a, LayerIds.TEMPLE ).sinceExtend(RecognisedVersion._1_8, LayerIds.OCEAN_MONUMENT ).sinceExtend(RecognisedVersion._15w31c, LayerIds.END_ISLANDS, LayerIds.END_CITY ).sinceExtend(RecognisedVersion._16w43a, LayerIds.WOODLAND_MANSION ).sinceExtend(RecognisedVersion._18w09a, LayerIds.OCEAN_FEATURES ).construct()) .with(FeatureKey.BIOME_LIST, DefaultBiomes.DEFAULT_BIOMES) .with(FeatureKey.END_ISLAND_ORACLE, VersionFeature.fixed(features -> EndIslandOracle.from(getWorldSeed(features)) )) .with(FeatureKey.SLIME_CHUNK_ORACLE, VersionFeature.fixed(features -> new SlimeChunkOracle(getWorldSeed(features)) )) .with(FeatureKey.WORLD_SPAWN_ORACLE, VersionFeature.fixed(features -> new HeuristicWorldSpawnOracle( getWorldSeed(features), getBiomeOracle(features, Dimension.OVERWORLD), features.get(SPAWN_VALID_BIOMES)) )) .with(SPAWN_VALID_BIOMES, VersionFeature.<Integer> listBuilder() .init( DefaultBiomes.forest, DefaultBiomes.plains, DefaultBiomes.taiga ).sinceExtend(RecognisedVersion._12w01a, DefaultBiomes.taigaHills, DefaultBiomes.forestHills ).sinceExtend(RecognisedVersion._12w03a, DefaultBiomes.jungle, DefaultBiomes.jungleHills ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(FeatureKey.NETHER_FORTRESS_PRODUCER, VersionFeature.<WorldIconProducer<Void>> builder() .init(new NoopProducer<>()) .since(RecognisedVersion._b1_9_pre1, VersionFeature.fixed(features -> new NetherFortressProducer_Original(getWorldSeed(features))) ).since(RecognisedVersion._20w16a, VersionFeature.fixed(features -> NetherFortressProducer_Scattered.create( getWorldSeed(features), features.get(NETHER_BUILDING_SALT), features.get(NETHER_BUILDING_SPACING), features.get(NETHER_BUILDING_SEPARATION), features.get(BUGGY_STRUCTURE_COORDINATE_MATH), features.get(NETHER_FORTRESS_FUNCTION) ) ) ).construct()) .with(NETHER_FORTRESS_FUNCTION, VersionFeature.<Function<FastRand, Boolean>> builder() .init( r -> r.nextInt(6) < 2 ).since(RecognisedVersion._1_16_pre3, r -> r.nextInt(5) < 2 ).construct()) .with(FeatureKey.BASTION_REMNANT_PRODUCER, VersionFeature.<WorldIconProducer<Void>> builder() .init(new NoopProducer<>()) .since(RecognisedVersion._20w16a, VersionFeature.fixed(features -> BastionRemnantProducer.create( getWorldSeed(features), getBiomeOracle(features, Dimension.NETHER), features.get(BASTION_REMNANT_VALID_MIDDLE_CHUNK_BIOMES), features.get(NETHER_BUILDING_SALT), features.get(NETHER_BUILDING_SPACING), features.get(NETHER_BUILDING_SEPARATION), features.get(BUGGY_STRUCTURE_COORDINATE_MATH), features.get(BASTION_REMNANT_FUNCTION) ) ) ).construct()) .with(BASTION_REMNANT_VALID_MIDDLE_CHUNK_BIOMES, VersionFeature.<Integer> listBuilder() .init() .sinceExtend(RecognisedVersion._20w16a, DefaultBiomes.hell, DefaultBiomes.soulSandValley, DefaultBiomes.crimsonForest, DefaultBiomes.warpedForest ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(BASTION_REMNANT_FUNCTION, VersionFeature.<Function<FastRand, Boolean>> builder() .init( r -> r.nextInt(6) >= 2 ).since(RecognisedVersion._1_16_pre3, r -> r.nextInt(5) >= 2 ).construct()) .with(NETHER_BUILDING_SALT, VersionFeature.constant(30084232L)) .with(NETHER_BUILDING_SPACING, VersionFeature.<Byte> builder() .init( (byte) 24 ).since(RecognisedVersion._20w19a, (byte) 30 ).since(RecognisedVersion._1_16_pre3, (byte) 27 ).construct() ) .with(NETHER_BUILDING_SEPARATION, VersionFeature.constant((byte) 4)) .with(FeatureKey.END_CITY_PRODUCER, VersionFeature.<WorldIconProducer<List<EndIsland>>> builder() .init(new NoopProducer<>()) .since(RecognisedVersion._15w31c, VersionFeature.fixed(features -> new RegionalStructureProducer<List<EndIsland>>( Resolution.CHUNK, 8, null, new EndCityWorldIconTypeProvider(), Dimension.END, false, getWorldSeed(features), 10387313L, (byte) 20, (byte) 11, true, features.get(BUGGY_STRUCTURE_COORDINATE_MATH) ) ) ).construct()) .with(MINESHAFT_LOCATION_CHECKER, VersionFeature.<LocationChecker> builder() .init( VersionFeature.fixed(features -> new MineshaftAlgorithm_Original(getWorldSeed(features))) ).since(RecognisedVersion._1_4_2, VersionFeature.fixed(features -> new MineshaftAlgorithm_ChanceBased(getWorldSeed(features), 0.01D, true)) ).since(RecognisedVersion._1_7_2, VersionFeature.fixed(features -> new MineshaftAlgorithm_ChanceBased(getWorldSeed(features), 0.004D, true)) ).since(RecognisedVersion._18w06a, VersionFeature.fixed(features -> new MineshaftAlgorithm_ChanceBased(getWorldSeed(features), 0.004D, false)) ).construct()) .with(FeatureKey.MINESHAFT_PRODUCER, VersionFeature.<WorldIconProducer<Void>>builder() .init(new NoopProducer<>()) .since(RecognisedVersion._b1_8_1, // this should be beta 1.8 pre-release VersionFeature.fixed(features -> new ChunkStructureProducer<>( Resolution.CHUNK, 8, features.get(MINESHAFT_LOCATION_CHECKER), new ImmutableWorldIconTypeProvider(DefaultWorldIconTypes.MINESHAFT), Dimension.OVERWORLD, false )) ).construct()) .with(FeatureKey.STRONGHOLD_PRODUCER, VersionFeature.<CachedWorldIconProducer>builder() .init(new CachedWorldIconProducer.Empty()) .since(RecognisedVersion._b1_8_1, // Actually starts at beta 1.8, with a single stronghold per world VersionFeature.fixed(features -> new StrongholdProducer_Original( getWorldSeed(features), getBiomeOracle(features, Dimension.OVERWORLD), features.get(STRONGHOLD_VALID_MIDDLE_CHUNK_BIOMES) )) ).since(RecognisedVersion._15w43c, // this should be 15w43a, which is not recognised VersionFeature.fixed(features -> new StrongholdProducer_Buggy128Algorithm( getWorldSeed(features), getBiomeOracle(features, Dimension.OVERWORLD), features.get(STRONGHOLD_VALID_MIDDLE_CHUNK_BIOMES) )) ).since(RecognisedVersion._1_9_pre2, // this should be 16w06a VersionFeature.fixed(features -> new StrongholdProducer_128Algorithm( getWorldSeed(features), getBiomeOracle(features, Dimension.OVERWORLD), features.get(STRONGHOLD_VALID_MIDDLE_CHUNK_BIOMES) )) ) .construct()) .with(STRONGHOLD_VALID_MIDDLE_CHUNK_BIOMES, VersionFeature.<Integer> listBuilder() .init( DefaultBiomes.desert, DefaultBiomes.forest, DefaultBiomes.extremeHills, DefaultBiomes.swampland ).sinceExtend(RecognisedVersion._b1_9_pre6, DefaultBiomes.taiga, DefaultBiomes.icePlains, DefaultBiomes.iceMountains ).sinceExtend(RecognisedVersion._1_1, DefaultBiomes.desertHills, DefaultBiomes.forestHills, DefaultBiomes.extremeHillsEdge ).sinceExtend(RecognisedVersion._12w03a, DefaultBiomes.jungle, DefaultBiomes.jungleHills ).since(RecognisedVersion._13w36a, VersionFeature.fixed(features -> // this includes all the biomes above, except for the swampland getValidBiomesForStrongholdSinceV13w36a(features.get(FeatureKey.BIOME_LIST)) )).sinceExtend(RecognisedVersion._18w06a, DefaultBiomes.mushroomIslandShore ).sinceRemove(RecognisedVersion._20w21a, // MC-199298 DefaultBiomes.bambooJungle, DefaultBiomes.bambooJungleHills ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(FeatureKey.VILLAGE_PRODUCER, VersionFeature.fixed(features -> new VillageProducer( getBiomeOracle(features, Dimension.OVERWORLD), features.get(VILLAGE_VALID_BIOMES), getWorldSeed(features), features.get(DO_COMPLEX_VILLAGE_CHECK), features.get(BUGGY_STRUCTURE_COORDINATE_MATH) ) )) .with(VILLAGE_VALID_BIOMES, VersionFeature.<Integer> listBuilder() .init() .sinceExtend(RecognisedVersion._b1_8_1, // this should be b1.8 pre-release DefaultBiomes.plains, DefaultBiomes.desert ).sinceExtend(RecognisedVersion._13w36a, DefaultBiomes.savanna ).sinceExtend(RecognisedVersion._16w20a, DefaultBiomes.taiga ).sinceExtend(RecognisedVersion._18w49a, DefaultBiomes.icePlains ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(DO_COMPLEX_VILLAGE_CHECK, VersionFeature.<Boolean> builder() .init( true ).since(RecognisedVersion._16w20a, false ).construct()) .with(FeatureKey.PILLAGER_OUTPOST_PRODUCER, VersionFeature.fixed(features -> new PillagerOutpostProducer( getBiomeOracle(features, Dimension.OVERWORLD), features.get(PILLAGER_OUTPOST_VALID_BIOMES), getWorldSeed(features), features.get(FeatureKey.VILLAGE_PRODUCER), features.get(OUTPOST_VILLAGE_AVOID_DISTANCE), features.get(OUTPOST_USE_CHECKED_VILLAGES), features.get(BUGGY_STRUCTURE_COORDINATE_MATH) ) )) .with(PILLAGER_OUTPOST_VALID_BIOMES, VersionFeature.<Integer> listBuilder() .init() .sinceExtend(RecognisedVersion._18w47b, DefaultBiomes.plains, DefaultBiomes.desert, DefaultBiomes.savanna, DefaultBiomes.taiga ).sinceExtend(RecognisedVersion._18w49a, DefaultBiomes.icePlains ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(OUTPOST_VILLAGE_AVOID_DISTANCE, VersionFeature.<Integer> builder() .init( -1 // from 19w11a to 19w13a, outpost towers aren't generated close // to villages, but the structure is still reported by `/locate`. ).since(RecognisedVersion._19w13b, 10 ).construct()) .with(OUTPOST_USE_CHECKED_VILLAGES, VersionFeature.<Boolean> builder() .init( true ).since(RecognisedVersion._20w21a, false ).construct()) .with(FeatureKey.DESERT_TEMPLE_PRODUCER, scatteredFeature( Resolution.CHUNK, 8, DESERT_TEMPLE_VALID_MIDDLE_CHUNK_BIOMES, DefaultWorldIconTypes.DESERT, Dimension.OVERWORLD, DESERT_TEMPLE_SALT)) .with(DESERT_TEMPLE_VALID_MIDDLE_CHUNK_BIOMES, VersionFeature.<Integer> listBuilder() .init( DefaultBiomes.desert ).sinceExtend(RecognisedVersion._12w01a, DefaultBiomes.desertHills ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(DESERT_TEMPLE_SALT, VersionFeature.<Long> builder() .init( 14357617L ).construct()) .with(FeatureKey.IGLOO_PRODUCER, scatteredFeature( Resolution.CHUNK, 8, IGLOO_VALID_MIDDLE_CHUNK_BIOMES, DefaultWorldIconTypes.IGLOO, Dimension.OVERWORLD, IGLOO_SALT)) .with(IGLOO_VALID_MIDDLE_CHUNK_BIOMES, VersionFeature.<Integer> listBuilder() .init() .sinceExtend(RecognisedVersion._15w43c, DefaultBiomes.icePlains, DefaultBiomes.coldTaiga ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(IGLOO_SALT, VersionFeature.<Long> builder() .init( 14357617L ).since(RecognisedVersion._18w06a, 14357618L ).construct()) .with(FeatureKey.JUNGLE_TEMPLE_PRODUCER, scatteredFeature( Resolution.CHUNK, 8, JUNGLE_TEMPLE_VALID_MIDDLE_CHUNK_BIOMES, DefaultWorldIconTypes.JUNGLE, Dimension.OVERWORLD, JUNGLE_TEMPLE_SALT)) .with(JUNGLE_TEMPLE_VALID_MIDDLE_CHUNK_BIOMES, VersionFeature.<Integer> listBuilder() .init() .sinceExtend(RecognisedVersion._12w22a, DefaultBiomes.jungle ).sinceExtend(RecognisedVersion._1_4_2, DefaultBiomes.jungleHills // TODO: jungle temples spawn only since 1.4.2 in jungle hills? ).sinceExtend(RecognisedVersion._19w06a, DefaultBiomes.bambooJungle, DefaultBiomes.bambooJungleHills ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(JUNGLE_TEMPLE_SALT, VersionFeature.<Long> builder() .init( 14357617L ).since(RecognisedVersion._18w06a, 14357619L ).construct()) .with(FeatureKey.WITCH_HUT_PRODUCER, scatteredFeature( Resolution.CHUNK, 8, WITCH_HUT_VALID_MIDDLE_CHUNK_BIOMES, DefaultWorldIconTypes.WITCH, Dimension.OVERWORLD, WITCH_HUT_SALT)) .with(WITCH_HUT_VALID_MIDDLE_CHUNK_BIOMES, VersionFeature.<Integer> listBuilder() .init() .sinceExtend(RecognisedVersion._1_4_2, DefaultBiomes.swampland ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(WITCH_HUT_SALT, VersionFeature.<Long> builder() .init( 14357617L ).since(RecognisedVersion._18w06a, 14357620L ).construct()) .with(FeatureKey.OCEAN_MONUMENT_PRODUCER, VersionFeature.<WorldIconProducer<Void>> builder() .init( VersionFeature.fixed(features -> new OceanMonumentProducer_Original( getWorldSeed(features), getBiomeOracle(features, Dimension.OVERWORLD), features.get(OCEAN_MONUMENT_VALID_MIDDLE_CHUNK_BIOMES), features.get(OCEAN_MONUMENT_VALID_BIOMES), features.get(BUGGY_STRUCTURE_COORDINATE_MATH) )) ).since(RecognisedVersion._15w46a, VersionFeature.fixed(features -> new OceanMonumentProducer_Fixed( getWorldSeed(features), getBiomeOracle(features, Dimension.OVERWORLD), features.get(OCEAN_MONUMENT_VALID_MIDDLE_CHUNK_BIOMES), features.get(OCEAN_MONUMENT_VALID_BIOMES), features.get(BUGGY_STRUCTURE_COORDINATE_MATH) )) ).construct()) .with(OCEAN_MONUMENT_VALID_MIDDLE_CHUNK_BIOMES, VersionFeature.<Integer> listBuilder() .init() .sinceExtend(RecognisedVersion._1_8, DefaultBiomes.deepOcean ).sinceExtend(RecognisedVersion._18w08a, DefaultBiomes.coldDeepOcean, DefaultBiomes.warmDeepOcean, DefaultBiomes.lukewarmDeepOcean, DefaultBiomes.frozenDeepOcean ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(OCEAN_MONUMENT_VALID_BIOMES, VersionFeature.<Integer> listBuilder() .init().sinceExtend(RecognisedVersion._1_8, DefaultBiomes.ocean, DefaultBiomes.deepOcean, DefaultBiomes.frozenOcean, DefaultBiomes.river, DefaultBiomes.frozenRiver ).sinceExtend(RecognisedVersion._18w08a, DefaultBiomes.coldOcean, DefaultBiomes.coldDeepOcean, DefaultBiomes.warmOcean, DefaultBiomes.warmDeepOcean, DefaultBiomes.lukewarmOcean, DefaultBiomes.lukewarmDeepOcean, DefaultBiomes.frozenDeepOcean ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(FeatureKey.WOODLAND_MANSION_PRODUCER, VersionFeature.fixed(features -> new RegionalStructureProducer<> ( Resolution.CHUNK, 8, new StructureBiomeLocationChecker(getBiomeOracle(features, Dimension.OVERWORLD), 32, features.get(WOODLAND_MANSION_VALID_BIOMES)), new ImmutableWorldIconTypeProvider(DefaultWorldIconTypes.WOODLAND_MANSION), Dimension.OVERWORLD, false, getWorldSeed(features), 10387319L, (byte) 80, (byte) 20, true, features.get(BUGGY_STRUCTURE_COORDINATE_MATH) ) )) .with(WOODLAND_MANSION_VALID_BIOMES, VersionFeature.<Integer> listBuilder() .init().sinceExtend(RecognisedVersion._16w43a, // Actually 16w39a, but version strings are identical DefaultBiomes.roofedForest, DefaultBiomes.roofedForestM ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(FeatureKey.OCEAN_RUINS_PRODUCER, scatteredFeature( Resolution.CHUNK, 8, OCEAN_RUINS_VALID_MIDDLE_CHUNK_BIOMES, DefaultWorldIconTypes.OCEAN_RUINS, Dimension.OVERWORLD, OCEAN_RUINS_SALT, OCEAN_RUINS_SPACING, OCEAN_RUINS_SEPARATION)) .with(OCEAN_RUINS_VALID_MIDDLE_CHUNK_BIOMES, VersionFeature.<Integer> listBuilder() .init() .sinceExtend(RecognisedVersion._18w09a, DefaultBiomes.ocean, DefaultBiomes.deepOcean, DefaultBiomes.coldOcean, DefaultBiomes.coldDeepOcean, DefaultBiomes.warmOcean, DefaultBiomes.warmDeepOcean, DefaultBiomes.lukewarmOcean, DefaultBiomes.lukewarmDeepOcean, DefaultBiomes.frozenOcean, DefaultBiomes.frozenDeepOcean ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(OCEAN_RUINS_SEPARATION, VersionFeature.<Byte> builder() .init( (byte) 8 ).construct()) .with(OCEAN_RUINS_SPACING, VersionFeature.<Byte> builder() .init( (byte) 16 ).since(RecognisedVersion._20w06a, (byte) 20 ).construct()) .with(OCEAN_RUINS_SALT, VersionFeature.<Long> builder() .init( 14357621L ).construct()) .with(FeatureKey.SHIPWRECK_PRODUCER, scatteredFeature( Resolution.CHUNK, 8, SHIPWRECK_VALID_MIDDLE_CHUNK_BIOMES, DefaultWorldIconTypes.SHIPWRECK, Dimension.OVERWORLD, SHIPWRECK_SALT, SHIPWRECK_SPACING, SHIPWRECK_SEPARATION)) .with(SHIPWRECK_VALID_MIDDLE_CHUNK_BIOMES, VersionFeature.<Integer> listBuilder() .init() .sinceExtend(RecognisedVersion._18w11a, DefaultBiomes.beach, DefaultBiomes.coldBeach, DefaultBiomes.ocean, DefaultBiomes.deepOcean, DefaultBiomes.coldOcean, DefaultBiomes.coldDeepOcean, DefaultBiomes.warmOcean, DefaultBiomes.warmDeepOcean, DefaultBiomes.lukewarmOcean, DefaultBiomes.lukewarmDeepOcean, DefaultBiomes.frozenOcean, DefaultBiomes.frozenDeepOcean ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(SHIPWRECK_SPACING, VersionFeature.<Byte> builder() .init( (byte) 15 ).since(RecognisedVersion._1_13_pre7, (byte) 16 ).since(RecognisedVersion._20w06a, (byte) 24 ).construct()) .with(SHIPWRECK_SEPARATION, VersionFeature.<Byte> builder() .init( (byte) 8 ).since(RecognisedVersion._20w06a, (byte) 4 ).construct()) .with(SHIPWRECK_SALT, VersionFeature.<Long> builder() .init( 165745295L ).construct()) .with(FeatureKey.BURIED_TREASURE_PRODUCER, VersionFeature.fixed(features -> new ChunkStructureProducer<>( Resolution.CHUNK, 9, new BuriedTreasureLocationChecker( getWorldSeed(features), getBiomeOracle(features, Dimension.OVERWORLD), features.get(BURIED_TREASURE_VALID_MIDDLE_CHUNK_BIOMES), features.get(BURIED_TREASURE_SALT) ), new ImmutableWorldIconTypeProvider(DefaultWorldIconTypes.BURIED_TREASURE), Dimension.OVERWORLD, false ) )) .with(BURIED_TREASURE_VALID_MIDDLE_CHUNK_BIOMES, VersionFeature.<Integer> listBuilder() .init().sinceExtend(RecognisedVersion._18w10d, DefaultBiomes.beach, DefaultBiomes.coldBeach ).construct().andThenFixed(DefaultVersionFeatures::makeBiomeList)) .with(BURIED_TREASURE_SALT, VersionFeature.<Long> builder() .init( 10387320L ).construct()) .with(BUGGY_STRUCTURE_COORDINATE_MATH, VersionFeature.<Boolean> builder() .init( false ).since(RecognisedVersion._18w06a, true // Bug MC-131462. ).since(RecognisedVersion._1_13_pre4, false ).since(RecognisedVersion._1_13_pre7, true // Bug MC-131462, again. ).since(RecognisedVersion._18w30b, // actually 18w30a false ).construct()); private static BiomeDataOracle.Config getBiomeOracleConfig(VersionFeatures features) { BiomeDataOracle.Config config = new BiomeDataOracle.Config(); config.quarterResOverride = features.get(BIOME_DATA_ORACLE_QUARTER_RES_OVERRIDE); config.middleOfChunkOffset = features.get(BIOME_DATA_ORACLE_MIDDLE_OF_CHUNK_OFFSET); config.accurateLocationCount = features.get(BIOME_DATA_ORACLE_ACCURATE_LOCATION_COUNT); return config; } private static List<Integer> getValidBiomesForStrongholdSinceV13w36a(BiomeList biomeList) { List<Integer> result = new ArrayList<>(); for (Biome biome : biomeList.iterable()) { if (biome.getType().getBiomeDepth() > 0) { result.add(biome.getId()); } } return result; } private static List<Biome> makeBiomeList(VersionFeatures features, List<Integer> biomeIds) { BiomeList biomeList = features.get(FeatureKey.BIOME_LIST); List<Biome> biomes = biomeIds.stream() .flatMap(id -> { try { return Stream.of(biomeList.getById(id)); } catch (UnknownBiomeIdException e) { AmidstLogger.warn("Unknown biome id found in version features: " + id + ", skipping"); return Stream.empty(); } }) .collect(Collectors.toList()); return Collections.unmodifiableList(biomes); } private static long getWorldSeed(VersionFeatures features) { return features.get(FeatureKey.WORLD_OPTIONS).getWorldSeed().getLong(); } private static BiomeDataOracle getBiomeOracle(VersionFeatures features, Dimension dimension) { switch (dimension) { case OVERWORLD: return features.get(FeatureKey.OVERWORLD_BIOME_DATA_ORACLE); case NETHER: Optional<BiomeDataOracle> oracle = features.get(FeatureKey.NETHER_BIOME_DATA_ORACLE); if (oracle.isPresent()) { return oracle.get(); } default: throw new RuntimeException("Can't retrieve BiomeDataOracle for dimension " + dimension); } } private static VersionFeature<WorldIconProducer<Void>> scatteredFeature( Resolution resolution, int offsetInWorld, FeatureKey<List<Biome>> validBiomes, DefaultWorldIconTypes iconType, Dimension dimension, FeatureKey<Long> salt, FeatureKey<Byte> spacing, FeatureKey<Byte> separation) { return VersionFeature.fixed(features -> new ScatteredFeaturesProducer( resolution, offsetInWorld, getBiomeOracle(features, dimension), validBiomes == null ? null : features.get(validBiomes), new ImmutableWorldIconTypeProvider(iconType), dimension, false, getWorldSeed(features), features.get(salt), features.get(spacing), features.get(separation), features.get(BUGGY_STRUCTURE_COORDINATE_MATH) ) ); } private static VersionFeature<WorldIconProducer<Void>> scatteredFeature( Resolution resolution, int offsetInWorld, FeatureKey<List<Biome>> validBiomes, DefaultWorldIconTypes iconType, Dimension dimension, FeatureKey<Long> salt) { return VersionFeature.fixed(features -> new ScatteredFeaturesProducer( resolution, offsetInWorld, getBiomeOracle(features, dimension), validBiomes == null ? null : features.get(validBiomes), new ImmutableWorldIconTypeProvider(iconType), dimension, false, getWorldSeed(features), features.get(salt), features.get(BUGGY_STRUCTURE_COORDINATE_MATH) ) ); } }
amidst
src\main\java\amidst\mojangapi\world\versionfeatures\FeatureKey.java
package amidst.mojangapi.world.versionfeatures; import java.util.List; import java.util.Optional; import amidst.documentation.Immutable; import amidst.mojangapi.world.WorldOptions; import amidst.mojangapi.world.biome.BiomeList; import amidst.mojangapi.world.icon.producer.CachedWorldIconProducer; import amidst.mojangapi.world.icon.producer.VillageProducer; import amidst.mojangapi.world.icon.producer.WorldIconProducer; import amidst.mojangapi.world.oracle.BiomeDataOracle; import amidst.mojangapi.world.oracle.EndIsland; import amidst.mojangapi.world.oracle.EndIslandOracle; import amidst.mojangapi.world.oracle.SlimeChunkOracle; import amidst.mojangapi.world.oracle.WorldSpawnOracle; @Immutable public class FeatureKey<T> { // @formatter:off public static final FeatureKey<WorldOptions> WORLD_OPTIONS = make(); public static final FeatureKey<BiomeDataOracle> OVERWORLD_BIOME_DATA_ORACLE = make(); public static final FeatureKey<Optional<BiomeDataOracle>> NETHER_BIOME_DATA_ORACLE = make(); public static final FeatureKey<BiomeList> BIOME_LIST = make(); public static final FeatureKey<List<Integer>> ENABLED_LAYERS = make(); public static final FeatureKey<SlimeChunkOracle> SLIME_CHUNK_ORACLE = make(); public static final FeatureKey<EndIslandOracle> END_ISLAND_ORACLE = make(); public static final FeatureKey<WorldSpawnOracle> WORLD_SPAWN_ORACLE = make(); public static final FeatureKey<WorldIconProducer<Void>> NETHER_FORTRESS_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<Void>> BASTION_REMNANT_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<List<EndIsland>>> END_CITY_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<Void>> MINESHAFT_PRODUCER = make(); public static final FeatureKey<CachedWorldIconProducer> STRONGHOLD_PRODUCER = make(); public static final FeatureKey<VillageProducer> VILLAGE_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<Void>> PILLAGER_OUTPOST_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<Void>> DESERT_TEMPLE_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<Void>> IGLOO_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<Void>> JUNGLE_TEMPLE_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<Void>> WITCH_HUT_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<Void>> OCEAN_MONUMENT_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<Void>> WOODLAND_MANSION_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<Void>> OCEAN_RUINS_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<Void>> SHIPWRECK_PRODUCER = make(); public static final FeatureKey<WorldIconProducer<Void>> BURIED_TREASURE_PRODUCER = make(); // @formatter:on private final StackTraceElement location; private FeatureKey(StackTraceElement location) { this.location = location; } public static<T> FeatureKey<T> make() { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); if (stackTrace.length < 2 || !stackTrace[2].getMethodName().equals("<clinit>")) { throw new IllegalStateException("make() must be called from a static initializer"); } return new FeatureKey<>(stackTrace[2]); } @Override public String toString() { return "(" + location.getFileName() + ":" + location.getLineNumber() + ")"; } }
amidst
src\main\java\amidst\mojangapi\world\versionfeatures\VersionFeature.java
package amidst.mojangapi.world.versionfeatures; import java.util.function.BiFunction; import java.util.function.Function; import amidst.mojangapi.minecraftinterface.RecognisedVersion; @FunctionalInterface public interface VersionFeature<V> { public V getValue(RecognisedVersion version, VersionFeatures features); public static<V> VersionFeatureBuilder<V, ?> builder() { return new VersionFeatureBuilder<>(); } public static<V> VersionFeatureListBuilder<V, ?> listBuilder() { return new VersionFeatureListBuilder<>(); } public static<V> VersionFeature<V> constant(V value) { return (version, features) -> value; } public static<V> VersionFeature<V> fixed(Function<VersionFeatures, V> factory) { return (version, features) -> factory.apply(features); } public default<W> VersionFeature<W> andThen(Function<V, W> mapper) { return (version, features) -> mapper.apply(this.getValue(version, features)); } public default<W> VersionFeature<W> andThenFixed(BiFunction<VersionFeatures, V, W> mapper) { return (version, features) -> mapper.apply(features, this.getValue(version, features)); } }
amidst
src\main\java\amidst\mojangapi\world\versionfeatures\VersionFeatureBuilder.java
package amidst.mojangapi.world.versionfeatures; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import java.util.function.UnaryOperator; import amidst.documentation.NotThreadSafe; import amidst.mojangapi.minecraftinterface.RecognisedVersion; import amidst.mojangapi.world.versionfeatures.VersionFeatureImpl.Entry; @NotThreadSafe public class VersionFeatureBuilder<V, B extends VersionFeatureBuilder<V, B>> { private RecognisedVersion previousVersion; private List<Entry<V>> entriesOldestFirst; public VersionFeatureBuilder() { this.previousVersion = null; this.entriesOldestFirst = new ArrayList<>(); } @SuppressWarnings("unchecked") protected final B self() { return (B) this; } public B init(VersionFeature<V> defaultValue) { if (!this.entriesOldestFirst.isEmpty()) { throw new IllegalStateException("only one default value is allowed"); } this.entriesOldestFirst.add(Entry.defaultValue(defaultValue)); return self(); } public B init(V defaultValue) { return init(VersionFeature.constant(defaultValue)); } private B addEntry(Entry<V> entry) { if (this.entriesOldestFirst.isEmpty()) { throw new IllegalStateException("you must specify a default value first"); } else if (previousVersion != null && entry.getVersion() == previousVersion) { throw new IllegalStateException("you can only specify one value per version"); } else if (previousVersion != null && RecognisedVersion.isOlderOrEqualTo(entry.getVersion(), previousVersion)) { throw new IllegalStateException("you have to specify versions in ascending order"); } entriesOldestFirst.add(entry); previousVersion = entry.getVersion(); return self(); } public B since(RecognisedVersion version, VersionFeature<V> value) { return addEntry(Entry.since(version, value)); } public B since(RecognisedVersion version, V value) { return since(version, VersionFeature.constant(value)); } public B sinceUpdateFeature(RecognisedVersion version, Function<V, VersionFeature<V>> valueUpdater) { return addEntry(Entry.sinceUpdate(version, valueUpdater)); } public B sinceUpdate(RecognisedVersion version, UnaryOperator<V> valueUpdater) { return sinceUpdateFeature(version, oldValue -> VersionFeature.constant(valueUpdater.apply(oldValue))); } public VersionFeature<V> construct() { if (this.entriesOldestFirst.isEmpty()) { throw new IllegalStateException("you must specify a default value first"); } return new VersionFeatureImpl<>(entriesOldestFirst.subList(0, entriesOldestFirst.size())); } }
amidst
src\main\java\amidst\mojangapi\world\versionfeatures\VersionFeatureImpl.java
package amidst.mojangapi.world.versionfeatures; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.function.Function; import amidst.documentation.Immutable; import amidst.mojangapi.minecraftinterface.RecognisedVersion; @Immutable public class VersionFeatureImpl<V> implements VersionFeature<V> { private final List<Entry<V>> entriesOldestFirst; public VersionFeatureImpl(List<Entry<V>> entriesOldestFirst) { if (!entriesOldestFirst.isEmpty()) { Entry<?> first = entriesOldestFirst.get(0); if (first.version == null && first.valueSupplier != null) { this.entriesOldestFirst = entriesOldestFirst; return; } } throw new IllegalArgumentException("invalid entry list"); } @Override public V getValue(RecognisedVersion version, VersionFeatures features) { Iterator<Entry<V>> entries = getEntriesToApply(version); V value = entries.next().createValue(version, features); while (entries.hasNext()) { value = entries.next().updateValue(version, features, value); } return value; } private Iterator<Entry<V>> getEntriesToApply(RecognisedVersion version) { int until = entriesOldestFirst.size(); Entry<?> entry; do { entry = entriesOldestFirst.get(--until); } while (!entry.isApplicableTo(version)); int from = until; do { entry = entriesOldestFirst.get(from--); } while (entry.needsPreviousValue()); return entriesOldestFirst.subList(from+1, until+1).iterator(); } @Immutable public static class Entry<V> { private final RecognisedVersion version; private final VersionFeature<V> valueSupplier; private final Function<V, VersionFeature<V>> valueUpdater; private Entry(RecognisedVersion version, VersionFeature<V> supplier, Function<V, VersionFeature<V>> updater) { this.version = version; this.valueSupplier = supplier; this.valueUpdater = updater; } public static<V> Entry<V> defaultValue(VersionFeature<V> valueSupplier) { return new Entry<>(null, Objects.requireNonNull(valueSupplier), null); } public static<V> Entry<V> since(RecognisedVersion version, VersionFeature<V> valueSupplier) { return new Entry<>(Objects.requireNonNull(version), Objects.requireNonNull(valueSupplier), null); } public static<V> Entry<V> sinceUpdate(RecognisedVersion version, Function<V, VersionFeature<V>> valueUpdater) { return new Entry<>(Objects.requireNonNull(version), null, Objects.requireNonNull(valueUpdater)); } public RecognisedVersion getVersion() { return this.version; } public boolean isApplicableTo(RecognisedVersion version) { return this.version == null || RecognisedVersion.isOlderOrEqualTo(this.version, version); } public boolean needsPreviousValue() { return this.valueSupplier == null; } public V createValue(RecognisedVersion version, VersionFeatures features) { V value = this.valueSupplier.getValue(version, features); return Objects.requireNonNull(value, "feature value cannot be null"); } public V updateValue(RecognisedVersion version, VersionFeatures features, V oldValue) { V value = this.valueUpdater.apply(oldValue).getValue(version, features); return Objects.requireNonNull(value, "feature value cannot be null"); } } }
amidst
src\main\java\amidst\mojangapi\world\versionfeatures\VersionFeatureListBuilder.java
package amidst.mojangapi.world.versionfeatures; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import amidst.mojangapi.minecraftinterface.RecognisedVersion; public class VersionFeatureListBuilder<V, B extends VersionFeatureListBuilder<V, B>> extends VersionFeatureBuilder<List<V>, B> { public VersionFeatureListBuilder() { super(); } @SafeVarargs public final B init(V... defaultValues) { return init((version, features) -> new ArrayList<>(Arrays.asList(defaultValues))); } @SafeVarargs public final B since(RecognisedVersion since, V... values) { return since(since, (version, features) -> new ArrayList<>(Arrays.asList(values))); } @SafeVarargs public final B sinceExtend(RecognisedVersion since, V... additionalValues) { return sinceUpdate(since, oldValue -> { for (V additionalValue: additionalValues) { oldValue.add(additionalValue); } return oldValue; }); } @SafeVarargs public final B sinceRemove(RecognisedVersion since, V... removedValues) { return sinceUpdate(since, oldValue -> { for (V removedValue: removedValues) { oldValue.remove(removedValue); } return oldValue; }); } @Override public VersionFeature<List<V>> construct() { return super.construct().andThen(Collections::unmodifiableList); } }
amidst
src\main\java\amidst\mojangapi\world\versionfeatures\VersionFeatures.java
package amidst.mojangapi.world.versionfeatures; import java.util.IdentityHashMap; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import amidst.documentation.Immutable; import amidst.documentation.ThreadSafe; import amidst.mojangapi.minecraftinterface.RecognisedVersion; @Immutable @ThreadSafe public class VersionFeatures { private final RecognisedVersion version; private final Map<FeatureKey<?>, Entry<?>> featureEntries; private VersionFeatures(RecognisedVersion version, Map<FeatureKey<?>, Entry<?>> featureEntries) { this.version = version; this.featureEntries = featureEntries; } public<T> T get(FeatureKey<T> key) { if (!featureEntries.containsKey(key)) { throw new IllegalArgumentException("unknown feature " + key); } @SuppressWarnings("unchecked") Entry<T> entry = (Entry<T>) featureEntries.get(key); return entry.getOrCompute(this); } public static Builder builder() { return new Builder(); } public static class Builder implements Cloneable { private final Map<FeatureKey<?>, Entry<?>> features; private Builder() { features = new IdentityHashMap<>(); } private Builder(Builder builder) { features = new IdentityHashMap<>(builder.features); } private<T> Builder addEntry(FeatureKey<T> key, Entry<T> entry) { Objects.requireNonNull(key); if (features.containsKey(key)) { throw new IllegalArgumentException("the feature " + key + " was already set"); } features.put(key, entry); return this; } public<T> Builder with(FeatureKey<T> key, VersionFeature<T> feature) { return addEntry(key, new Entry<>(Objects.requireNonNull(feature))); } public<T> Builder withValue(FeatureKey<T> key, T value) { return addEntry(key, new Entry<>(Objects.requireNonNull(value))); } @Override public Builder clone() { return new Builder(this); } public VersionFeatures create(RecognisedVersion version) { return new VersionFeatures( version, features.entrySet().stream().collect(Collectors.toMap( e -> e.getKey(), e -> new Entry<>(e.getValue()), (v1, v2) -> { throw new IllegalStateException("duplicate key"); }, IdentityHashMap::new )) ); } } private static class Entry<T> { // Three possible states : // - value == null, feature != null: the value isn't computed yet // - value == null, feature == null: the value is currently being computed // - value != null, feature == null: the value is computed private T value; private VersionFeature<T> feature; public Entry(VersionFeature<T> feature) { this.value = null; this.feature = feature; } public Entry(T value) { this.value = value; this.feature = null; } public Entry(Entry<T> other) { this.value = other.value; this.feature = other.feature; } public synchronized T getOrCompute(VersionFeatures features) { if (value != null) { return value; } VersionFeature<T> tmpFeature = feature; if (tmpFeature == null) { throw new IllegalStateException("Circular feature loading"); } feature = null; value = tmpFeature.getValue(features.version, features); if (value == null) { feature = tmpFeature; throw new NullPointerException("Feature value can't be null"); } return value; } } }
amidst
src\main\java\amidst\mojangapi\world\icon\locationchecker\AllValidLocationChecker.java
package amidst.mojangapi.world.icon.locationchecker; import amidst.documentation.ThreadSafe; @ThreadSafe public class AllValidLocationChecker implements LocationChecker { private final LocationChecker[] checkers; private final boolean hasValidLocation; public AllValidLocationChecker(LocationChecker... checkers) { this.checkers = checkers; hasValidLocation = getHasValidLocation(checkers); } @Override public boolean isValidLocation(int x, int y) { for (LocationChecker checker : checkers) { if (!checker.isValidLocation(x, y)) { return false; } } return true; } @Override public boolean hasValidLocations() { return hasValidLocation; } private static boolean getHasValidLocation(LocationChecker[] checkers) { for(LocationChecker checker: checkers) { if(!checker.hasValidLocations()) return false; } return true; } }
amidst
src\main\java\amidst\mojangapi\world\icon\locationchecker\BiomeLocationChecker.java
package amidst.mojangapi.world.icon.locationchecker; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.oracle.BiomeDataOracle; @ThreadSafe public class BiomeLocationChecker implements LocationChecker { private final BiomeDataOracle biomeDataOracle; private final List<Biome> validBiome; public BiomeLocationChecker(BiomeDataOracle biomeDataOracle, List<Biome> validBiomes) { this.biomeDataOracle = biomeDataOracle; this.validBiome = validBiomes; } @Override public boolean isValidLocation(int x, int y) { return biomeDataOracle.isValidBiomeAtMiddleOfChunk(x, y, validBiome); } @Override public boolean hasValidLocations() { return !validBiome.isEmpty(); } }
amidst
src\main\java\amidst\mojangapi\world\icon\locationchecker\BuriedTreasureLocationChecker.java
package amidst.mojangapi.world.icon.locationchecker; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.oracle.BiomeDataOracle; import amidst.util.FastRand; @ThreadSafe public class BuriedTreasureLocationChecker extends AllValidLocationChecker { private static final float BURIED_TREASURE_CHANCE = 0.01F; public BuriedTreasureLocationChecker( long seed, BiomeDataOracle biomeDataOracle, List<Biome> validBiomesForStructure, long seedForStructure) { super( new BuriedTreasureAlgorithm(seed + seedForStructure, BURIED_TREASURE_CHANCE), new BiomeLocationChecker(biomeDataOracle, validBiomesForStructure) ); } private static class BuriedTreasureAlgorithm implements LocationChecker { private static final long MAGIC_NUMBER_FOR_SEED_1 = 341873128712L; private static final long MAGIC_NUMBER_FOR_SEED_2 = 132897987541L; private final long seed; private final float chance; public BuriedTreasureAlgorithm(long seed, float chance) { this.seed = seed; this.chance = chance; } @Override public boolean isValidLocation(int x, int y) { FastRand random = new FastRand(x*MAGIC_NUMBER_FOR_SEED_1 + y*MAGIC_NUMBER_FOR_SEED_2 + seed); return random.nextFloat() < chance; } } }
amidst
src\main\java\amidst\mojangapi\world\icon\locationchecker\LocationChecker.java
package amidst.mojangapi.world.icon.locationchecker; import amidst.documentation.ThreadSafe; /** * This should ONLY be used for things where we have to check against * it every time. For example, we have to do this with biome checks * and buried treasures. */ @ThreadSafe public interface LocationChecker { boolean isValidLocation(int x, int y); default boolean hasValidLocations() { return true; } }
amidst
src\main\java\amidst\mojangapi\world\icon\locationchecker\MineshaftAlgorithm_Base.java
package amidst.mojangapi.world.icon.locationchecker; import amidst.documentation.Immutable; import amidst.util.FastRand; @Immutable public abstract class MineshaftAlgorithm_Base implements LocationChecker { private final long seed; public MineshaftAlgorithm_Base(long seed) { this.seed = seed; } @Override public boolean isValidLocation(int chunkX, int chunkY) { /** * Note: even if this check succeeds, the mineshaft may fail to generate if the * central room isn't in a suitable location (for example, if it spawns inside * a cave or a ravine). We can't check these cases, so we will have to accept * some false positives. */ FastRand random = new FastRand(seed); long var13 = chunkX * random.nextLong(); long var15 = chunkY * random.nextLong(); random.setSeed(var13 ^ var15 ^ seed); if(doExtraCheck()) random.advance(); if(!getResult(chunkX, chunkY, random)) return false; return !doExtraCheck() || random.nextInt(80) < Math.max(Math.abs(chunkX), Math.abs(chunkY)); } protected abstract boolean getResult(int chunkX, int chunkY, FastRand random); protected boolean doExtraCheck() { return true; } }
amidst
src\main\java\amidst\mojangapi\world\icon\locationchecker\MineshaftAlgorithm_ChanceBased.java
package amidst.mojangapi.world.icon.locationchecker; import amidst.documentation.Immutable; import amidst.util.FastRand; /** * As of v1.4.2 Minecraft switched to this version of the algorithm */ @Immutable public class MineshaftAlgorithm_ChanceBased extends MineshaftAlgorithm_Base { private final double chancePerChunk; private final boolean extraCheck; public MineshaftAlgorithm_ChanceBased(long seed, double chancePerChunk, boolean extraCheck) { super(seed); this.chancePerChunk = chancePerChunk; this.extraCheck = extraCheck; } @Override protected boolean getResult(int chunkX, int chunkY, FastRand random) { return random.nextDouble() < chancePerChunk; } @Override protected boolean doExtraCheck() { return extraCheck; } }
amidst
src\main\java\amidst\mojangapi\world\icon\locationchecker\MineshaftAlgorithm_Original.java
package amidst.mojangapi.world.icon.locationchecker; import amidst.documentation.Immutable; import amidst.util.FastRand; /** * Empirical testing suggests this version of the algorithm works all the way * back to b1.8, and the Minecraft Wiki says b1.8 was when mineshafts were * introduced, but since Amidst versions only go back as far as * RecognisedVersion.Vb1_8_1 I won't bother to check for pre-mineshaft versions. * * I've not decompiled the very early Minecraft versions, and TheMasterCaver * points out that "for older versions it is possible that the second part of * this code, nextInt(80) < (max of absolute value of chunk coordinates), may * not have been present, resulting in mineshafts being equally as common near * the origin as they currently are 80 or more chunks away." I've included * TheMasterCaver's comment because my empirical testing that Amidst mineshafts * do appear in the game can't tell us whether the very early versions have * fewer mineshafts near the origin. */ @Immutable public class MineshaftAlgorithm_Original extends MineshaftAlgorithm_Base { public MineshaftAlgorithm_Original(long seed) { super(seed); } @Override protected boolean getResult(int chunkX, int chunkY, FastRand random) { return random.nextInt(100) == 0; } }
amidst
src\main\java\amidst\mojangapi\world\icon\locationchecker\RegionRandomLocationChecker.java
package amidst.mojangapi.world.icon.locationchecker; import java.util.function.Function; import amidst.mojangapi.world.icon.producer.RegionalStructureProducer; import amidst.util.FastRand; public class RegionRandomLocationChecker implements LocationChecker { private RegionalStructureProducer<?> regionalProducer; private final Function<FastRand, Boolean> randomFunction; public RegionRandomLocationChecker(Function<FastRand, Boolean> randomFunction) { this.randomFunction = randomFunction; } public void setRegionalProducer(RegionalStructureProducer<?> regionalProducer) { this.regionalProducer = regionalProducer; } @Override public boolean isValidLocation(int chunkX, int chunkY) { FastRand random = new FastRand(regionalProducer.getRegionSeed( regionalProducer.getRegionCoord(chunkX), regionalProducer.getRegionCoord(chunkY) )); random.advance(); random.advance(); if (regionalProducer.isTriangular) { random.advance(); random.advance(); } return randomFunction.apply(random); } }
amidst
src\main\java\amidst\mojangapi\world\icon\locationchecker\StructureBiomeLocationChecker.java
package amidst.mojangapi.world.icon.locationchecker; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.oracle.BiomeDataOracle; @ThreadSafe public class StructureBiomeLocationChecker implements LocationChecker { private final BiomeDataOracle biomeDataOracle; private final int size; private final List<Biome> validBiomes; public StructureBiomeLocationChecker(BiomeDataOracle biomeDataOracle, int size, List<Biome> validBiomes) { this.biomeDataOracle = biomeDataOracle; this.size = size; this.validBiomes = validBiomes; } @Override public boolean isValidLocation(int x, int y) { return biomeDataOracle.isValidBiomeForStructureAtMiddleOfChunk(x, y, size, validBiomes); } @Override public boolean hasValidLocations() { return !validBiomes.isEmpty(); } }
amidst
src\main\java\amidst\mojangapi\world\icon\locationchecker\SuppressAroundLocationChecker.java
package amidst.mojangapi.world.icon.locationchecker; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.icon.producer.RegionalStructureProducer; @ThreadSafe public class SuppressAroundLocationChecker implements LocationChecker { private final RegionalStructureProducer<?> regionalProducer; private final int distance; private final boolean checkLocations; public SuppressAroundLocationChecker(RegionalStructureProducer<?> regionalProducer, int distance, boolean checkLocations) { this.regionalProducer = regionalProducer; this.distance = distance; this.checkLocations = checkLocations; } /** * Adaptation of <a * href=https://github.com/KaptainWutax/FeatureUtils/blob/master/src/main/java/kaptainwutax/featureutils/structure/PillagerOutpost.java#L96>this</a> */ @Override public boolean isValidLocation(int chunkX, int chunkZ) { if (distance < 0) { return true; } CoordinatesInWorld thisStructPos = new CoordinatesInWorld(chunkX, chunkZ); int nwChunkX = chunkX - distance; int nwChunkZ = chunkZ - distance; int seChunkX = chunkX + distance; int seChunkZ = chunkZ + distance; CoordinatesInWorld otherStructPos = getLocation(nwChunkX, nwChunkZ); if (otherStructPos != null && otherStructPos.getDistanceChebyshev(thisStructPos) <= distance) { return false; } int nwRegionX = regionalProducer.getRegionCoord(nwChunkX); int nwRegionZ = regionalProducer.getRegionCoord(nwChunkZ); int seRegionX = regionalProducer.getRegionCoord(seChunkX); int seRegionZ = regionalProducer.getRegionCoord(seChunkZ); //The area is contained within one region. if (nwRegionX == seRegionX && nwRegionZ == seRegionZ) { return true; } //The area intersects 4 regions. if (nwRegionX != seRegionX && nwRegionZ != seRegionZ) { otherStructPos = getLocation(seChunkX, seChunkZ); if (otherStructPos != null && otherStructPos.getDistanceChebyshev(thisStructPos) <= distance) { return false; } otherStructPos = getLocation(nwChunkX, seChunkZ); if (otherStructPos != null && otherStructPos.getDistanceChebyshev(thisStructPos) <= distance) { return false; } otherStructPos = getLocation(seChunkX, nwChunkZ); return !(otherStructPos != null && otherStructPos.getDistanceChebyshev(thisStructPos) <= distance); } //The area intersects 2 regions. otherStructPos = getLocation(seChunkX, seChunkZ); return !(otherStructPos != null && otherStructPos.getDistanceChebyshev(thisStructPos) <= distance); } private CoordinatesInWorld getLocation(int chunkX, int chunkZ) { if (checkLocations) { return regionalProducer.getCheckedLocation(chunkX, chunkZ); } else { return regionalProducer.getPossibleLocation(chunkX, chunkZ); } } }
amidst
src\main\java\amidst\mojangapi\world\icon\locationchecker\VillageAlgorithm.java
package amidst.mojangapi.world.icon.locationchecker; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.oracle.BiomeDataOracle; @ThreadSafe public class VillageAlgorithm implements LocationChecker { private final BiomeDataOracle biomeDataOracle; private final List<Biome> validBiomes; public VillageAlgorithm(BiomeDataOracle biomeDataOracle, List<Biome> validBiomes) { this.biomeDataOracle = biomeDataOracle; this.validBiomes = validBiomes; } @Override public boolean isValidLocation(int chunkX, int chunkY) { // @formatter:off /** * Villages start will a well, size 6 x 6, extending to the right and down from * the village spawn coordinates. The well starts the village bounding box at 6 x 6. * * My hypothesis was as follows: * "If a river or non-valid biome cuts through this area then none of the paths extending from * the well will generate (as I think they each retest the bounding box against valid biomes as they * expand the bounding box). If none of the paths generate then I think the Village fails as a certain number * of buildings are required - it even looks like more than 2 roads may be required." * * Village at [-5008, -8000] and [-6352, -8144] on seed -1364077613 disprove the hypothesis, yet * strangely it still appears to be a fantastic improvement to village accuracy - eliminating 18% of * all villages from the 20km test area with those two being the only false negative I've found (having * checked over half of the eliminated villages). So I'll keep this code in AmidstExporter, but leave * it up to other maintainers to decide if it goes in their versions. * * The village paths must be only biome-testing their own bounding box, rather than the village's, so * beats me why this works so well. I guess because paths each test for bad biomes by an extra 4 blocks * beyond their own bounds, which means that any biome touching the well will most likely be knocking * out 3 of the 4 possible paths, and a village doesn't have much chance of becoming large enough to be * viable from just one path? */ // @formatter:on // For some reason MapGenVillage.Start.Start() adds only 2 to the // multiplied coord int wellSize = 6; int x1 = chunkX * 16 + 2; int y1 = chunkY * 16 + 2; int x2 = x1 + wellSize - 1; int y2 = y1 + wellSize - 1; int wellX = (x1 + x2) / 2; int wellY = (y1 + y2) / 2; // @formatter:off /** * There's an arbitraryConstant of 4 in the Minecraft source that's added to bounding * box sizes to get the "structureSize" for areBiomesViable() (e.g. see func_176069_e()), but * adding 4 to this well heuristic eliminates several villages I have confirmed to exist. The * source is hard to read and (as above) I've obviously missed a lot of how the villages work, * so trying a different tact... * * Setting arbitraryConstant to 1 means a wellStructureSize of 3, which means the area * passed to isValidBiome() will exactly match the visual footprint of the well. Setting * arbitraryConstant to 2 will mean a wellStructureSize of 4 which corresponds to a 1-block * lip around the well also being checked for bad biomes (this test is at 1/4th the block * resolution, too). * Testing all villages within 20km of the seed -1364077613, I see that the difference between * arbitraryConstant of 1 vs 2 is that a value of 2 correctly eliminates a further 8 villages * and none of those 8 villages exist in the game, however values above 2 will eliminate more * villages that do exist (e.g. [2672, -5424] and [3376, -3504]). * * So in lieu of a larger data set, and at the risk of optimizing it to the "training" data, * lets set arbitraryConstant to 2 ;) */ // @formatter:on int arbitraryConstant = 2; int wellStructureSize = (x2 - x1) / 2 + arbitraryConstant; // @formatter:off /** * Checking that the well is able to build eliminates most of the false positives, however * a few remain. Here are some villages unable to build sufficiently beyond the * well (i.e. I have confirmed they do not exist in the game), which are not eliminated by * canSpawnWellAtCoords. Found during testing on seed -1364077613: * * 2912, 2080 * * -5888, 4784 * * -7952, -9424 * * -272, -7872 */ // @formatter:on return biomeDataOracle.isValidBiomeForStructure(wellX, wellY, wellStructureSize, validBiomes); } @Override public boolean hasValidLocations() { return !validBiomes.isEmpty(); } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\BastionRemnantProducer.java
package amidst.mojangapi.world.icon.producer; import java.util.List; import java.util.function.Function; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.coordinates.Resolution; import amidst.mojangapi.world.icon.locationchecker.AllValidLocationChecker; import amidst.mojangapi.world.icon.locationchecker.BiomeLocationChecker; import amidst.mojangapi.world.icon.locationchecker.RegionRandomLocationChecker; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.mojangapi.world.icon.type.ImmutableWorldIconTypeProvider; import amidst.mojangapi.world.oracle.BiomeDataOracle; import amidst.util.FastRand; public class BastionRemnantProducer extends RegionalStructureProducer<Void> { private static final Resolution RESOLUTION = Resolution.NETHER_CHUNK; private static final int OFFSET_IN_WORLD = 88; private static final Dimension DIMENSION = Dimension.NETHER; private static final boolean DISPLAY_DIMENSION = false; private static final boolean IS_TRIANGULAR = false; public static BastionRemnantProducer create( long worldSeed, BiomeDataOracle biomeDataOracle, List<Biome> validBiomesAtMiddleOfChunk, long salt, byte spacing, byte separation, boolean buggyStructureCoordinateMath, Function<FastRand, Boolean> randomFunction) { RegionRandomLocationChecker regionRandomChecker = new RegionRandomLocationChecker(randomFunction); BastionRemnantProducer producer = new BastionRemnantProducer( worldSeed, biomeDataOracle, validBiomesAtMiddleOfChunk, salt, spacing, separation, buggyStructureCoordinateMath, regionRandomChecker ); regionRandomChecker.setRegionalProducer(producer); return producer; } private BastionRemnantProducer( long worldSeed, BiomeDataOracle biomeDataOracle, List<Biome> validBiomesAtMiddleOfChunk, long salt, byte spacing, byte separation, boolean buggyStructureCoordinateMath, RegionRandomLocationChecker regionRandomChecker) { super(RESOLUTION, OFFSET_IN_WORLD, new AllValidLocationChecker( new BiomeLocationChecker(biomeDataOracle, validBiomesAtMiddleOfChunk), regionRandomChecker ), new ImmutableWorldIconTypeProvider(DefaultWorldIconTypes.BASTION_REMNANT), DIMENSION, DISPLAY_DIMENSION, worldSeed, salt, spacing, separation, IS_TRIANGULAR, buggyStructureCoordinateMath ); } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\CachedWorldIconProducer.java
package amidst.mojangapi.world.icon.producer; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import amidst.documentation.ThreadSafe; import amidst.fragment.Fragment; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.icon.WorldIcon; @ThreadSafe public abstract class CachedWorldIconProducer extends WorldIconProducer<Void> { private final Object cacheLock = new Object(); private volatile List<WorldIcon> cache; @Override public void produce(CoordinatesInWorld corner, Consumer<WorldIcon> consumer, Void additionalData) { for (WorldIcon icon : getCache()) { if (icon.getCoordinates().isInBoundsOf(corner, Fragment.SIZE)) { consumer.accept(icon); } } } public List<WorldIcon> getWorldIcons() { return getCache(); } public WorldIcon getFirstWorldIcon() { List<WorldIcon> cache = getCache(); if (cache.isEmpty()) { return null; } else { return cache.get(0); } } public void resetCache() { cache = null; } /** * Gets the list of WorldIcons. Returns the cache and creates it, if * necessary. This will never return null. This also ensures that * createCache is only called by one thread at a time. */ private List<WorldIcon> getCache() { List<WorldIcon> result = cache; if (result == null) { synchronized (cacheLock) { if (cache == null) { cache = createCache(); } result = cache; } } return result; } /** * Creates the list of WorldIcons. This will never return null. */ private List<WorldIcon> createCache() { List<WorldIcon> result = doCreateCache(); if (result == null) { return Collections.emptyList(); } else { return Collections.unmodifiableList(result); } } /** * This actually create the cache. This can return null. This will only be * called by one thread at a time. */ protected abstract List<WorldIcon> doCreateCache(); public static final class Empty extends CachedWorldIconProducer { @Override protected List<WorldIcon> doCreateCache() { return null; } } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\ChunkStructureProducer.java
package amidst.mojangapi.world.icon.producer; import java.util.function.Consumer; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.coordinates.Resolution; import amidst.mojangapi.world.icon.WorldIcon; import amidst.mojangapi.world.icon.locationchecker.LocationChecker; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.mojangapi.world.icon.type.WorldIconTypeProvider; @ThreadSafe public class ChunkStructureProducer<T> extends WorldIconProducer<T> { private final Resolution resolution; private final int size; private final int offsetInWorld; private final LocationChecker checker; private final WorldIconTypeProvider<T> provider; private final Dimension dimension; private final boolean displayDimension; public ChunkStructureProducer( Resolution resolution, int offsetInWorld, LocationChecker checker, WorldIconTypeProvider<T> provider, Dimension dimension, boolean displayDimension) { this.resolution = resolution; this.size = resolution.getStepsPerFragment(); this.offsetInWorld = offsetInWorld; this.checker = checker; this.provider = provider; this.dimension = dimension; this.displayDimension = displayDimension; } @Override public void produce(CoordinatesInWorld corner, Consumer<WorldIcon> consumer, T additionalData) { if(checker != null && !checker.hasValidLocations()) { return; // No need to check if the LocationChecker will never accept anything } for (int xRelativeToFragment = 0; xRelativeToFragment < size; xRelativeToFragment++) { for (int yRelativeToFragment = 0; yRelativeToFragment < size; yRelativeToFragment++) { generateAt(corner, consumer, additionalData, xRelativeToFragment, yRelativeToFragment); } } } // TODO: use longs? private void generateAt( CoordinatesInWorld corner, Consumer<WorldIcon> consumer, T additionalData, int xRelativeToFragment, int yRelativeToFragment) { int x = xRelativeToFragment + (int) corner.getXAs(resolution); int y = yRelativeToFragment + (int) corner.getYAs(resolution); // if there is no checker provided, skip it if (checker == null || checker.isValidLocation(x, y)) { DefaultWorldIconTypes worldIconType = provider.get(x, y, additionalData); if (worldIconType != null) { CoordinatesInWorld coordinates = createCoordinates(corner, xRelativeToFragment, yRelativeToFragment); consumer.accept( new WorldIcon( coordinates, worldIconType.getLabel(), worldIconType.getImage(), dimension, displayDimension)); } } } private CoordinatesInWorld createCoordinates( CoordinatesInWorld corner, int xRelativeToFragment, int yRelativeToFragment) { long xInWorld = resolution.convertFromThisToWorld(xRelativeToFragment); long yInWorld = resolution.convertFromThisToWorld(yRelativeToFragment); return corner.add(xInWorld + offsetInWorld, yInWorld + offsetInWorld); } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\MultiProducer.java
package amidst.mojangapi.world.icon.producer; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.icon.WorldIcon; public class MultiProducer<T> extends WorldIconProducer<T> { private final List<WorldIconProducer<T>> producers; public MultiProducer(List<WorldIconProducer<T>> producers) { this.producers = producers; } @SafeVarargs public MultiProducer(WorldIconProducer<T>... producers) { this(Arrays.asList(producers)); } @Override public void produce(CoordinatesInWorld corner, Consumer<WorldIcon> consumer, T additionalData) { for(WorldIconProducer<T> producer: producers) { producer.produce(corner, consumer, additionalData); } } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\NameFilteredWorldIconCollector.java
package amidst.mojangapi.world.icon.producer; import amidst.documentation.NotThreadSafe; import amidst.mojangapi.world.icon.WorldIcon; @NotThreadSafe public class NameFilteredWorldIconCollector extends WorldIconCollector { private final String name; public NameFilteredWorldIconCollector(String name) { this.name = name; } @Override public void accept(WorldIcon worldIcon) { if (worldIcon.getName().equals(name)) { super.accept(worldIcon); } } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\NetherFortressProducer_Original.java
package amidst.mojangapi.world.icon.producer; import java.util.function.Consumer; import amidst.documentation.Immutable; import amidst.fragment.Fragment; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.coordinates.Resolution; import amidst.mojangapi.world.icon.WorldIcon; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.util.FastRand; @Immutable public class NetherFortressProducer_Original extends WorldIconProducer<Void> { private static final DefaultWorldIconTypes ICON_TYPE = DefaultWorldIconTypes.NETHER_FORTRESS; private static final Dimension DIMENSION = Dimension.NETHER; private static final Resolution RESOLUTION = Resolution.NETHER_CHUNK; private static final int OFFSET_IN_WORLD = 88; private static final int SPACING = 16; // nether chunks (i think) because of the "coord >> 4" bit shift /** * Length of chunks needed to cover the maximum possible regions * intersecting a fragment. */ private static final int INTERSECTING_REGION_CHUNKS = (RESOLUTION.getStepsPerFragment() + SPACING - 1) / SPACING * SPACING; private final long seed; public NetherFortressProducer_Original(long seed) { this.seed = seed; } @Override public void produce(CoordinatesInWorld corner, Consumer<WorldIcon> consumer, Void additionalData) { for (int xRelativeToFragment = 0; xRelativeToFragment <= INTERSECTING_REGION_CHUNKS; xRelativeToFragment += SPACING) { for (int yRelativeToFragment = 0; yRelativeToFragment <= INTERSECTING_REGION_CHUNKS; yRelativeToFragment += SPACING) { generateAt(corner, consumer, xRelativeToFragment, yRelativeToFragment); } } } // TODO: use longs? private void generateAt( CoordinatesInWorld corner, Consumer<WorldIcon> consumer, int xRelativeToFragment, int yRelativeToFragment) { int x = xRelativeToFragment + (int) corner.getXAs(RESOLUTION); int y = yRelativeToFragment + (int) corner.getYAs(RESOLUTION); CoordinatesInWorld checkedLocation = getCheckedLocation(x, y); if(checkedLocation != null) { int possibleX = (int) checkedLocation.getX(); int possibleY = (int) checkedLocation.getY(); CoordinatesInWorld coordinates = createCoordinates(possibleX, possibleY); if(coordinates.isInBoundsOf(corner, Fragment.SIZE)) { consumer.accept( new WorldIcon( coordinates, ICON_TYPE.getLabel(), ICON_TYPE.getImage(), DIMENSION, false)); } } } private CoordinatesInWorld createCoordinates(int structX, int structY) { long xInWorld = RESOLUTION.convertFromThisToWorld(structX); long yInWorld = RESOLUTION.convertFromThisToWorld(structY); return new CoordinatesInWorld(xInWorld + OFFSET_IN_WORLD, yInWorld + OFFSET_IN_WORLD); } private CoordinatesInWorld getCheckedLocation(int x, int y) { int i = x >> 4; int j = y >> 4; FastRand random = new FastRand(i ^ j << 4 ^ seed); random.advance(); if(random.nextInt(3) == 0) { return new CoordinatesInWorld((i << 4) + 4 + random.nextInt(8), (j << 4) + 4 + random.nextInt(8)); } return null; } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\NetherFortressProducer_Scattered.java
package amidst.mojangapi.world.icon.producer; import java.util.function.Function; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.coordinates.Resolution; import amidst.mojangapi.world.icon.locationchecker.RegionRandomLocationChecker; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.mojangapi.world.icon.type.ImmutableWorldIconTypeProvider; import amidst.util.FastRand; public class NetherFortressProducer_Scattered extends RegionalStructureProducer<Void> { private static final Resolution RESOLUTION = Resolution.NETHER_CHUNK; private static final int OFFSET_IN_WORLD = 88; private static final Dimension DIMENSION = Dimension.NETHER; private static final boolean DISPLAY_DIMENSION = false; private static final boolean IS_TRIANGULAR = false; public static NetherFortressProducer_Scattered create( long worldSeed, long salt, byte spacing, byte separation, boolean buggyStructureCoordinateMath, Function<FastRand, Boolean> randomFunction) { RegionRandomLocationChecker regionRandomChecker = new RegionRandomLocationChecker(randomFunction); NetherFortressProducer_Scattered producer = new NetherFortressProducer_Scattered( worldSeed, salt, spacing, separation, buggyStructureCoordinateMath, regionRandomChecker ); regionRandomChecker.setRegionalProducer(producer); return producer; } private NetherFortressProducer_Scattered( long worldSeed, long salt, byte spacing, byte separation, boolean buggyStructureCoordinateMath, RegionRandomLocationChecker regionRandomChecker) { super(RESOLUTION, OFFSET_IN_WORLD, regionRandomChecker, new ImmutableWorldIconTypeProvider(DefaultWorldIconTypes.NETHER_FORTRESS), DIMENSION, DISPLAY_DIMENSION, worldSeed, salt, spacing, separation, IS_TRIANGULAR, buggyStructureCoordinateMath ); } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\NoopProducer.java
package amidst.mojangapi.world.icon.producer; import java.util.function.Consumer; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.icon.WorldIcon; public class NoopProducer<T> extends WorldIconProducer<T> { @Override public void produce(CoordinatesInWorld corner, Consumer<WorldIcon> consumer, T additionalData) {} }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\OceanMonumentProducer_Fixed.java
package amidst.mojangapi.world.icon.producer; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.coordinates.Resolution; import amidst.mojangapi.world.icon.locationchecker.AllValidLocationChecker; import amidst.mojangapi.world.icon.locationchecker.StructureBiomeLocationChecker; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.mojangapi.world.icon.type.ImmutableWorldIconTypeProvider; import amidst.mojangapi.world.oracle.BiomeDataOracle; /** * Bug https://bugs.mojang.com/browse/MC-65214 was fixed in 15w46a, and the fix * changes where Ocean Monuments can appear. This class implements the * RegionalStructureProducer for after the fix was implemented. * * The fix is described here: * https://bugs.mojang.com/browse/MC-65214?focusedCommentId * =228462&page=com.atlassian * .jira.plugin.system.issuetabpanels:comment-tabpanel#comment-228462 That * description is quoted below: * * ---- "The issue lies in that the server is calculating DEEP_BIOME based on * the 1.8 World Generator and NOT the worlds ACTUAL biome from previous * versions. * * I had a report of a biome in OCEAN (Not Deep), and when I generated a 1.8 * world with exact same seed, sure enough that location was DEEP_OCEAN in that * seed. * * The Monument Structure check uses 2 different Biome lookup methods, and the * one that does DEEP_BIOME check uses the World Gen calculations, and then the * followup check for "Surrounding biomes" uses the actual worlds data. * * I temp fixed for my server with the following change: - if * (this.c.getWorldChunkManager().getBiome(new BlockPosition(k * 16 + 8, 64, l * * 16 + 8), (BiomeBase) null) != BiomeBase.DEEP_OCEAN) { + if * (!this.c.getWorldChunkManager().a(k * 16 + 8, l * 16 + 8, 16, * Arrays.asList(BiomeBase.DEEP_OCEAN))) { * * This issue has more flaws than this report states as it also causes monuments * to spawn in the middle of Rivers, Frozen Rivers and Frozen Oceans, which is * quite odd to stroll through the mountains and find a monument." ---- * * Examples: In seed -3189899870270394863, the monuments at (808, 1224) and * (-856, 184) are eliminated by this fix. * */ @ThreadSafe public class OceanMonumentProducer_Fixed extends RegionalStructureProducer<Void> { private static final Resolution RESOLUTION = Resolution.CHUNK; private static final int OFFSET_IN_WORLD = 8; private static final Dimension DIMENSION = Dimension.OVERWORLD; private static final boolean DISPLAY_DIMENSION = false; private static final long SALT = 10387313L; private static final byte SPACING = 32; private static final byte SEPARATION = 5; private static final boolean IS_TRIANGULAR = true; private static final int STRUCTURE_SIZE = 29; private static final int STRUCTURE_CENTER_SIZE = 16; public OceanMonumentProducer_Fixed( long worldSeed, BiomeDataOracle biomeDataOracle, List<Biome> validBiomesAtMiddleOfChunk, List<Biome> validBiomesForStructure, boolean buggyStructureCoordinateMath) { super(RESOLUTION, OFFSET_IN_WORLD, new AllValidLocationChecker( new StructureBiomeLocationChecker(biomeDataOracle, STRUCTURE_CENTER_SIZE, validBiomesAtMiddleOfChunk), new StructureBiomeLocationChecker(biomeDataOracle, STRUCTURE_SIZE, validBiomesForStructure) ), new ImmutableWorldIconTypeProvider(DefaultWorldIconTypes.OCEAN_MONUMENT), DIMENSION, DISPLAY_DIMENSION, worldSeed, SALT, SPACING, SEPARATION, IS_TRIANGULAR, buggyStructureCoordinateMath ); } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\OceanMonumentProducer_Original.java
package amidst.mojangapi.world.icon.producer; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.coordinates.Resolution; import amidst.mojangapi.world.icon.locationchecker.AllValidLocationChecker; import amidst.mojangapi.world.icon.locationchecker.BiomeLocationChecker; import amidst.mojangapi.world.icon.locationchecker.StructureBiomeLocationChecker; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.mojangapi.world.icon.type.ImmutableWorldIconTypeProvider; import amidst.mojangapi.world.oracle.BiomeDataOracle; @ThreadSafe public class OceanMonumentProducer_Original extends RegionalStructureProducer<Void> { private static final Resolution RESOLUTION = Resolution.CHUNK; private static final int OFFSET_IN_WORLD = 8; private static final Dimension DIMENSION = Dimension.OVERWORLD; private static final boolean DISPLAY_DIMENSION = false; private static final long SALT = 10387313L; private static final byte SPACING = 32; private static final byte SEPARATION = 5; private static final boolean IS_TRIANGULAR = true; private static final int STRUCTURE_SIZE = 29; public OceanMonumentProducer_Original( long worldSeed, BiomeDataOracle biomeDataOracle, List<Biome> validBiomesAtMiddleOfChunk, List<Biome> validBiomesForStructure, boolean buggyStructureCoordinateMath) { super(RESOLUTION, OFFSET_IN_WORLD, new AllValidLocationChecker( new BiomeLocationChecker(biomeDataOracle, validBiomesAtMiddleOfChunk), new StructureBiomeLocationChecker(biomeDataOracle, STRUCTURE_SIZE, validBiomesForStructure) ), new ImmutableWorldIconTypeProvider(DefaultWorldIconTypes.OCEAN_MONUMENT), DIMENSION, DISPLAY_DIMENSION, worldSeed, SALT, SPACING, SEPARATION, IS_TRIANGULAR, buggyStructureCoordinateMath ); } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\PillagerOutpostProducer.java
package amidst.mojangapi.world.icon.producer; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.coordinates.Resolution; import amidst.mojangapi.world.icon.locationchecker.AllValidLocationChecker; import amidst.mojangapi.world.icon.locationchecker.LocationChecker; import amidst.mojangapi.world.icon.locationchecker.StructureBiomeLocationChecker; import amidst.mojangapi.world.icon.locationchecker.SuppressAroundLocationChecker; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.mojangapi.world.icon.type.ImmutableWorldIconTypeProvider; import amidst.mojangapi.world.oracle.BiomeDataOracle; import amidst.util.FastRand; @ThreadSafe public class PillagerOutpostProducer extends RegionalStructureProducer<Void> { private static final Resolution RESOLUTION = Resolution.CHUNK; private static final int OFFSET_IN_WORLD = 4; private static final Dimension DIMENSION = Dimension.OVERWORLD; private static final boolean DISPLAY_DIMENSION = false; private static final long SALT = 165745296L; private static final byte SPACING = 32; private static final byte SEPARATION = 8; private static final boolean IS_TRIANGULAR = false; private static final int STRUCTURE_SIZE = 0; public PillagerOutpostProducer( BiomeDataOracle biomeDataOracle, List<Biome> validBiomesForStructure, long worldSeed, RegionalStructureProducer<Void> villageProducer, int avoidVillageRadius, boolean checkVillageLocations, boolean buggyStructureCoordinateMath) { super(RESOLUTION, OFFSET_IN_WORLD, new AllValidLocationChecker( new PillagerOutpostAlgorithm(worldSeed), new StructureBiomeLocationChecker(biomeDataOracle, STRUCTURE_SIZE, validBiomesForStructure), new SuppressAroundLocationChecker(villageProducer, avoidVillageRadius, checkVillageLocations) ), new ImmutableWorldIconTypeProvider(DefaultWorldIconTypes.PILLAGER_OUTPOST), DIMENSION, DISPLAY_DIMENSION, worldSeed, SALT, SPACING, SEPARATION, IS_TRIANGULAR, buggyStructureCoordinateMath ); } private static class PillagerOutpostAlgorithm implements LocationChecker { private final long seed; public PillagerOutpostAlgorithm(long seed) { this.seed = seed; } @Override public boolean isValidLocation(int x, int y) { FastRand random = new FastRand((x >> 4) ^ ((y >> 4) << 4) ^ seed); random.advance(); return random.nextInt(5) == 0; } } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\PlayerProducer.java
package amidst.mojangapi.world.icon.producer; import java.util.LinkedList; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.icon.WorldIcon; import amidst.mojangapi.world.player.MovablePlayerList; import amidst.mojangapi.world.player.Player; import amidst.mojangapi.world.player.PlayerCoordinates; @ThreadSafe public class PlayerProducer extends CachedWorldIconProducer { private final MovablePlayerList movablePlayerList; public PlayerProducer(MovablePlayerList movablePlayerList) { this.movablePlayerList = movablePlayerList; } @Override protected List<WorldIcon> doCreateCache() { List<WorldIcon> result = new LinkedList<>(); for (Player player : movablePlayerList) { PlayerCoordinates coordinates = player.getPlayerCoordinates(); result.add( new WorldIcon( coordinates.getCoordinatesInWorld(), player.getPlayerName(), player.getHead(), coordinates.getDimension(), true)); } return result; } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\RegionalStructureProducer.java
package amidst.mojangapi.world.icon.producer; import java.util.function.Consumer; import amidst.documentation.ThreadSafe; import amidst.fragment.Fragment; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.coordinates.Resolution; import amidst.mojangapi.world.icon.WorldIcon; import amidst.mojangapi.world.icon.locationchecker.LocationChecker; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.mojangapi.world.icon.type.WorldIconTypeProvider; import amidst.util.FastRand; @ThreadSafe public class RegionalStructureProducer<T> extends WorldIconProducer<T> { private final Resolution resolution; private final int offsetInWorld; /** * This should ONLY be used for things where we have to check against * it every time. For example, we have to do this with biomes and * buried treasures. */ private final LocationChecker checker; private final WorldIconTypeProvider<T> provider; private final Dimension dimension; private final boolean displayDimension; // These have never changed and probably never will change, so we hard code them instead of giving them a version feature private static final long MAGIC_NUMBER_1 = 341873128712L; private static final long MAGIC_NUMBER_2 = 132897987541L; public final long worldSeed; public final long salt; public final byte spacing; // spacing in chunks public final int separation; // offset in chunks public final boolean isTriangular; public final boolean buggyStructureCoordinateMath; /** * Length of chunks needed to cover the maximum possible regions * intersecting a fragment. */ private final int intersectingRegionChunks; public RegionalStructureProducer( Resolution resolution, int offsetInWorld, LocationChecker checker, WorldIconTypeProvider<T> provider, Dimension dimension, boolean displayDimension, long worldSeed, long salt, byte spacing, byte separation, boolean isTriangular, boolean buggyStructureCoordinateMath) { this.resolution = resolution; this.offsetInWorld = offsetInWorld; this.checker = checker; this.provider = provider; this.dimension = dimension; this.displayDimension = displayDimension; this.worldSeed = worldSeed; this.salt = salt; this.spacing = spacing; this.separation = separation; this.isTriangular = isTriangular; this.buggyStructureCoordinateMath = buggyStructureCoordinateMath; this.intersectingRegionChunks = getIntersectingRegionChunks(); } @Override public void produce(CoordinatesInWorld corner, Consumer<WorldIcon> consumer, T additionalData) { if(checker != null && !checker.hasValidLocations()) { return; // No need to check if the LocationChecker will never accept anything } for (int xRelativeToFragment = 0; xRelativeToFragment <= intersectingRegionChunks; xRelativeToFragment += spacing) { for (int yRelativeToFragment = 0; yRelativeToFragment <= intersectingRegionChunks; yRelativeToFragment += spacing) { generateAt(corner, consumer, additionalData, xRelativeToFragment, yRelativeToFragment); } } } // TODO: use longs? private void generateAt( CoordinatesInWorld corner, Consumer<WorldIcon> consumer, T additionalData, int xRelativeToFragment, int yRelativeToFragment) { int x = xRelativeToFragment + (int) corner.getXAs(resolution); int y = yRelativeToFragment + (int) corner.getYAs(resolution); CoordinatesInWorld structLocation = getPossibleLocation(x, y); int structX = (int) structLocation.getX(); int structY = (int) structLocation.getY(); CoordinatesInWorld resultCoordinates = createCoordinates(structX, structY); // This is needed to avoid duplicate world icons. // Calling this before isValidLocation gives a huge speedup. if(resultCoordinates.isInBoundsOf(corner, Fragment.SIZE)) { // if there is no checker provided, skip it if (checker == null || checker.isValidLocation(structX, structY)) { DefaultWorldIconTypes worldIconType = provider.get(structX, structY, additionalData); if (worldIconType != null) { consumer.accept( new WorldIcon( resultCoordinates, worldIconType.getLabel(), worldIconType.getImage(), dimension, displayDimension)); } } } } private CoordinatesInWorld createCoordinates(int structX, int structY) { long xInWorld = resolution.convertFromThisToWorld(structX); long yInWorld = resolution.convertFromThisToWorld(structY); return new CoordinatesInWorld(xInWorld + offsetInWorld, yInWorld + offsetInWorld); } public CoordinatesInWorld getCheckedLocation(int chunkX, int chunkY) { CoordinatesInWorld possibleLocation = getPossibleLocation(chunkX, chunkY); // if there is no checker provided, skip it if (checker == null || checker.isValidLocation((int) possibleLocation.getX(), (int) possibleLocation.getY())) { return possibleLocation; } return null; } /** * This returns the equivalent of a StructureStart's position. */ public CoordinatesInWorld getPossibleLocation(int chunkX, int chunkY) { int value1 = getRegionCoord(chunkX); int value2 = getRegionCoord(chunkY); FastRand random = new FastRand(getRegionSeed(value1, value2)); value1 = getStructCoordInRegion(random, value1); value2 = getStructCoordInRegion(random, value2); return new CoordinatesInWorld(value1, value2); } public int getRegionCoord(int coordinate) { return getModifiedCoord(coordinate) / spacing; } private int getModifiedCoord(int coordinate) { if (coordinate < 0) { if (buggyStructureCoordinateMath) { // Bug MC-131462. return coordinate - spacing - 1; } else { return coordinate - spacing + 1; } } else { return coordinate; } } public long getRegionSeed(int value1, int value2) { // @formatter:off return value1 * MAGIC_NUMBER_1 + value2 * MAGIC_NUMBER_2 + worldSeed + salt; // @formatter:on } private int getStructCoordInRegion(FastRand random, int value) { int result = value * spacing; if (isTriangular) { result += (random.nextInt(spacing - separation) + random.nextInt(spacing - separation)) / 2; } else { result += random.nextInt(spacing - separation); } return result; } private int getIntersectingRegionChunks() { return (resolution.getStepsPerFragment() + spacing - 1) / spacing * spacing; } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\ScatteredFeaturesProducer.java
package amidst.mojangapi.world.icon.producer; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.coordinates.Resolution; import amidst.mojangapi.world.icon.locationchecker.BiomeLocationChecker; import amidst.mojangapi.world.icon.type.WorldIconTypeProvider; import amidst.mojangapi.world.oracle.BiomeDataOracle; @ThreadSafe public class ScatteredFeaturesProducer extends RegionalStructureProducer<Void> { private static final byte DEFAULT_SPACING = 32; private static final byte DEFAULT_SEPARATION = 8; private static final boolean IS_TRIANGULAR = false; public ScatteredFeaturesProducer( Resolution resolution, int offsetInWorld, BiomeDataOracle biomeDataOracle, List<Biome> validBiomesAtMiddleOfChunk, WorldIconTypeProvider<Void> provider, Dimension dimension, boolean displayDimension, long worldSeed, long salt, boolean buggyStructureCoordinateMath) { this(resolution, offsetInWorld, biomeDataOracle, validBiomesAtMiddleOfChunk, provider, dimension, displayDimension, worldSeed, salt, DEFAULT_SPACING, DEFAULT_SEPARATION, buggyStructureCoordinateMath ); } public ScatteredFeaturesProducer( Resolution resolution, int offsetInWorld, BiomeDataOracle biomeDataOracle, List<Biome> validBiomesAtMiddleOfChunk, WorldIconTypeProvider<Void> provider, Dimension dimension, boolean displayDimension, long worldSeed, long salt, byte spacing, byte separation, boolean buggyStructureCoordinateMath) { super(resolution, offsetInWorld, validBiomesAtMiddleOfChunk == null ? null : new BiomeLocationChecker(biomeDataOracle, validBiomesAtMiddleOfChunk), provider, dimension, displayDimension, worldSeed, salt, spacing, separation, IS_TRIANGULAR, buggyStructureCoordinateMath ); } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\SpawnProducer.java
package amidst.mojangapi.world.icon.producer; import java.util.Arrays; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.logging.AmidstLogger; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.icon.WorldIcon; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.mojangapi.world.oracle.WorldSpawnOracle; @ThreadSafe public class SpawnProducer extends CachedWorldIconProducer { private final WorldSpawnOracle oracle; public SpawnProducer(WorldSpawnOracle oracle) { this.oracle = oracle; } @Override protected List<WorldIcon> doCreateCache() { return Arrays.asList(createSpawnWorldIcon()); } private WorldIcon createSpawnWorldIcon() { CoordinatesInWorld spawnLocation = oracle.get(); if (spawnLocation != null) { return createWorldIcon(spawnLocation); } else { CoordinatesInWorld origin = CoordinatesInWorld.origin(); AmidstLogger.info("Unable to find spawn biome. Falling back to " + origin.toString() + "."); return createWorldIcon(origin); } } private WorldIcon createWorldIcon(CoordinatesInWorld coordinates) { return new WorldIcon( coordinates, DefaultWorldIconTypes.SPAWN.getLabel(), DefaultWorldIconTypes.SPAWN.getImage(), Dimension.OVERWORLD, false); } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\StrongholdProducer_128Algorithm.java
package amidst.mojangapi.world.icon.producer; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.oracle.BiomeDataOracle; import amidst.util.FastRand; /** * This is the fixed version of the 128 stronghold algorithm. It introduced in * 16w06a. * * see https://bugs.mojang.com/browse/MC-92289 */ @ThreadSafe public class StrongholdProducer_128Algorithm extends StrongholdProducer_Buggy128Algorithm { public StrongholdProducer_128Algorithm(long seed, BiomeDataOracle biomeDataOracle, List<Biome> validBiomes) { super(seed, biomeDataOracle, validBiomes); } @Override protected int getInitialValue_ring() { return 0; } @Override protected double getNextValue_startAngle(double currentValue, FastRand random) { // In this algorithm, the getInitialValue_startAngle() formula is used // at the start of each new ring. return currentValue + getInitialValue_startAngle(random); } @Override protected double getAngleDelta(int ring, int structuresPerRing) { return 6.283185307179586D / structuresPerRing; } @Override protected double getNextValue_distance(int currentRing, FastRand random) { return (4.0 * DISTANCE_IN_CHUNKS) + (6.0 * currentRing * DISTANCE_IN_CHUNKS) + (random.nextDouble() - 0.5) * (DISTANCE_IN_CHUNKS * 2.5); } @Override protected int getNextValue_structuresPerRing( int currentValue, int currentRing, int structuresRemaining, FastRand random) { int result = currentValue + 2 * currentValue / (currentRing + 1); result = Math.min(result, structuresRemaining); return result; } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\StrongholdProducer_Base.java
package amidst.mojangapi.world.icon.producer; import java.util.LinkedList; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.icon.WorldIcon; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.mojangapi.world.oracle.BiomeDataOracle; import amidst.util.FastRand; @ThreadSafe public abstract class StrongholdProducer_Base extends CachedWorldIconProducer { protected static final double DISTANCE_IN_CHUNKS = 32.0D; private static final int STRUCTURES_ON_FIRST_RING = 3; private final long seed; private final BiomeDataOracle biomeDataOracle; private final List<Biome> validBiomes; public StrongholdProducer_Base(long seed, BiomeDataOracle biomeDataOracle, List<Biome> validBiomes) { this.seed = seed; this.biomeDataOracle = biomeDataOracle; this.validBiomes = validBiomes; } @Override protected List<WorldIcon> doCreateCache() { List<WorldIcon> result = new LinkedList<>(); FastRand random = new FastRand(seed); int ring = getInitialValue_ring(); int structuresPerRing = STRUCTURES_ON_FIRST_RING; int currentRingStructureCount = 0; double angle = getInitialValue_startAngle(random); for (int i = 0; i < getTotalStructureCount(); i++) { double distance = getNextValue_distance(ring, random); int x = getX(angle, distance); int y = getY(angle, distance); CoordinatesInWorld strongholdLocation = getStrongholdLocation(x, y, findStronghold(random, x, y)); result.add(createWorldIcon(strongholdLocation)); angle += getAngleDelta(ring, structuresPerRing); currentRingStructureCount++; if (currentRingStructureCount == structuresPerRing) { // This ring of strongholds is completed, adjust values to // begin placing strongholds on the next ring. ring = getNextValue_ring(ring); currentRingStructureCount = getNextValue_currentRingStructureCount(currentRingStructureCount); structuresPerRing = getNextValue_structuresPerRing( structuresPerRing, ring, getTotalStructureCount() - i, random); angle = getNextValue_startAngle(angle, random); } } return result; } private int getX(double angle, double distance) { return (int) Math.round(Math.cos(angle) * distance); } private int getY(double angle, double distance) { return (int) Math.round(Math.sin(angle) * distance); } private CoordinatesInWorld findStronghold(FastRand random, int chunkX, int chunkY) { return biomeDataOracle.findValidLocationAtMiddleOfChunk(chunkX, chunkY, 112, validBiomes, random); } private CoordinatesInWorld getStrongholdLocation(int x, int y, CoordinatesInWorld coordinates) { if (coordinates != null) { return getCornerOfChunk(coordinates); } else { return CoordinatesInWorld.from(x << 4, y << 4); } } private CoordinatesInWorld getCornerOfChunk(CoordinatesInWorld coordinates) { long xInWorld = (coordinates.getX() >> 4) << 4; long yInWorld = (coordinates.getY() >> 4) << 4; return CoordinatesInWorld.from(xInWorld, yInWorld); } private WorldIcon createWorldIcon(CoordinatesInWorld coordinates) { return new WorldIcon( coordinates, DefaultWorldIconTypes.STRONGHOLD.getLabel(), DefaultWorldIconTypes.STRONGHOLD.getImage(), Dimension.OVERWORLD, false); } // This function depends on the Minecraft version, subclasses may override. protected int getTotalStructureCount() { return 3; } // This function depends on the Minecraft version, subclasses may override. protected int getInitialValue_ring() { return 1; } // This function depends on the Minecraft version, subclasses may override. protected int getNextValue_ring(int currentValue) { return currentValue + 1; } // This function depends on the Minecraft version, subclasses may override. protected double getInitialValue_startAngle(FastRand random) { return random.nextDouble() * 3.141592653589793D * 2.0D; } // This function depends on the Minecraft version, subclasses may override. protected double getNextValue_startAngle(double currentValue, FastRand random) { return currentValue; } // This function depends on the Minecraft version, subclasses may override. protected double getAngleDelta(int currentRing, int structuresPerRing) { return 6.283185307179586D * currentRing / structuresPerRing; } // This function depends on the Minecraft version, subclasses may override. protected double getNextValue_distance(int currentRing, FastRand random) { return (1.25D * currentRing + random.nextDouble()) * (DISTANCE_IN_CHUNKS * currentRing); } // This function depends on the Minecraft version, subclasses may override. protected int getNextValue_currentRingStructureCount(int currentValue) { // Versions with more than 3 structures set currentRingStructureCount // back to zero each time a ring is complete. return 0; } // This function depends on the Minecraft version, subclasses may override. protected int getNextValue_structuresPerRing( int currentValue, int currentRing, int structuresRemaining, FastRand random) { return currentValue + currentValue + random.nextInt(currentValue); } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\StrongholdProducer_Buggy128Algorithm.java
package amidst.mojangapi.world.icon.producer; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.oracle.BiomeDataOracle; /** * This is the buggy version of the 128 stronghold algorithm. It was introduced * in 15w43a and fixed in 16w06a. * * see https://bugs.mojang.com/browse/MC-92289 */ @ThreadSafe public class StrongholdProducer_Buggy128Algorithm extends StrongholdProducer_Base { public StrongholdProducer_Buggy128Algorithm(long seed, BiomeDataOracle biomeDataOracle, List<Biome> validBiomes) { super(seed, biomeDataOracle, validBiomes); } @Override protected int getTotalStructureCount() { return 128; } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\StrongholdProducer_Original.java
package amidst.mojangapi.world.icon.producer; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.oracle.BiomeDataOracle; @ThreadSafe public class StrongholdProducer_Original extends StrongholdProducer_Base { public StrongholdProducer_Original(long seed, BiomeDataOracle biomeDataOracle, List<Biome> validBiomes) { super(seed, biomeDataOracle, validBiomes); } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\VillageProducer.java
package amidst.mojangapi.world.icon.producer; import java.util.List; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.coordinates.Resolution; import amidst.mojangapi.world.icon.locationchecker.AllValidLocationChecker; import amidst.mojangapi.world.icon.locationchecker.LocationChecker; import amidst.mojangapi.world.icon.locationchecker.StructureBiomeLocationChecker; import amidst.mojangapi.world.icon.locationchecker.VillageAlgorithm; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.mojangapi.world.icon.type.ImmutableWorldIconTypeProvider; import amidst.mojangapi.world.oracle.BiomeDataOracle; @ThreadSafe public class VillageProducer extends RegionalStructureProducer<Void> { private static final Resolution RESOLUTION = Resolution.CHUNK; private static final int OFFSET_IN_WORLD = 4; private static final Dimension DIMENSION = Dimension.OVERWORLD; private static final boolean DISPLAY_DIMENSION = false; private static final long SALT = 10387312L; private static final byte SPACING = 32; private static final byte SEPARATION = 8; private static final boolean IS_TRIANGULAR = false; private static final int STRUCTURE_SIZE = 0; public VillageProducer( BiomeDataOracle biomeDataOracle, List<Biome> validBiomesForStructure, long worldSeed, boolean doComplexVillageCheck, boolean buggyStructureCoordinateMath) { super(RESOLUTION, OFFSET_IN_WORLD, getLocationCheckers(worldSeed, biomeDataOracle, validBiomesForStructure, doComplexVillageCheck), new ImmutableWorldIconTypeProvider(DefaultWorldIconTypes.VILLAGE), DIMENSION, DISPLAY_DIMENSION, worldSeed, SALT, SPACING, SEPARATION, IS_TRIANGULAR, buggyStructureCoordinateMath ); } private static LocationChecker getLocationCheckers( long seed, BiomeDataOracle biomeDataOracle, List<Biome> validBiomesForStructure, boolean doComplexVillageCheck) { LocationChecker biome = new StructureBiomeLocationChecker(biomeDataOracle, STRUCTURE_SIZE, validBiomesForStructure); if(doComplexVillageCheck) { return new AllValidLocationChecker(biome, new VillageAlgorithm(biomeDataOracle, validBiomesForStructure)); } else { return biome; } } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\WorldIconCollector.java
package amidst.mojangapi.world.icon.producer; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.function.Consumer; import amidst.documentation.NotThreadSafe; import amidst.mojangapi.world.icon.WorldIcon; @NotThreadSafe public class WorldIconCollector implements Consumer<WorldIcon> { private List<WorldIcon> worldIcons; @Override public void accept(WorldIcon worldIcon) { initListIfNecessary(); worldIcons.add(worldIcon); } private void initListIfNecessary() { if (worldIcons == null) { worldIcons = new LinkedList<>(); } } public List<WorldIcon> get() { if (worldIcons == null) { return Collections.emptyList(); } else { return worldIcons; } } }
amidst
src\main\java\amidst\mojangapi\world\icon\producer\WorldIconProducer.java
package amidst.mojangapi.world.icon.producer; import java.util.List; import java.util.function.Consumer; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.icon.WorldIcon; @ThreadSafe public abstract class WorldIconProducer<T> { public abstract void produce(CoordinatesInWorld corner, Consumer<WorldIcon> consumer, T additionalData); public List<WorldIcon> getAt(CoordinatesInWorld corner, T additionalData) { WorldIconCollector collector = new WorldIconCollector(); produce(corner, collector, additionalData); return collector.get(); } }
amidst
src\main\java\amidst\mojangapi\world\icon\type\DefaultWorldIconTypes.java
package amidst.mojangapi.world.icon.type; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import amidst.ResourceLoader; import amidst.documentation.Immutable; import amidst.mojangapi.world.icon.WorldIconImage; /** * This is only a helper enum to have a central place where these constants can * be collected. However, it should not be used as a type. */ @Immutable public enum DefaultWorldIconTypes { // @formatter:off NETHER_FORTRESS ("nether_fortress", "Nether Fortress"), BASTION_REMNANT ("bastion_remnant", "Bastion Remnant"), PLAYER ("player", "Player"), STRONGHOLD ("stronghold", "Stronghold"), JUNGLE ("jungle", "Jungle Temple"), DESERT ("desert", "Desert Temple"), VILLAGE ("village", "Village"), SPAWN ("spawn", "World Spawn"), WITCH ("witch", "Witch Hut"), OCEAN_MONUMENT ("ocean_monument", "Ocean Monument"), IGLOO ("igloo", "Igloo"), MINESHAFT ("mineshaft", "Mineshaft"), WOODLAND_MANSION ("woodland_mansion", "Woodland Mansion"), END_CITY ("end_city", "Likely End City"), POSSIBLE_END_CITY ("possible_end_city", "Possible End City"), OCEAN_RUINS ("ocean_ruins", "Ocean Ruins"), SHIPWRECK ("shipwreck", "Shipwreck"), BURIED_TREASURE ("buried_treasure", "Buried Treasure"), PILLAGER_OUTPOST ("pillager_outpost", "Pillager Outpost"); // @formatter:on private static final Map<String, DefaultWorldIconTypes> typeMap = createTypeMap(); private static Map<String, DefaultWorldIconTypes> createTypeMap() { Map<String, DefaultWorldIconTypes> result = new HashMap<>(); for (DefaultWorldIconTypes iconType : EnumSet.allOf(DefaultWorldIconTypes.class)) { result.put(iconType.getName(), iconType); } return Collections.unmodifiableMap(result); } public static DefaultWorldIconTypes getByName(String name) { return typeMap.get(name); } public static boolean exists(String name) { return typeMap.containsKey(name); } private static String getFilename(String name) { return "/amidst/gui/main/icon/" + name + ".png"; } private final String name; private final String label; private final WorldIconImage image; private DefaultWorldIconTypes(String name, String label) { this.name = name; this.label = label; this.image = WorldIconImage.fromPixelTransparency(ResourceLoader.getImage(getFilename(name))); } public String getName() { return name; } public String getLabel() { return label; } public WorldIconImage getImage() { return image; } }
amidst
src\main\java\amidst\mojangapi\world\icon\type\EndCityWorldIconTypeProvider.java
package amidst.mojangapi.world.icon.type; import java.util.List; import amidst.mojangapi.world.oracle.EndIsland; public class EndCityWorldIconTypeProvider implements WorldIconTypeProvider<List<EndIsland>> { /** * REQUIRED_INFLUENCE is a value between 0 and 80 that I'm finding by trial * and error. If the island influence is 0 or higher then an End City can * spawn, but they don't spawn unless all of the ground under then is at a * higher y value than 60. Since we don't want to generate the land to * discover the high areas, I'm using the island influence as proxy for how * high the land might be. */ private static final int REQUIRED_INFLUENCE = 60; @Override public DefaultWorldIconTypes get(int chunkX, int chunkY, List<EndIsland> endIslands) { // Convert coordinates to long to guard against overflow if (((long) chunkX * (long) chunkX + (long) chunkY * (long) chunkY) > 4096) { return hasSuitableIslandFoundation(chunkX, chunkY, endIslands); } else { return null; } } /** * If the influence is greater or equal to zero, Minecraft WILL attempt to * build an End City, however if the ground at any of the corners of the end * city is below height 60 then the End City will be aborted. * * TODO: Use Amidst's ability to hook into the minecraft .jar file to get * Minecraft to build just this single chunk so we can tell for certain * whether an End City builds here. (If that's feasible) * * In the meantime, fall back on the requiredInfluence heuristic */ private DefaultWorldIconTypes hasSuitableIslandFoundation(int chunkX, int chunkY, List<EndIsland> endIslands) { DefaultWorldIconTypes result = null; for (EndIsland island : endIslands) { float influence = island.influenceAtChunk(chunkX, chunkY); if (influence >= REQUIRED_INFLUENCE) { return DefaultWorldIconTypes.END_CITY; } else if (influence >= 0) { result = DefaultWorldIconTypes.POSSIBLE_END_CITY; } } return result; } }
amidst
src\main\java\amidst\mojangapi\world\icon\type\ImmutableWorldIconTypeProvider.java
package amidst.mojangapi.world.icon.type; import amidst.documentation.Immutable; @Immutable public class ImmutableWorldIconTypeProvider implements WorldIconTypeProvider<Void> { private final DefaultWorldIconTypes worldIconType; public ImmutableWorldIconTypeProvider(DefaultWorldIconTypes worldIconType) { this.worldIconType = worldIconType; } @Override public DefaultWorldIconTypes get(int x, int y, Void additionalData) { return worldIconType; } }
amidst
src\main\java\amidst\mojangapi\world\icon\type\WorldIconTypeProvider.java
package amidst.mojangapi.world.icon.type; import amidst.documentation.ThreadSafe; @ThreadSafe public interface WorldIconTypeProvider<T> { DefaultWorldIconTypes get(int x, int y, T additionalData); }
amidst
src\main\java\amidst\parsing\json\JsonReader.java
package amidst.parsing.json; import java.io.IOException; import java.io.Reader; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import com.google.gson.Gson; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; import amidst.documentation.Immutable; import amidst.documentation.NotNull; import amidst.parsing.FormatException; import amidst.parsing.URIUtils; @Immutable public enum JsonReader { ; private static final Gson GSON = new Gson(); @NotNull public static <T> T readLocation(Path file, Class<T> class1) throws FormatException, IOException { return read(Files.newBufferedReader(file), class1); } @NotNull public static <T> T readLocation(URL location, Class<T> clazz) throws FormatException, IOException { return read(URIUtils.newReader(location), clazz); } @NotNull public static <T> T readLocation(String location, Class<T> clazz) throws FormatException, IOException { return read(URIUtils.newReader(location), clazz); } @NotNull public static <T> T read(Reader reader, Class<T> clazz) throws FormatException, IOException { try (Reader theReader = reader) { T result = GSON.fromJson(theReader, clazz); if (result != null) { return result; } else { throw new FormatException("result was null"); } } catch (JsonSyntaxException e) { throw new FormatException(e); } catch (JsonIOException e) { throw new IOException(e); } } @NotNull public static <T> T readString(String string, Class<T> clazz) throws FormatException { try { T result = GSON.fromJson(string, clazz); if (result != null) { return result; } else { throw new FormatException("result was null"); } } catch (JsonSyntaxException e) { throw new FormatException(e); } } }
amidst
src\main\java\amidst\settings\biomeprofile\BiomeColorJson.java
package amidst.settings.biomeprofile; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; import amidst.mojangapi.world.biome.BiomeColor; @Immutable public class BiomeColorJson { private int r; private int g; private int b; @GsonConstructor public BiomeColorJson() { } public BiomeColorJson(int r, int g, int b) { this.r = r; this.g = g; this.b = b; } public int getR() { return r; } public int getG() { return g; } public int getB() { return b; } public BiomeColor createBiomeColor() { return BiomeColor.from(r, g, b); } }
amidst
src\main\java\amidst\settings\biomeprofile\BiomeProfile.java
package amidst.settings.biomeprofile; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; import amidst.logging.AmidstLogger; import amidst.mojangapi.world.biome.BiomeColor; import amidst.parsing.FormatException; import amidst.parsing.json.JsonReader; @Immutable public class BiomeProfile implements Serializable { private static final long serialVersionUID = 656038328314515511L; private static BiomeProfile createDefaultProfile() { final String profileFile = "/amidst/mojangapi/default_biome_profile.json"; try (InputStream stream = BiomeProfile.class.getResourceAsStream(profileFile)) { // For some reason this is the only way we can read the file from inside and outside the jar try (Scanner scanner = new Scanner(stream)) { StringBuffer buffer = new StringBuffer(); while(scanner.hasNext()){ buffer.append(scanner.nextLine()); } return JsonReader.readString(buffer.toString(), BiomeProfile.class); } } catch (IOException | FormatException e) { throw new RuntimeException("Unable to create default biome profile", e); } } public static BiomeProfile getDefaultProfile() { return DEFAULT_PROFILE; } public static BiomeProfile createExampleProfile() { return new BiomeProfile("example", "control E", DEFAULT_PROFILE.colorMap); } private static final BiomeProfile DEFAULT_PROFILE = createDefaultProfile(); private volatile String name; private volatile String shortcut; private volatile Map<Integer, BiomeColorJson> colorMap; @GsonConstructor public BiomeProfile() { } BiomeProfile(String name, String shortcut, Map<Integer, BiomeColorJson> colorMap) { this.name = name; this.shortcut = shortcut; this.colorMap = colorMap; } public String getName() { return name == null ? "<unnamed>" : name; } public String getShortcut() { return shortcut; } public boolean validate() { if(this.colorMap == null) { AmidstLogger.info("Color map is missing in profile: {}", name); return false; } if(this.name == null) { AmidstLogger.info("Name is missing in profile"); return false; } return true; } public ConcurrentHashMap<Integer, BiomeColor> createBiomeColorMap() { ConcurrentHashMap<Integer, BiomeColor> result = new ConcurrentHashMap<Integer, BiomeColor>(); colorMap.forEach((k,v) -> result.put(k, v.createBiomeColor())); return result; } public boolean save(Path file) { return writeToFile(file, serialize()); } public String serialize() { String output = "{ \"name\":\"" + name + "\", "; output += shortcut != null ? "\"shortcut\":\"" + shortcut + "\", " : ""; output += "\"colorMap\":[\r\n" + serializeColorMap(); return output + " ] }\r\n"; } /** * This method uses the sorted color map, so the serialization will have a * reproducible order. */ private String serializeColorMap() { String output = ""; for (Map.Entry<Integer, BiomeColorJson> pairs : getSortedColorMapEntries()) { output += "[ " + pairs.getKey() + ", { "; output += "\"r\":" + pairs.getValue().getR() + ", "; output += "\"g\":" + pairs.getValue().getG() + ", "; output += "\"b\":" + pairs.getValue().getB() + " } ],\r\n"; } return output.substring(0, output.length() - 3); } private Set<Entry<Integer, BiomeColorJson>> getSortedColorMapEntries() { if(colorMap == null) { return Collections.emptySet(); } SortedMap<Integer, BiomeColorJson> result = new TreeMap<>(Integer::compare); result.putAll(colorMap); return result.entrySet(); } private boolean writeToFile(Path file, String output) { try (BufferedWriter writer = Files.newBufferedWriter(file)) { writer.write(output); return true; } catch (IOException e) { return false; } } }
amidst
src\main\java\amidst\settings\biomeprofile\BiomeProfileDirectory.java
package amidst.settings.biomeprofile; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import amidst.documentation.Immutable; import amidst.logging.AmidstLogger; import amidst.parsing.FormatException; import amidst.parsing.json.JsonReader; @Immutable public class BiomeProfileDirectory { public static BiomeProfileDirectory create(Path biomeProfilesDirectory) { if (biomeProfilesDirectory == null) { biomeProfilesDirectory = DEFAULT_ROOT_DIRECTORY; } BiomeProfileDirectory result = new BiomeProfileDirectory(biomeProfilesDirectory); AmidstLogger.info("using biome profiles at: '" + result.getRoot() + "'"); return result; } private static final Path DEFAULT_ROOT_DIRECTORY = Paths.get("biome"); private final Path root; public BiomeProfileDirectory(Path root) { this.root = root; } public Path getRoot() { return root; } public boolean isValid() { return Files.isDirectory(root); } public boolean visitProfiles(BiomeProfileVisitor visitor) { return visitProfiles(root, visitor); } private boolean visitProfiles(Path directory, BiomeProfileVisitor visitor) { boolean[] entered = new boolean[]{ false }; try { Files.list(directory).forEachOrdered(file -> { if (Files.isRegularFile(file)) { BiomeProfile profile = createFromFile(file); if (profile != null) { if (!entered[0]) { entered[0] = true; visitor.enterDirectory(directory.getFileName().toString()); } visitor.visitProfile(profile); } } else { visitProfiles(file, visitor); } }); } catch (IOException e) { AmidstLogger.error(e, "Unexpected IO error while visiting biomes profiles."); } if (entered[0]) { visitor.leaveDirectory(); } return entered[0]; } private BiomeProfile createFromFile(Path file) { try { BiomeProfile profile = JsonReader.readLocation(file, BiomeProfile.class); if(profile.validate()) { return profile; } AmidstLogger.warn("Profile invalid, ignoring: {}", file); } catch (IOException | FormatException e) { try { BiomeProfile newProfile = JsonReader.readLocation(file, BiomeProfileOld.class).convertToNewFormat(); if(newProfile.validate()) { newProfile.save(file); AmidstLogger.info("Profile converted to new format: {}", file); return newProfile; } AmidstLogger.warn("Profile invalid, ignoring: {}", file); } catch (Exception e1) { AmidstLogger.warn(e, "Unable to load file: {}", file); } } return null; } }
amidst
src\main\java\amidst\settings\biomeprofile\BiomeProfileOld.java
package amidst.settings.biomeprofile; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.SortedMap; import java.util.TreeMap; import java.util.Map.Entry; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable class BiomeProfileOld { private volatile String name; private volatile String shortcut; private volatile Map<String, BiomeColorJson> colorMap; @GsonConstructor BiomeProfileOld() { } public BiomeProfile convertToNewFormat() { final String conversionFile = "/amidst/mojangapi/conversion_map.txt"; Map<String, Integer> conversionMap = new HashMap<String, Integer>(); try (InputStream stream = BiomeProfile.class.getResourceAsStream(conversionFile)) { try (Scanner scanner = new Scanner(stream)) { while(scanner.hasNextLine()) { String[] parts = scanner.nextLine().split(","); if (parts.length != 2) { throw new RuntimeException("Invalid biome profile conversion file"); } else { try { conversionMap.put(parts[0], Integer.parseInt(parts[1])); } catch (NumberFormatException e) { throw new RuntimeException("Invalid biome profile conversion file", e); } } } } } catch (IOException e) { throw new RuntimeException("Unable to get biome profile conversion file", e); } SortedMap<Integer, BiomeColorJson> newMap = new TreeMap<Integer, BiomeColorJson>(Integer::compare); for(Entry<String, BiomeColorJson> entry : colorMap.entrySet()) { Integer id = conversionMap.get(entry.getKey()); if(id == null) { throw new RuntimeException("Unable to convert biome profile: Biome " + entry.getKey() + " not found"); } newMap.put(id, entry.getValue()); } return new BiomeProfile(name, shortcut, newMap); } }
amidst
src\main\java\amidst\settings\biomeprofile\BiomeProfileSelection.java
package amidst.settings.biomeprofile; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import amidst.documentation.ThreadSafe; import amidst.logging.AmidstLogger; import amidst.logging.AmidstMessageBox; import amidst.mojangapi.world.biome.BiomeColor; import amidst.mojangapi.world.biome.UnknownBiomeIdException; @ThreadSafe public class BiomeProfileSelection { private ConcurrentHashMap<Integer, BiomeColor> biomeColors; private Set<Integer> unknownBiomes; public BiomeProfileSelection(BiomeProfile biomeProfile) { set(biomeProfile); } public BiomeColor getBiomeColorOrUnknown(int index) { try { return getBiomeColor(index); } catch (UnknownBiomeIdException e) { // Only show an error if this is the first time we encounter this biome if (unknownBiomes.add(index)) { AmidstLogger.error(e); AmidstMessageBox.displayError("Error", e); } return BiomeColor.unknown(); } } public BiomeColor getBiomeColor(int index) throws UnknownBiomeIdException { BiomeColor color = biomeColors.get(index); if(color != null) { return color; } else { throw new UnknownBiomeIdException("unsupported biome index detected: " + index); } } public void set(BiomeProfile biomeProfile) { this.biomeColors = biomeProfile.createBiomeColorMap(); this.unknownBiomes = ConcurrentHashMap.newKeySet(); AmidstLogger.info("Biome profile activated: " + biomeProfile.getName()); } }
amidst
src\main\java\amidst\settings\biomeprofile\BiomeProfileVisitor.java
package amidst.settings.biomeprofile; public interface BiomeProfileVisitor { void enterDirectory(String name); void visitProfile(BiomeProfile profile); void leaveDirectory(); }
amidst
src\main\java\amidst\threading\worker\ExceptionalWorker.java
package amidst.threading.worker; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; @FunctionalInterface public interface ExceptionalWorker { @CalledOnlyBy(AmidstThread.WORKER) void run() throws Exception; }
amidst
src\main\java\amidst\threading\worker\ExceptionalWorkerWithResult.java
package amidst.threading.worker; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; @FunctionalInterface public interface ExceptionalWorkerWithResult<R> { @CalledOnlyBy(AmidstThread.WORKER) R run() throws Exception; }
amidst
src\main\java\amidst\threading\worker\ProgressReporter.java
package amidst.threading.worker; public interface ProgressReporter<P> { void report(P data); }
amidst
src\main\java\amidst\threading\worker\ProgressReportingExceptionalWorker.java
package amidst.threading.worker; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; @FunctionalInterface public interface ProgressReportingExceptionalWorker<P> { @CalledOnlyBy(AmidstThread.WORKER) void run(ProgressReporter<P> progressReporter) throws Exception; }
amidst
src\main\java\amidst\threading\worker\ProgressReportingExceptionalWorkerWithResult.java
package amidst.threading.worker; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; @FunctionalInterface public interface ProgressReportingExceptionalWorkerWithResult<R, P> { @CalledOnlyBy(AmidstThread.WORKER) R run(ProgressReporter<P> progressReporter) throws Exception; }
amidst
src\main\java\amidst\threading\worker\ProgressReportingWorker.java
package amidst.threading.worker; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; @FunctionalInterface public interface ProgressReportingWorker<P> { @CalledOnlyBy(AmidstThread.WORKER) void run(ProgressReporter<P> progressReporter); }
amidst
src\main\java\amidst\threading\worker\ProgressReportingWorkerWithResult.java
package amidst.threading.worker; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; @FunctionalInterface public interface ProgressReportingWorkerWithResult<R, P> { @CalledOnlyBy(AmidstThread.WORKER) R run(ProgressReporter<P> progressReporter); }
amidst
src\main\java\amidst\threading\worker\Worker.java
package amidst.threading.worker; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; @FunctionalInterface public interface Worker { @CalledOnlyBy(AmidstThread.WORKER) void run(); }