diff --git a/build.gradle b/build.gradle index 1da9bd3..37c9c75 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,15 @@ +apply plugin: 'java' +apply plugin: 'maven' +apply plugin: 'shadow' + +version = "1.2.2" +group= "mcp.mobius.opis" // http://maven.apache.org/guides/mini/guide-naming-conventions.html +archivesBaseName = "Opis" + buildscript { repositories { mavenCentral() + //jcenter() maven { name = "forge" url = "http://files.minecraftforge.net/maven" @@ -9,42 +18,107 @@ buildscript { name = "sonatype" url = "https://oss.sonatype.org/content/repositories/snapshots/" } + maven { + name = "shadow-repo" + url = 'http://dl.bintray.com/content/johnrengelman/gradle-plugins/' + } } dependencies { classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' + classpath 'com.github.jengelman.gradle.plugins:shadow:0.8' } } +apply plugin: 'forge' + +minecraft { + version = "1.7.2-10.12.1.1101" + assetDir = "eclipse/assets" +} + +shadow { + + //relocation { + // pattern = 'org.apache.commons.lang3' + // shadedPattern = 'opisapache.lang3' + //} + + relocation { + pattern = 'org.apache.commons.math3' + shadedPattern = 'opisapache.math3' + } + + artifactSet { + include 'org.apache.commons' + exclude 'org.apache.commons.lang3' + include 'org.jfree' + include 'com.miglayout' + include 'net.sf.opencsv' + } +} + +tasks.shadowJar.dependsOn "reobf" + configurations { deployerJars - packed - compile.extendsFrom packed } repositories { + mavenLocal() mavenCentral() + maven { + name "Mobius Repo" + url "http://mobiusstrip.eu/maven" + } } -apply plugin: 'java' -apply plugin: 'forge' -apply plugin: 'maven' - -version = "1.0" -group= "com.yourname.modid" // http://maven.apache.org/guides/mini/guide-naming-conventions.html -archivesBaseName = "modid" - dependencies { - packed 'org.apache.commons:commons-math3:3.2' - packed 'org.jfree:jcommon:1.0.21' - packed 'org.jfree:jfreechart:1.0.17' - packed 'com.miglayout:miglayout-swing:4.2' - packed 'net.sf.opencsv:opencsv:2.3' + compile 'org.apache.commons:commons-math3:3.2' + compile 'org.jfree:jcommon:1.0.21' + compile 'org.jfree:jfreechart:1.0.17' + compile 'com.miglayout:miglayout-swing:4.2' + compile 'net.sf.opencsv:opencsv:2.3' + compile "mcp.mobius.mobiuscore:MobiusCore:1.2.1:dev" deployerJars "org.apache.maven.wagon:wagon-ssh:2.2" } -minecraft { - version = "1.7.2-10.12.1.1065" - assetDir = "eclipse/assets" +def root = project.projectDir.parentFile +sourceSets { + main { + java { + srcDir new File(root, "src") + } + resources { + srcDir new File(root, "resources") + } + } +} + +task sourceJar(type: Jar) { + from sourceSets.main.java + from new File(root, "dev") + classifier = 'sources' +} + +task devJar(type: Jar) { + from sourceSets.main.output + classifier = 'dev' +} + +// some crazy stuff to make sure the chicken stuff is in the mods folder... +// because it wont work otherwise... because FML doesnt laod coremods from the classpath +task copyCoreMods(type: Copy, dependsOn: "extractUserDev") { + from configurations.compile + include "**/*Mobius*.jar" + //include "**/*Chicken*.jar", "**/*NotEnoughItems*.jar" + //exclude "**/CodeChickenLib*" // because CCC downloads it anyways.. -_- + into file(minecraft.assetDir + "/../mods") // paralell to the assets dir +} +tasks.setupDevWorkspace.dependsOn copyCoreMods +tasks.setupDecompWorkspace.dependsOn copyCoreMods + +artifacts { + archives sourceJar, devJar } processResources @@ -66,17 +140,3 @@ processResources exclude 'mcmod.info' } } - -jar -{ - // packs a bunch of stuff into my jar. - // everything marked as packed - from { - configurations.packed.collect { - it.isDirectory() ? it : zipTree(it).matching { - exclude "META-INF", "META-INF/**", "*META-INF*", "meta-inf" - exclude "**.jar", "**/*.jar", "*.jar" - } - } - } -} \ No newline at end of file diff --git a/src/main/java/cpw/mods/fml/common/FMLCommonHandler.java b/src/main/java/cpw/mods/fml/common/FMLCommonHandler.java deleted file mode 100644 index 909a93e..0000000 --- a/src/main/java/cpw/mods/fml/common/FMLCommonHandler.java +++ /dev/null @@ -1,606 +0,0 @@ -/* - * Forge Mod Loader - * Copyright (c) 2012-2013 cpw. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v2.1 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html - * - * Contributors: - * cpw - implementation - */ - -package cpw.mods.fml.common; - -import java.io.File; -import java.lang.ref.WeakReference; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import net.minecraft.crash.CrashReport; -import net.minecraft.crash.CrashReportCategory; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.INetHandler; -import net.minecraft.network.NetworkManager; -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.World; -import net.minecraft.world.storage.SaveHandler; -import net.minecraft.world.storage.WorldInfo; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.Logger; - -import com.google.common.base.Joiner; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableList.Builder; -import com.google.common.collect.Lists; -import com.google.common.collect.MapMaker; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; - -import cpw.mods.fml.common.eventhandler.EventBus; -import cpw.mods.fml.common.gameevent.InputEvent; -import cpw.mods.fml.common.gameevent.PlayerEvent; -import cpw.mods.fml.common.gameevent.TickEvent; -import cpw.mods.fml.common.gameevent.TickEvent.Phase; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.server.FMLServerHandler; - - -/** - * The main class for non-obfuscated hook handling code - * - * Anything that doesn't require obfuscated or client/server specific code should - * go in this handler - * - * It also contains a reference to the sided handler instance that is valid - * allowing for common code to access specific properties from the obfuscated world - * without a direct dependency - * - * @author cpw - * - */ -public class FMLCommonHandler -{ - /** - * The singleton - */ - private static final FMLCommonHandler INSTANCE = new FMLCommonHandler(); - /** - * The delegate for side specific data and functions - */ - private IFMLSidedHandler sidedDelegate; - - private Class forge; - private boolean noForge; - private List brandings; - private List brandingsNoMC; - private List crashCallables = Lists.newArrayList(Loader.instance().getCallableCrashInformation()); - private Set handlerSet = Sets.newSetFromMap(new MapMaker().weakKeys().makeMap()); - private WeakReference handlerToCheck; - private EventBus eventBus = new EventBus(); - private volatile CountDownLatch exitLatch = null; - /** - * The FML event bus. Subscribe here for FML related events - * - * @return the event bus - */ - public EventBus bus() - { - return eventBus; - } - - public void beginLoading(IFMLSidedHandler handler) - { - sidedDelegate = handler; - FMLLog.log("MinecraftForge", Level.INFO, "Attempting early MinecraftForge initialization"); - callForgeMethod("initialize"); - callForgeMethod("registerCrashCallable"); - FMLLog.log("MinecraftForge", Level.INFO, "Completed early MinecraftForge initialization"); - } - - /** - * @return the instance - */ - public static FMLCommonHandler instance() - { - return INSTANCE; - } - /** - * Find the container that associates with the supplied mod object - * @param mod - */ - public ModContainer findContainerFor(Object mod) - { - if (mod instanceof String) - { - return Loader.instance().getIndexedModList().get(mod); - } - else - { - return Loader.instance().getReversedModObjectList().get(mod); - } - } - /** - * Get the forge mod loader logging instance (goes to the forgemodloader log file) - * @return The log instance for the FML log file - */ - public Logger getFMLLogger() - { - return FMLLog.getLogger(); - } - - public Side getSide() - { - return sidedDelegate.getSide(); - } - - /** - * Return the effective side for the context in the game. This is dependent - * on thread analysis to try and determine whether the code is running in the - * server or not. Use at your own risk - */ - public Side getEffectiveSide() - { - Thread thr = Thread.currentThread(); - if ((thr.getName().equals("Server thread"))) - { - return Side.SERVER; - } - - return Side.CLIENT; - } - /** - * Raise an exception - */ - public void raiseException(Throwable exception, String message, boolean stopGame) - { - FMLLog.log(Level.ERROR, exception, "Something raised an exception. The message was '%s'. 'stopGame' is %b", message, stopGame); - if (stopGame) - { - getSidedDelegate().haltGame(message,exception); - } - } - - - private Class findMinecraftForge() - { - if (forge==null && !noForge) - { - try { - forge = Class.forName("net.minecraftforge.common.MinecraftForge"); - } catch (Exception ex) { - noForge = true; - } - } - return forge; - } - - private Object callForgeMethod(String method) - { - if (noForge) - return null; - try - { - return findMinecraftForge().getMethod(method).invoke(null); - } - catch (Exception e) - { - // No Forge installation - return null; - } - } - - public void computeBranding() - { - if (brandings == null) - { - Builder brd = ImmutableList.builder(); - brd.add(Loader.instance().getMCVersionString()); - brd.add(Loader.instance().getMCPVersionString()); - brd.add("FML v"+Loader.instance().getFMLVersionString()); - String forgeBranding = (String) callForgeMethod("getBrandingVersion"); - if (!Strings.isNullOrEmpty(forgeBranding)) - { - brd.add(forgeBranding); - } - if (sidedDelegate!=null) - { - brd.addAll(sidedDelegate.getAdditionalBrandingInformation()); - } - if (Loader.instance().getFMLBrandingProperties().containsKey("fmlbranding")) - { - brd.add(Loader.instance().getFMLBrandingProperties().get("fmlbranding")); - } - int tModCount = Loader.instance().getModList().size(); - int aModCount = Loader.instance().getActiveModList().size(); - brd.add(String.format("%d mod%s loaded, %d mod%s active", tModCount, tModCount!=1 ? "s" :"", aModCount, aModCount!=1 ? "s" :"" )); - brandings = brd.build(); - brandingsNoMC = brandings.subList(1, brandings.size()); - } - } - public List getBrandings(boolean includeMC) - { - if (brandings == null) - { - computeBranding(); - } - return includeMC ? ImmutableList.copyOf(brandings) : ImmutableList.copyOf(brandingsNoMC); - } - - public IFMLSidedHandler getSidedDelegate() - { - return sidedDelegate; - } - - public void onPostServerTick() - { - bus().post(new TickEvent.ServerTickEvent(Phase.END)); - ProfilerSection.TICK.stop(); - } - - /** - * Every tick just after world and other ticks occur - */ - public void onPostWorldTick(World world) - { - bus().post(new TickEvent.WorldTickEvent(Side.SERVER, Phase.END, world)); - ProfilerSection.DIMENSION_TICK.stop(world); - } - - public void onPreServerTick() - { - ProfilerSection.TICK.start(); - bus().post(new TickEvent.ServerTickEvent(Phase.START)); - } - - /** - * Every tick just before world and other ticks occur - */ - public void onPreWorldTick(World world) - { - ProfilerSection.DIMENSION_TICK.start(world); - bus().post(new TickEvent.WorldTickEvent(Side.SERVER, Phase.START, world)); - } - - public boolean handleServerAboutToStart(MinecraftServer server) - { - return Loader.instance().serverAboutToStart(server); - } - - public boolean handleServerStarting(MinecraftServer server) - { - return Loader.instance().serverStarting(server); - } - - public void handleServerStarted() - { - Loader.instance().serverStarted(); - } - - public void handleServerStopping() - { - Loader.instance().serverStopping(); - } - - public File getSavesDirectory() { - return sidedDelegate.getSavesDirectory(); - } - - public MinecraftServer getMinecraftServerInstance() - { - return sidedDelegate.getServer(); - } - - public void showGuiScreen(Object clientGuiElement) - { - sidedDelegate.showGuiScreen(clientGuiElement); - } - - public void queryUser(StartupQuery query) throws InterruptedException - { - sidedDelegate.queryUser(query); - } - - public void onServerStart(MinecraftServer dedicatedServer) - { - FMLServerHandler.instance(); - sidedDelegate.beginServerLoading(dedicatedServer); - } - - public void onServerStarted() - { - sidedDelegate.finishServerLoading(); - } - - - public void onPreClientTick() - { - bus().post(new TickEvent.ClientTickEvent(Phase.START)); - } - - public void onPostClientTick() - { - bus().post(new TickEvent.ClientTickEvent(Phase.END)); - } - - public void onRenderTickStart(float timer) - { - bus().post(new TickEvent.RenderTickEvent(Phase.START, timer)); - } - - public void onRenderTickEnd(float timer) - { - bus().post(new TickEvent.RenderTickEvent(Phase.END, timer)); - } - - public void onPlayerPreTick(EntityPlayer player) - { - bus().post(new TickEvent.PlayerTickEvent(Phase.START, player)); - } - - public void onPlayerPostTick(EntityPlayer player) - { - bus().post(new TickEvent.PlayerTickEvent(Phase.END, player)); - } - - public void registerCrashCallable(ICrashCallable callable) - { - crashCallables.add(callable); - } - - public void enhanceCrashReport(CrashReport crashReport, CrashReportCategory category) - { - for (ICrashCallable call: crashCallables) - { - category.addCrashSectionCallable(call.getLabel(), call); - } - } - - public void handleWorldDataSave(SaveHandler handler, WorldInfo worldInfo, NBTTagCompound tagCompound) - { - for (ModContainer mc : Loader.instance().getModList()) - { - if (mc instanceof InjectedModContainer) - { - WorldAccessContainer wac = ((InjectedModContainer)mc).getWrappedWorldAccessContainer(); - if (wac != null) - { - NBTTagCompound dataForWriting = wac.getDataForWriting(handler, worldInfo); - tagCompound.setTag(mc.getModId(), dataForWriting); - } - } - } - } - - public void handleWorldDataLoad(SaveHandler handler, WorldInfo worldInfo, NBTTagCompound tagCompound) - { - if (getEffectiveSide()!=Side.SERVER) - { - return; - } - if (handlerSet.contains(handler)) - { - return; - } - handlerSet.add(handler); - handlerToCheck = new WeakReference(handler); // for confirmBackupLevelDatUse - Map additionalProperties = Maps.newHashMap(); - worldInfo.setAdditionalProperties(additionalProperties); - for (ModContainer mc : Loader.instance().getModList()) - { - if (mc instanceof InjectedModContainer) - { - WorldAccessContainer wac = ((InjectedModContainer)mc).getWrappedWorldAccessContainer(); - if (wac != null) - { - wac.readData(handler, worldInfo, additionalProperties, tagCompound.getCompoundTag(mc.getModId())); - } - } - } - } - - public void confirmBackupLevelDatUse(SaveHandler handler) - { - if (handlerToCheck == null || handlerToCheck.get() != handler) { - // only run if the save has been initially loaded - handlerToCheck = null; - return; - } - - String text = "Forge Mod Loader detected that the backup level.dat is being used.\n\n" + - "This may happen due to a bug or corruption, continuing can damage\n" + - "your world beyond repair or lose data / progress.\n\n" + - "It's recommended to create a world backup before continuing."; - - boolean confirmed = StartupQuery.confirm(text); - if (!confirmed) StartupQuery.abort(); - } - - public boolean shouldServerBeKilledQuietly() - { - if (sidedDelegate == null) - { - return false; - } - return sidedDelegate.shouldServerShouldBeKilledQuietly(); - } - - /** - * Make handleExit() wait for handleServerStopped(). - * - * For internal use only! - */ - public void expectServerStopped() - { - exitLatch = new CountDownLatch(1); - } - - /** - * Delayed System.exit() until the server is actually stopped/done saving. - * - * For internal use only! - * - * @param retVal Exit code for System.exit() - */ - public void handleExit(int retVal) - { - CountDownLatch latch = exitLatch; - - if (latch != null) - { - try - { - FMLLog.info("Waiting for the server to terminate/save."); - if (!latch.await(10, TimeUnit.SECONDS)) - { - FMLLog.warning("The server didn't stop within 10 seconds, exiting anyway."); - } - else - { - FMLLog.info("Server terminated."); - } - } - catch (InterruptedException e) - { - FMLLog.warning("Interrupted wait, exiting."); - } - } - - System.exit(retVal); - } - - public void handleServerStopped() - { - sidedDelegate.serverStopped(); - MinecraftServer server = getMinecraftServerInstance(); - Loader.instance().serverStopped(); - // FORCE the internal server to stop: hello optifine workaround! - if (server!=null) ObfuscationReflectionHelper.setPrivateValue(MinecraftServer.class, server, false, "field_71316"+"_v", "u", "serverStopped"); - - // allow any pending exit to continue, clear exitLatch - CountDownLatch latch = exitLatch; - - if (latch != null) - { - latch.countDown(); - exitLatch = null; - } - } - - public String getModName() - { - List modNames = Lists.newArrayListWithExpectedSize(3); - modNames.add("fml"); - if (!noForge) - { - modNames.add("forge"); - } - - if (Loader.instance().getFMLBrandingProperties().containsKey("snooperbranding")) - { - modNames.add(Loader.instance().getFMLBrandingProperties().get("snooperbranding")); - } - return Joiner.on(',').join(modNames); - } - - public void addModToResourcePack(ModContainer container) - { - sidedDelegate.addModAsResource(container); - } - - public void updateResourcePackList() - { - sidedDelegate.updateResourcePackList(); - } - - public String getCurrentLanguage() - { - - return sidedDelegate.getCurrentLanguage(); - } - - public void bootstrap() - { - } - - public NetworkManager getClientToServerNetworkManager() - { - return sidedDelegate.getClientToServerNetworkManager(); - } - - public void fireMouseInput() - { - bus().post(new InputEvent.MouseInputEvent()); - } - - public void fireKeyInput() - { - bus().post(new InputEvent.KeyInputEvent()); - } - - public void firePlayerChangedDimensionEvent(EntityPlayer player, int fromDim, int toDim) - { - bus().post(new PlayerEvent.PlayerChangedDimensionEvent(player, fromDim, toDim)); - } - - public void firePlayerLoggedIn(EntityPlayer player) - { - bus().post(new PlayerEvent.PlayerLoggedInEvent(player)); - } - - public void firePlayerLoggedOut(EntityPlayer player) - { - bus().post(new PlayerEvent.PlayerLoggedOutEvent(player)); - } - - public void firePlayerRespawnEvent(EntityPlayer player) - { - bus().post(new PlayerEvent.PlayerRespawnEvent(player)); - } - - public void firePlayerItemPickupEvent(EntityPlayer player, EntityItem item) - { - bus().post(new PlayerEvent.ItemPickupEvent(player, item)); - } - - public void firePlayerCraftingEvent(EntityPlayer player, ItemStack crafted, IInventory craftMatrix) - { - bus().post(new PlayerEvent.ItemCraftedEvent(player, crafted, craftMatrix)); - } - - public void firePlayerSmeltedEvent(EntityPlayer player, ItemStack smelted) - { - bus().post(new PlayerEvent.ItemSmeltedEvent(player, smelted)); - } - - public INetHandler getClientPlayHandler() - { - return sidedDelegate.getClientPlayHandler(); - } - - public void waitForPlayClient() - { - sidedDelegate.waitForPlayClient(); - } - - public void fireNetRegistrationEvent(NetworkManager manager, Set channelSet, String channel, Side side) - { - sidedDelegate.fireNetRegistrationEvent(bus(), manager, channelSet, channel, side); - } - - public boolean shouldAllowPlayerLogins() - { - return sidedDelegate.shouldAllowPlayerLogins(); - } -} \ No newline at end of file diff --git a/src/main/java/cpw/mods/fml/common/eventhandler/ASMEventHandler.java b/src/main/java/cpw/mods/fml/common/eventhandler/ASMEventHandler.java deleted file mode 100644 index 6d7081b..0000000 --- a/src/main/java/cpw/mods/fml/common/eventhandler/ASMEventHandler.java +++ /dev/null @@ -1,149 +0,0 @@ -package cpw.mods.fml.common.eventhandler; - -import static org.objectweb.asm.Opcodes.*; - -import java.lang.reflect.Method; -import java.util.HashMap; - -import mcp.mobius.mobiuscore.profiler.ProfilerSection; - -import org.apache.logging.log4j.ThreadContext; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Type; - -import com.google.common.collect.Maps; - -import cpw.mods.fml.common.ModContainer; - - -public class ASMEventHandler implements IEventListener -{ - private static int IDs = 0; - private static final String HANDLER_DESC = Type.getInternalName(IEventListener.class); - private static final String HANDLER_FUNC_DESC = Type.getMethodDescriptor(IEventListener.class.getDeclaredMethods()[0]); - private static final ASMClassLoader LOADER = new ASMClassLoader(); - private static final HashMap> cache = Maps.newHashMap(); - - private final IEventListener handler; - private final SubscribeEvent subInfo; - private final String package_; - private ModContainer owner; - public ASMEventHandler(Object target, Method method, ModContainer owner) throws Exception - { - this.owner = owner; - package_ = method.getDeclaringClass().getCanonicalName(); - handler = (IEventListener)createWrapper(method).getConstructor(Object.class).newInstance(target); - subInfo = method.getAnnotation(SubscribeEvent.class); - } - - @Override - public void invoke(Event event) - { - if (owner != null) - { - ThreadContext.put("mod", owner.getName()); - } - else - { - ThreadContext.put("mod", ""); - } - if (handler != null) - { - if (!event.isCancelable() || !event.isCanceled() || subInfo.receiveCanceled()) - { - ProfilerSection.EVENT_INVOKE.start(); - handler.invoke(event); - ProfilerSection.EVENT_INVOKE.stop(event, package_, handler, owner.getName()); - } - } - ThreadContext.remove("mod"); - } - - public EventPriority getPriority() - { - return subInfo.priority(); - } - - public Class createWrapper(Method callback) - { - if (cache.containsKey(callback)) - { - return cache.get(callback); - } - - ClassWriter cw = new ClassWriter(0); - MethodVisitor mv; - - String name = getUniqueName(callback); - String desc = name.replace('.', '/'); - String instType = Type.getInternalName(callback.getDeclaringClass()); - String eventType = Type.getInternalName(callback.getParameterTypes()[0]); - - /* - System.out.println("Name: " + name); - System.out.println("Desc: " + desc); - System.out.println("InstType: " + instType); - System.out.println("Callback: " + callback.getName() + Type.getMethodDescriptor(callback)); - System.out.println("Event: " + eventType); - */ - - cw.visit(V1_6, ACC_PUBLIC | ACC_SUPER, desc, null, "java/lang/Object", new String[]{ HANDLER_DESC }); - - cw.visitSource(".dynamic", null); - { - cw.visitField(ACC_PUBLIC, "instance", "Ljava/lang/Object;", null, null).visitEnd(); - } - { - mv = cw.visitMethod(ACC_PUBLIC, "", "(Ljava/lang/Object;)V", null, null); - mv.visitCode(); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V"); - mv.visitVarInsn(ALOAD, 0); - mv.visitVarInsn(ALOAD, 1); - mv.visitFieldInsn(PUTFIELD, desc, "instance", "Ljava/lang/Object;"); - mv.visitInsn(RETURN); - mv.visitMaxs(2, 2); - mv.visitEnd(); - } - { - mv = cw.visitMethod(ACC_PUBLIC, "invoke", HANDLER_FUNC_DESC, null, null); - mv.visitCode(); - mv.visitVarInsn(ALOAD, 0); - mv.visitFieldInsn(GETFIELD, desc, "instance", "Ljava/lang/Object;"); - mv.visitTypeInsn(CHECKCAST, instType); - mv.visitVarInsn(ALOAD, 1); - mv.visitTypeInsn(CHECKCAST, eventType); - mv.visitMethodInsn(INVOKEVIRTUAL, instType, callback.getName(), Type.getMethodDescriptor(callback)); - mv.visitInsn(RETURN); - mv.visitMaxs(2, 2); - mv.visitEnd(); - } - cw.visitEnd(); - Class ret = LOADER.define(name, cw.toByteArray()); - cache.put(callback, ret); - return ret; - } - - private String getUniqueName(Method callback) - { - return String.format("%s_%d_%s_%s_%s", getClass().getName(), IDs++, - callback.getDeclaringClass().getSimpleName(), - callback.getName(), - callback.getParameterTypes()[0].getSimpleName()); - } - - private static class ASMClassLoader extends ClassLoader - { - private ASMClassLoader() - { - super(ASMClassLoader.class.getClassLoader()); - } - - public Class define(String name, byte[] data) - { - return defineClass(name, data, 0, data.length); - } - } - -} \ No newline at end of file diff --git a/src/main/java/cpw/mods/fml/common/network/FMLOutboundHandler.java b/src/main/java/cpw/mods/fml/common/network/FMLOutboundHandler.java deleted file mode 100644 index 6af9072..0000000 --- a/src/main/java/cpw/mods/fml/common/network/FMLOutboundHandler.java +++ /dev/null @@ -1,293 +0,0 @@ -package cpw.mods.fml.common.network; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelOutboundHandlerAdapter; -import io.netty.channel.ChannelPromise; -import io.netty.channel.embedded.EmbeddedChannel; -import io.netty.util.AttributeKey; - -import java.util.List; - -import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.NetworkManager; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Sets; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; -import cpw.mods.fml.common.network.handshake.NetworkDispatcher; -import cpw.mods.fml.common.network.internal.FMLProxyPacket; -import cpw.mods.fml.relauncher.Side; - -public class FMLOutboundHandler extends ChannelOutboundHandlerAdapter { - public static final AttributeKey FML_MESSAGETARGET = new AttributeKey("fml:outboundTarget"); - public static final AttributeKey FML_MESSAGETARGETARGS = new AttributeKey("fml:outboundTargetArgs"); - public enum OutboundTarget { - /** - * The packet is sent nowhere. It will be on the {@link EmbeddedChannel#outboundMessages()} Queue. - * - * @author cpw - * - */ - NOWHERE(Sets.immutableEnumSet(Side.CLIENT, Side.SERVER)) - { - @Override - public void validateArgs(Object args) - { - // NOOP - } - - @Override - public List selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet) - { - return null; - } - - }, - /** - * The packet is sent to the {@link NetworkDispatcher} supplied as an argument. - * - * @author cpw - * - */ - DISPATCHER(Sets.immutableEnumSet(Side.SERVER)) - { - @Override - public void validateArgs(Object args) - { - if (!(args instanceof NetworkDispatcher)) - { - throw new RuntimeException("DISPATCHER expects a NetworkDispatcher"); - } - } - - @Override - public List selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet) - { - return ImmutableList.of((NetworkDispatcher)args); - } - }, - /** - * The packet is sent to the originator of the packet. This requires the inbound packet - * to have it's originator information set. - * - * @author cpw - * - */ - REPLY(Sets.immutableEnumSet(Side.SERVER)) - { - @Override - public void validateArgs(Object args) - { - // NOOP - } - - @Override - public List selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet) - { - return ImmutableList.of(packet.getDispatcher()); - } - }, - /** - * The packet is sent to the {@link EntityPlayerMP} supplied as an argument. - * - * @author cpw - * - */ - PLAYER(Sets.immutableEnumSet(Side.SERVER)) - { - @Override - public void validateArgs(Object args) - { - if (!(args instanceof EntityPlayerMP)) - { - throw new RuntimeException("PLAYER target expects a Player arg"); - } - } - @Override - public List selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet) - { - EntityPlayerMP player = (EntityPlayerMP) args; - NetworkDispatcher dispatcher = player.playerNetServerHandler.netManager.channel().attr(NetworkDispatcher.FML_DISPATCHER).get(); - return ImmutableList.of(dispatcher); - } - }, - /** - * The packet is dispatched to all players connected to the server. - * @author cpw - * - */ - ALL(Sets.immutableEnumSet(Side.SERVER)) - { - @Override - public void validateArgs(Object args) - { - } - @SuppressWarnings("unchecked") - @Override - public List selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet) - { - ImmutableList.Builder builder = ImmutableList.builder(); - for (EntityPlayerMP player : (List)FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().playerEntityList) - { - NetworkDispatcher dispatcher = player.playerNetServerHandler.netManager.channel().attr(NetworkDispatcher.FML_DISPATCHER).get(); - builder.add(dispatcher); - } - return builder.build(); - } - }, - /** - * The packet is sent to all players in the dimension identified by the integer argument. - * @author cpw - * - */ - DIMENSION(Sets.immutableEnumSet(Side.SERVER)) - { - @Override - public void validateArgs(Object args) - { - if (!(args instanceof Integer)) - { - throw new RuntimeException("DIMENSION expects an integer argument"); - } - } - @SuppressWarnings("unchecked") - @Override - public List selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet) - { - int dimension = (Integer)args; - ImmutableList.Builder builder = ImmutableList.builder(); - for (EntityPlayerMP player : (List)FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().playerEntityList) - { - if (dimension == player.dimension) - { - NetworkDispatcher dispatcher = player.playerNetServerHandler.netManager.channel().attr(NetworkDispatcher.FML_DISPATCHER).get(); - builder.add(dispatcher); - } - } - return builder.build(); - } - }, - /** - * The packet is sent to all players within range of the {@link TargetPoint} argument supplied. - * - * @author cpw - * - */ - ALLAROUNDPOINT(Sets.immutableEnumSet(Side.SERVER)) - { - @Override - public void validateArgs(Object args) - { - if (!(args instanceof TargetPoint)) - { - throw new RuntimeException("ALLAROUNDPOINT expects a TargetPoint argument"); - } - } - - @SuppressWarnings("unchecked") - @Override - public List selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet) - { - TargetPoint tp = (TargetPoint)args; - ImmutableList.Builder builder = ImmutableList.builder(); - for (EntityPlayerMP player : (List)FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().playerEntityList) - { - if (player.dimension == tp.dimension) - { - double d4 = tp.x - player.posX; - double d5 = tp.y - player.posY; - double d6 = tp.z - player.posZ; - - if (d4 * d4 + d5 * d5 + d6 * d6 < tp.range * tp.range) - { - NetworkDispatcher dispatcher = player.playerNetServerHandler.netManager.channel().attr(NetworkDispatcher.FML_DISPATCHER).get(); - builder.add(dispatcher); - } - } - } - return builder.build(); - } - }, - /** - * The packet is sent to the server this client is currently conversing with. - * @author cpw - * - */ - TOSERVER(Sets.immutableEnumSet(Side.CLIENT)) - { - @Override - public void validateArgs(Object args) - { - } - @Override - public List selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet) - { - NetworkManager clientConnection = FMLCommonHandler.instance().getClientToServerNetworkManager(); - return clientConnection == null ? ImmutableList.of() : ImmutableList.of(clientConnection.channel().attr(NetworkDispatcher.FML_DISPATCHER).get()); - } - }; - - private OutboundTarget(ImmutableSet sides) - { - this.allowed = sides; - } - public final ImmutableSet allowed; - public abstract void validateArgs(Object args); - public abstract List selectNetworks(Object args, ChannelHandlerContext context, FMLProxyPacket packet); - } - - @Override - public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception - { - if (!(msg instanceof FMLProxyPacket)) - { - return; - } - FMLProxyPacket pkt = (FMLProxyPacket) msg; - - OutboundTarget outboundTarget; - Object args = null; - NetworkDispatcher dispatcher = ctx.channel().attr(NetworkDispatcher.FML_DISPATCHER).get(); - // INTERNAL message callback - let it pass out - if (dispatcher != null) - { - ctx.write(msg, promise); - return; - } - - outboundTarget = ctx.channel().attr(FML_MESSAGETARGET).get(); - Side channelSide = ctx.channel().attr(NetworkRegistry.CHANNEL_SOURCE).get(); - if (outboundTarget != null && outboundTarget.allowed.contains(channelSide)) - { - args = ctx.channel().attr(FML_MESSAGETARGETARGS).get(); - outboundTarget.validateArgs(args); - } - else if (channelSide == Side.CLIENT) - { - outboundTarget = OutboundTarget.TOSERVER; - } - else - { - throw new FMLNetworkException("Packet arrived at the outbound handler without a valid target!"); - } - - List dispatchers = outboundTarget.selectNetworks(args, ctx, pkt); - - // This will drop the messages into the output queue at the embedded channel - if (dispatchers == null) - { - ctx.write(msg, promise); - return; - } - for (NetworkDispatcher targetDispatcher : dispatchers) - { - ProfilerSection.PACKET_OUTBOUND.stop(pkt); - targetDispatcher.sendProxy((FMLProxyPacket) msg); - } - } - -} \ No newline at end of file diff --git a/src/main/java/cpw/mods/fml/common/network/internal/FMLProxyPacket.java b/src/main/java/cpw/mods/fml/common/network/internal/FMLProxyPacket.java deleted file mode 100644 index 06f5488..0000000 --- a/src/main/java/cpw/mods/fml/common/network/internal/FMLProxyPacket.java +++ /dev/null @@ -1,148 +0,0 @@ -package cpw.mods.fml.common.network.internal; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.embedded.EmbeddedChannel; - -import java.io.IOException; - -import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import net.minecraft.network.INetHandler; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -import net.minecraft.network.PacketBuffer; -import net.minecraft.network.play.client.C17PacketCustomPayload; -import net.minecraft.network.play.server.S3FPacketCustomPayload; - -import org.apache.logging.log4j.Level; - -import cpw.mods.fml.common.FMLLog; -import cpw.mods.fml.common.network.FMLNetworkException; -import cpw.mods.fml.common.network.NetworkRegistry; -import cpw.mods.fml.common.network.handshake.NetworkDispatcher; -import cpw.mods.fml.relauncher.Side; - -public class FMLProxyPacket extends Packet { - final String channel; - private Side target; - private final ByteBuf payload; - private INetHandler netHandler; - private NetworkDispatcher dispatcher; - - private FMLProxyPacket(byte[] payload, String channel) - { - this(Unpooled.wrappedBuffer(payload), channel); - } - - public FMLProxyPacket(S3FPacketCustomPayload original) - { - this(original.func_149168_d(), original.func_149169_c()); - this.target = Side.CLIENT; - } - - public FMLProxyPacket(C17PacketCustomPayload original) - { - this(original.func_149558_e(), original.func_149559_c()); - this.target = Side.SERVER; - } - - public FMLProxyPacket(ByteBuf payload, String channel) - { - this.channel = channel; - this.payload = payload; - } - /** - * Reads the raw packet data from the data stream. - */ - @Override - public void readPacketData(PacketBuffer packetbuffer) throws IOException - { - // NOOP - we are not built this way - } - - /** - * Writes the raw packet data to the data stream. - */ - @Override - public void writePacketData(PacketBuffer packetbuffer) throws IOException - { - // NOOP - we are not built this way - } - - /** - * Passes this Packet on to the NetHandler for processing. - */ - @Override - public void processPacket(INetHandler inethandler) - { - ProfilerSection.PACKET_INBOUND.stop(this); - - this.netHandler = inethandler; - EmbeddedChannel internalChannel = NetworkRegistry.INSTANCE.getChannel(this.channel, this.target); - if (internalChannel != null) - { - internalChannel.attr(NetworkRegistry.NET_HANDLER).set(this.netHandler); - try - { - internalChannel.writeInbound(this); - } - catch (FMLNetworkException ne) - { - FMLLog.log(Level.ERROR, ne, "There was a network exception handling a packet on channel %s", channel); - dispatcher.rejectHandshake(ne.getMessage()); - } - catch (Throwable t) - { - FMLLog.log(Level.ERROR, t, "There was a critical exception handling a packet on channel %s", channel); - dispatcher.rejectHandshake("A fatal error has occured, this connection is terminated"); - } - } - } - - public String channel() - { - return channel; - } - public ByteBuf payload() - { - return payload; - } - public INetHandler handler() - { - return netHandler; - } - public Packet toC17Packet() - { - return new C17PacketCustomPayload(channel, payload.array()); - } - - public Packet toS3FPacket() - { - return new S3FPacketCustomPayload(channel, payload.array()); - } - - public void setTarget(Side target) - { - this.target = target; - } - - public void setDispatcher(NetworkDispatcher networkDispatcher) - { - this.dispatcher = networkDispatcher; - } - - public NetworkManager getOrigin() - { - return this.dispatcher != null ? this.dispatcher.manager : null; - } - - public NetworkDispatcher getDispatcher() - { - return this.dispatcher; - } - - public Side getTarget() - { - return target; - } -} \ No newline at end of file diff --git a/src/main/java/mapwriter/BackgroundExecutor.java b/src/main/java/mapwriter/BackgroundExecutor.java new file mode 100644 index 0000000..ebeb786 --- /dev/null +++ b/src/main/java/mapwriter/BackgroundExecutor.java @@ -0,0 +1,124 @@ +package mapwriter; + +import java.util.LinkedList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import mapwriter.tasks.Task; + + + +/* +This class handles executing and managing 'tasks'. +A single background thread runs tasks in the sequence they are added (via addTask()). +A linked list FIFO queue of every unfinished task is processed every time the processTaskQueue method is called. +processTaskQueue checks the task at the front of the queue to see if the background thread has processed it. +If it the task is complete processTaskQueue calls the onComplete() method of the task and removes it from the queue. +If it is not complete the task is added to the front of the queue again. +In this way the tasks are always processed sequentially, in the order they were added to the queue. + +Tasks are extensions of the base Task class. +There are two abstract methods which must be overwritten by the extending class. + void run() + Is executed in the background thread when the executor reaches this task. + void onComplete() + Is called by processTaskQueue() when the task is done (after the run method is complete). + This method runs in the main thread so is a good place to copy the results of the run() method. + +The run() method of a task added to the queue is guaranteed to be run before the run() method of the next task +added. Likewise the onComplete() method of the first task is guaranteed to be run before the onComplete() of the second +task. However the run() method of any class added after a Task may be executed before the onComplete() method of +the earlier Task is called. + +e.g. addTask(Task1) + addTask(Task2) + addTask(Task3) + +may run in the order: + Task1.run() + Task2.run() + Task1.onComplete() + Task3.run() + Task2.onComplete() + Task3.onComplete() +*/ + +public class BackgroundExecutor { + + private ExecutorService executor; + private LinkedList taskQueue; + public boolean closed = false; + + public BackgroundExecutor() { + this.executor = Executors.newSingleThreadExecutor(); + this.taskQueue = new LinkedList(); + } + + // add a task to the queue + public boolean addTask(Task task) { + if (!this.closed) { + Future future = this.executor.submit(task); + task.setFuture(future); + this.taskQueue.add(task); + } else { + MwUtil.log("MwExecutor.addTask: error: cannot add task to closed executor"); + } + return this.closed; + } + + // Pop a Task entry from the task queue and check if the task's thread has finished. + // If it has completed then call onComplete for the task. + // If it has not completed then push the task back on the queue. + public boolean processTaskQueue() { + boolean processed = false; + Task task = this.taskQueue.poll(); + if (task != null) { + if (task.isDone()) { + task.printException(); + task.onComplete(); + processed = true; + } else { + // put entry back on top of queue + this.taskQueue.push(task); + } + } + return !processed; + } + + public boolean processRemainingTasks(int attempts, int delay) { + while ((this.taskQueue.size() > 0) && (attempts > 0)) { + if (this.processTaskQueue()) { + try { + Thread.sleep(delay); + } catch (Exception e) { + } + attempts--; + } + } + return (attempts <= 0); + } + + public int tasksRemaining() { + return this.taskQueue.size(); + } + + public boolean close() { + boolean error = true; + try { + // stop accepting new tasks + this.executor.shutdown(); + // process remaining tasks + this.processRemainingTasks(50, 5); + // should already be terminated, but just in case... + error = !this.executor.awaitTermination(10L, TimeUnit.SECONDS); + error = false; + } catch (InterruptedException e) { + MwUtil.log("error: IO task was interrupted during shutdown"); + e.printStackTrace(); + } + this.closed = true; + return error; + } +} diff --git a/src/main/java/mapwriter/BlockColourGen.java b/src/main/java/mapwriter/BlockColourGen.java new file mode 100644 index 0000000..d8a4ed2 --- /dev/null +++ b/src/main/java/mapwriter/BlockColourGen.java @@ -0,0 +1,176 @@ +package mapwriter; + +import mapwriter.region.BlockColours; +import mapwriter.region.BlockColours.BlockType; +import net.minecraft.block.Block; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.util.IIcon; +import net.minecraft.world.biome.BiomeGenBase; + +// Static class to generate BlockColours. +// This is separate from BlockColours because it needs to run in the GL rendering thread +// whereas the generated BlockColours object is used only in the background thread. +// So basically split to make it clear that BlockColourGen and the generated BlockColours +// must not have any interaction after it is generated. + +public class BlockColourGen { + + private static int getIconMapColour(IIcon icon, Texture terrainTexture) { + // flipped icons have the U and V coords reversed (minU > maxU, minV > maxV). + // thanks go to taelnia for fixing this. + int iconX = (int) Math.round(((float) terrainTexture.w) * Math.min(icon.getMinU(), icon.getMaxU())); + int iconY = (int) Math.round(((float) terrainTexture.h) * Math.min(icon.getMinV(), icon.getMaxV())); + int iconWidth = (int) Math.round(((float) terrainTexture.w) * Math.abs(icon.getMaxU() - icon.getMinU())); + int iconHeight = (int) Math.round(((float) terrainTexture.h) * Math.abs(icon.getMaxV() - icon.getMinV())); + + int[] pixels = new int[iconWidth * iconHeight]; + + //MwUtil.log("(%d, %d) %dx%d", iconX, iconY, iconWidth, iconHeight); + + terrainTexture.getRGB(iconX, iconY, iconWidth, iconHeight, pixels, 0, iconWidth); + + // need to use custom averaging routine rather than scaling down to one pixel to + // stop transparent pixel colours being included in the average. + return Render.getAverageColourOfArray(pixels); + } + + private static int adjustBlockColourFromType(BlockColours bc, int blockAndMeta, int blockColour) { + // for normal blocks multiply the block colour by the render colour. + // for other blocks the block colour will be multiplied by the biome colour. + int blockid = blockAndMeta >> 4; + Block block = (Block) Block.blockRegistry.getObjectById(blockid); + BlockType blockType = bc.getBlockType(blockAndMeta); + switch (blockType) { + + case OPAQUE: + blockColour |= 0xff000000; + case NORMAL: + // fix crash when mods don't implement getRenderColor for all + // block meta values. + try { + int renderColour = block.getRenderColor(blockAndMeta & 0xf); + if (renderColour != 0xffffff) { + blockColour = Render.multiplyColours(blockColour, 0xff000000 | renderColour); + } + } catch (RuntimeException e) { + // do nothing + } + break; + case LEAVES: + // leaves look weird on the map if they are not opaque. + // they also look too dark if the render colour is applied. + blockColour |= 0xff000000; + break; + default: + break; + } + return blockColour; + } + + private static void genBiomeColours(BlockColours bc) { + // generate array of foliage, grass, and water colour multipliers + // for each biome. + + for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) { + if (BiomeGenBase.getBiomeGenArray()[i] != null) { + bc.setBiomeWaterShading(i, BiomeGenBase.getBiomeGenArray()[i].getWaterColorMultiplier() & 0xffffff); + bc.setBiomeGrassShading(i, BiomeGenBase.getBiomeGenArray()[i].getBiomeGrassColor(0,0,0) & 0xffffff); //FIXME 0,0,0? + bc.setBiomeFoliageShading(i, BiomeGenBase.getBiomeGenArray()[i].getBiomeFoliageColor(0,0,0) & 0xffffff); //FIXME 0,0,0? + } else { + bc.setBiomeWaterShading(i, 0xffffff); + bc.setBiomeGrassShading(i, 0xffffff); + bc.setBiomeFoliageShading(i, 0xffffff); + } + } + } + + public static void genBlockColours(BlockColours bc) { + + MwUtil.log("generating block map colours from textures"); + + // copy terrain texture to MwRender pixel bytebuffer + + // bind the terrain texture + //Minecraft.getMinecraft().func_110434_K().func_110577_a(TextureMap.field_110575_b); + // get the bound texture id + //int terrainTextureId = Render.getBoundTextureId(); + + int terrainTextureId = Minecraft.getMinecraft().renderEngine.getTexture(TextureMap.locationBlocksTexture).getGlTextureId(); + + // create texture object from the currently bound GL texture + if (terrainTextureId == 0) { + MwUtil.log("error: could get terrain texture ID"); + return; + } + Texture terrainTexture = new Texture(terrainTextureId); + + double u1Last = 0; + double u2Last = 0; + double v1Last = 0; + double v2Last = 0; + int blockColourLast = 0; + int e_count = 0; + int b_count = 0; + int s_count = 0; + + for (int blockID = 0; blockID < 4096; blockID++) { //TODO: replace hardcoded 4096 with actual registry size + for (int dv = 0; dv < 16; dv++) { + + int blockAndMeta = ((blockID & 0xfff) << 4) | (dv & 0xf); + Block block = (Block) Block.blockRegistry.getObjectById(blockID); + int blockColour = 0; + + if (block != null) { + + IIcon icon = null; + try { + icon = block.getIcon(1, dv); + } catch (Exception e) { + //MwUtil.log("genFromTextures: exception caught when requesting block texture for %03x:%x", blockID, dv); + //e.printStackTrace(); + e_count++; + } + + if (icon != null) { + double u1 = icon.getMinU(); + double u2 = icon.getMaxU(); + double v1 = icon.getMinV(); + double v2 = icon.getMaxV(); + + if ((u1 == u1Last) && (u2 == u2Last) && (v1 == v1Last) && (v2 == v2Last)) { + blockColour = blockColourLast; + s_count++; + } else { + blockColour = getIconMapColour(icon, terrainTexture); + u1Last = u1; + u2Last = u2; + v1Last = v1; + v2Last = v2; + blockColourLast = blockColour; + b_count++; + } + //if (dv == 0) + // MwUtil.log("block %03x:%x colour = %08x", blockID, dv, blockColour); + } + + // doesn't work as some leaves blocks aren't rendered using the biome + // foliage colour + //try { + // if (block.isLeaves(null, 0, 0, 0)) { + // bc.setBlockType(blockAndMeta, BlockType.LEAVES); + // } + //} catch (NullPointerException e) { + //} + + blockColour = adjustBlockColourFromType(bc, blockAndMeta, blockColour); + } + bc.setColour(blockAndMeta, blockColour); + } + } + + MwUtil.log("processed %d block textures, %d skipped, %d exceptions", b_count, s_count, e_count); + + genBiomeColours(bc); + } +} diff --git a/src/main/java/mapwriter/ChunkManager.java b/src/main/java/mapwriter/ChunkManager.java new file mode 100644 index 0000000..674a4b8 --- /dev/null +++ b/src/main/java/mapwriter/ChunkManager.java @@ -0,0 +1,149 @@ +package mapwriter; + +import java.util.Map; + +import mapwriter.region.MwChunk; +import mapwriter.tasks.SaveChunkTask; +import mapwriter.tasks.UpdateSurfaceChunksTask; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.storage.ExtendedBlockStorage; + +public class ChunkManager { + public Mw mw; + private boolean closed = false; + private CircularHashMap chunkMap = new CircularHashMap(); + + private static final int VISIBLE_FLAG = 0x01; + private static final int VIEWED_FLAG = 0x02; + + public ChunkManager(Mw mw) { + this.mw = mw; + } + + public synchronized void close() { + this.closed = true; + this.saveChunks(); + this.chunkMap.clear(); + } + + // create MwChunk from Minecraft chunk. + // only MwChunk's should be used in the background thread. + // TODO: make this a full copy of chunk data to prevent possible race conditions + public static MwChunk copyToMwChunk(Chunk chunk) { + + byte[][] msbArray = new byte[16][]; + byte[][] lsbArray = new byte[16][]; + byte[][] metaArray = new byte[16][]; + byte[][] lightingArray = new byte[16][]; + + ExtendedBlockStorage[] storageArrays = chunk.getBlockStorageArray(); + if (storageArrays != null) { + for (ExtendedBlockStorage storage : storageArrays) { + if (storage != null) { + int y = (storage.getYLocation() >> 4) & 0xf; + lsbArray[y] = storage.getBlockLSBArray(); + msbArray[y] = (storage.getBlockMSBArray() != null) ? storage.getBlockMSBArray().data : null; + metaArray[y] = (storage.getMetadataArray() != null) ? storage.getMetadataArray().data : null; + lightingArray[y] = (storage.getBlocklightArray() != null) ? storage.getBlocklightArray().data : null; + } + } + } + + return new MwChunk(chunk.xPosition, chunk.zPosition, chunk.worldObj.provider.dimensionId, + msbArray, lsbArray, metaArray, lightingArray, chunk.getBiomeArray()); + } + + public synchronized void addChunk(Chunk chunk) { + if (!this.closed && (chunk != null)) { + this.chunkMap.put(chunk, 0); + } + } + + public synchronized void removeChunk(Chunk chunk) { + if (!this.closed && (chunk != null)) { + if(!this.chunkMap.containsKey(chunk)) return; //FIXME: Is this failsafe enough for unloading? + int flags = this.chunkMap.get(chunk); + if ((flags & VIEWED_FLAG) != 0) { + this.addSaveChunkTask(chunk); + } + this.chunkMap.remove(chunk); + } + } + + public synchronized void saveChunks() { + for (Map.Entry entry : this.chunkMap.entrySet()) { + int flags = entry.getValue(); + if ((flags & VIEWED_FLAG) != 0) { + this.addSaveChunkTask(entry.getKey()); + } + } + } + + public void updateUndergroundChunks() { + int chunkArrayX = (this.mw.playerXInt >> 4) - 1; + int chunkArrayZ = (this.mw.playerZInt >> 4) - 1; + MwChunk[] chunkArray = new MwChunk[9]; + for (int z = 0; z < 3; z++) { + for (int x = 0; x < 3; x++) { + Chunk chunk = this.mw.mc.theWorld.getChunkFromChunkCoords( + chunkArrayX + x, + chunkArrayZ + z + ); + if (!chunk.isEmpty()) { + chunkArray[(z * 3) + x] = copyToMwChunk(chunk); + } + } + } + } + + public void updateSurfaceChunks() { + int chunksToUpdate = Math.min(this.chunkMap.size(), this.mw.chunksPerTick); + MwChunk[] chunkArray = new MwChunk[chunksToUpdate]; + for (int i = 0; i < chunksToUpdate; i++) { + Map.Entry entry = this.chunkMap.getNextEntry(); + if (entry != null) { + // if this chunk is within a certain distance to the player then + // add it to the viewed set + Chunk chunk = entry.getKey(); + int flags = entry.getValue(); + if (MwUtil.distToChunkSq(this.mw.playerXInt, this.mw.playerZInt, chunk) <= this.mw.maxChunkSaveDistSq) { + flags |= (VISIBLE_FLAG | VIEWED_FLAG); + } else { + flags &= ~VISIBLE_FLAG; + } + entry.setValue(flags); + + if ((flags & VISIBLE_FLAG) != 0) { + chunkArray[i] = copyToMwChunk(chunk); + } else { + chunkArray[i] = null; + } + } + } + + this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); + } + + public void onTick() { + if (!this.closed) { + if ((this.mw.tickCounter & 0xf) == 0) { + this.updateUndergroundChunks(); + } else { + this.updateSurfaceChunks(); + } + } + } + + public void forceChunks(MwChunk[] chunkArray){ + this.mw.executor.addTask(new UpdateSurfaceChunksTask(this.mw, chunkArray)); + } + + private void addSaveChunkTask(Chunk chunk) { + if ((this.mw.multiplayer && this.mw.regionFileOutputEnabledMP) || + (!this.mw.multiplayer && this.mw.regionFileOutputEnabledSP)) { + if (!chunk.isEmpty()) { + this.mw.executor.addTask(new SaveChunkTask(copyToMwChunk(chunk), this.mw.regionManager)); + } + } + } +} diff --git a/src/main/java/mapwriter/CircularHashMap.java b/src/main/java/mapwriter/CircularHashMap.java new file mode 100644 index 0000000..30e1c73 --- /dev/null +++ b/src/main/java/mapwriter/CircularHashMap.java @@ -0,0 +1,194 @@ +package mapwriter; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class CircularHashMap { + /* A hash map where each node is linked to the previous and next nodes + * in the order of insertion. + * + * The 'head' node is the most recently added node. Its next pointer + * links to the first node added, forming a circle. + * + * The getNextEntry and getPrevEntry methods use an internal pointer to + * the 'current' node, and return either the current nodes 'next' or + * 'prev' node respectively. + * The current node becomes the node that was returned, such that repeated + * calls traverse all nodes in the map. + * + * Most methods are similar to those in the java.util.Map interface. + * The CircularHashMap class does not implement Map however as some of the + * required methods seemed unnecessary. + */ + + private Map nodeMap = new HashMap(); + private Node headNode = null; + private Node currentNode = null; + + public class Node implements Map.Entry{ + private final K key; + private V value; + private Node next; + private Node prev; + + Node(K key, V value) { + this.key = key; + this.value = value; + this.next = this; + this.prev = this; + } + + @Override + public K getKey() { + return this.key; + } + + @Override + public V getValue() { + return this.value; + } + + @Override + public V setValue(V value) { + V oldValue = this.value; + this.value = value; + return oldValue; + } + } + + public V put(K key, V value) { + Node node = this.nodeMap.get(key); + if (node == null) { + // add new node + node = new Node(key, value); + this.nodeMap.put(key, node); + + if (this.headNode == null) { + node.next = node; + node.prev = node; + + } else { + node.next = this.headNode.next; + node.prev = this.headNode; + + this.headNode.next.prev = node; + this.headNode.next = node; + } + + if (this.currentNode == null) { + this.currentNode = node; + } + + this.headNode = node; + + } else { + // update node + node.value = value; + } + return value; + } + + public V remove(Object key) { + Node node = this.nodeMap.get(key); + V value = null; + if (node != null) { + if (this.headNode == node) { + this.headNode = node.next; + if (this.headNode == node) { + this.headNode = null; + } + } + if (this.currentNode == node) { + this.currentNode = node.next; + if (this.currentNode == node) { + this.currentNode = null; + } + } + + node.prev.next = node.next; + node.next.prev = node.prev; + node.next = null; + node.prev = null; + value = node.value; + + this.nodeMap.remove(key); + } + return value; + } + + public void clear() { + for (Node node : this.nodeMap.values()) { + node.next = null; + node.prev = null; + } + this.nodeMap.clear(); + this.headNode = null; + this.currentNode = null; + } + + public boolean containsKey(Object key) { + return this.nodeMap.containsKey(key); + } + + public int size() { + return this.nodeMap.size(); + } + + public Set keySet() { + return this.nodeMap.keySet(); + } + + public Collection values() { + Collection list = new ArrayList(); + for (Node node : this.nodeMap.values()) { + list.add(node.value); + } + return list; + } + + public Collection> entrySet() { + return new ArrayList>(this.nodeMap.values()); + } + + public V get(Object key) { + Node node = this.nodeMap.get(key); + return (node != null) ? node.value : null; + } + + public boolean isEmpty() { + return this.nodeMap.isEmpty(); + } + + // + // interface to traverse circular nodes + // + + public Map.Entry getNextEntry() { + if (this.currentNode != null) { + this.currentNode = this.currentNode.next; + } + return this.currentNode; + } + + public Map.Entry getPrevEntry() { + if (this.currentNode != null) { + this.currentNode = this.currentNode.prev; + } + return this.currentNode; + } + + public void rewind() { + this.currentNode = (this.headNode != null) ? this.headNode.next : null; + } + + public boolean setPosition(K key) { + Node node = this.nodeMap.get(key); + if (node != null) { + this.currentNode = node; + } + return (node != null); + } +} diff --git a/src/main/java/mapwriter/Mw.java b/src/main/java/mapwriter/Mw.java new file mode 100644 index 0000000..11d41ad --- /dev/null +++ b/src/main/java/mapwriter/Mw.java @@ -0,0 +1,741 @@ +package mapwriter; + +import mapwriter.forge.MwConfig; +import mapwriter.forge.MwForge; +import mapwriter.forge.MwKeyHandler; +import mapwriter.gui.MwGui; +import mapwriter.gui.MwGuiMarkerDialog; +import mapwriter.map.*; +import mapwriter.overlay.OverlaySlime; +import mapwriter.region.BlockColours; +import mapwriter.region.RegionManager; +import mapwriter.tasks.CloseRegionManagerTask; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGameOver; +import net.minecraft.client.settings.KeyBinding; +import net.minecraft.server.integrated.IntegratedServer; +import net.minecraft.util.ChatComponentText; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +/* + +data transfers +--------------- +chunk image (16x16 int[]) -> texture (512x512 GL texture) | every chunk update +region file png -> texture (512x512 GL texture) | on region load (slow, disk access) +texture (512x512 GL texture) -> region file png | on region unload (slow, disk access) +chunk (Chunk object) -> anvil save file | on chunk unload, separate thread handled by minecraft + +background thread +------------------ +performs all data transfers except Chunk->Anvil, which is handled by ThreadedFileIOBase in minecraft. +regions created in main thread when necessary, but filled from the background thread. + +initialization +-------------- +init() + Called once only. + - registers event and key handlers + - loads configuration + - inits marker manager + - inits commands + - inits chunkQueue + +onClientLoggedIn() + Called upon entry to each world. + - inits executor + - inits overlay + - inits anvil save handler + - inits regionMap + +onConnectionClosed() + Called on every exit from world. + - closes chunkLoader + - closes regionMap + - closes overlay + - saves markermanager + - saves config + - closes executor + - flush chunkQueue + +Every hook and event handler should be enclosed in an 'if (this.ready)' statement to ensure that all +components are initialised. +One exception is the fillChunk handler which adds chunks to the chunkQueue so that they can be processed +after initialization. This is so that no chunks are skipped if the chunks are loaded before the player is +logged in. + +*/ + +public class Mw { + + public Minecraft mc = null; + + // server information + public String worldName = "default"; + private String serverName = "default"; + private int serverPort = 0; + + // configuration files (global and world specific) + public MwConfig config; + public MwConfig worldConfig = null; + + // directories + private final File configDir; + private final File saveDir; + public File worldDir = null; + public File imageDir = null; + + // configuration options + public boolean linearTextureScalingEnabled = true; + public int coordsMode = 0; + public boolean undergroundMode = false; + public boolean teleportEnabled = true; + public String teleportCommand = "tp"; + public int defaultTeleportHeight = 80; + public int maxZoom = 5; + public int minZoom = -5; + public boolean useSavedBlockColours = false; + public int maxChunkSaveDistSq = 128 * 128; + public boolean mapPixelSnapEnabled = true; + public int textureSize = 2048; + public int configTextureSize = 2048; + public int maxDeathMarkers = 3; + public int chunksPerTick = 5; + public boolean portNumberInWorldNameEnabled = true; + public String saveDirOverride = ""; + public boolean regionFileOutputEnabledSP = true; + public boolean regionFileOutputEnabledMP = true; + public int backgroundTextureMode = 0; + //public boolean lightingEnabled = false; + + // flags and counters + private boolean onPlayerDeathAlreadyFired = false; + public boolean ready = false; + public boolean multiplayer = false; + public int tickCounter = 0; + + // list of available dimensions + public List dimensionList = new ArrayList(); + + // player position and heading + public double playerX = 0.0; + public double playerZ = 0.0; + public double playerY = 0.0; + public int playerXInt = 0; + public int playerYInt = 0; + public int playerZInt = 0; + public double playerHeading = 0.0; + public int playerDimension = 0; + public double mapRotationDegrees = 0.0; + + // constants + public final static String catWorld = "world"; + public final static String catMarkers = "markers"; + public final static String catOptions = "options"; + public final static String worldDirConfigName = "mapwriter.cfg"; + public final static String blockColourSaveFileName = "MapWriterBlockColours.txt"; + public final static String blockColourOverridesFileName = "MapWriterBlockColourOverrides.txt"; + + // instances of components + public MapTexture mapTexture = null; + public UndergroundTexture undergroundMapTexture = null; + public BackgroundExecutor executor = null; + public MiniMap miniMap = null; + public MarkerManager markerManager = null; + public BlockColours blockColours = null; + public RegionManager regionManager = null; + public ChunkManager chunkManager = null; + public Trail playerTrail = null; + + public static Mw instance; + + public Mw(MwConfig config) { + // client only initialization + // oops, no idea why I was using a ModLoader method to get the Minecraft instance before + this.mc = Minecraft.getMinecraft(); + + // load config + this.config = config; + + // create base save directory + this.saveDir = new File(this.mc.mcDataDir, "saves"); + this.configDir = new File(this.mc.mcDataDir, "config"); + + this.ready = false; + + RegionManager.logger = MwForge.logger; + + instance = this; + } + + public String getWorldName() { + String worldName; + if (this.multiplayer) { + if (this.portNumberInWorldNameEnabled) { + worldName = String.format("%s_%d", this.serverName, this.serverPort); + } else { + worldName = String.format("%s", this.serverName); + } + + } else { + // cannot use this.mc.theWorld.getWorldInfo().getWorldName() as it + // is set statically to "MpServer". + IntegratedServer server = this.mc.getIntegratedServer(); + worldName = (server != null) ? server.getFolderName() : "sp_world"; + } + + // strip invalid characters from the server name so that it + // can't be something malicious like '..\..\..\windows\' + worldName = MwUtil.mungeString(worldName); + + // if something went wrong make sure the name is not blank + // (causes crash on start up due to empty configuration section) + if (worldName == "") { + worldName = "default"; + } + return worldName; + } + + public void loadConfig() { + this.config.load(); + this.linearTextureScalingEnabled = this.config.getOrSetBoolean(catOptions, "linearTextureScaling", this.linearTextureScalingEnabled); + this.useSavedBlockColours = this.config.getOrSetBoolean(catOptions, "useSavedBlockColours", this.useSavedBlockColours); + this.teleportEnabled = this.config.getOrSetBoolean(catOptions, "teleportEnabled", this.teleportEnabled); + this.teleportCommand = this.config.get(catOptions, "teleportCommand", this.teleportCommand).getString(); + this.coordsMode = this.config.getOrSetInt(catOptions, "coordsMode", this.coordsMode, 0, 2); + this.maxChunkSaveDistSq = this.config.getOrSetInt(catOptions, "maxChunkSaveDistSq", this.maxChunkSaveDistSq, 1, 256 * 256); + this.mapPixelSnapEnabled = this.config.getOrSetBoolean(catOptions, "mapPixelSnapEnabled", this.mapPixelSnapEnabled); + this.maxDeathMarkers = this.config.getOrSetInt(catOptions, "maxDeathMarkers", this.maxDeathMarkers, 0, 1000); + this.chunksPerTick = this.config.getOrSetInt(catOptions, "chunksPerTick", this.chunksPerTick, 1, 500); + this.saveDirOverride = this.config.get(catOptions, "saveDirOverride", this.saveDirOverride).getString(); + this.portNumberInWorldNameEnabled = config.getOrSetBoolean(catOptions, "portNumberInWorldNameEnabled", this.portNumberInWorldNameEnabled); + this.undergroundMode = this.config.getOrSetBoolean(catOptions, "undergroundMode", this.undergroundMode); + this.regionFileOutputEnabledSP = this.config.getOrSetBoolean(catOptions, "regionFileOutputEnabledSP", this.regionFileOutputEnabledSP); + this.regionFileOutputEnabledMP = this.config.getOrSetBoolean(catOptions, "regionFileOutputEnabledMP", this.regionFileOutputEnabledMP); + this.backgroundTextureMode = this.config.getOrSetInt(catOptions, "backgroundTextureMode", this.backgroundTextureMode, 0, 1); + //this.lightingEnabled = this.config.getOrSetBoolean(catOptions, "lightingEnabled", this.lightingEnabled); + + this.maxZoom = this.config.getOrSetInt(catOptions, "zoomOutLevels", this.maxZoom, 1, 256); + this.minZoom = -this.config.getOrSetInt(catOptions, "zoomInLevels", -this.minZoom, 1, 256); + + this.configTextureSize = this.config.getOrSetInt(catOptions, "textureSize", this.configTextureSize, 1024, 8192); + this.setTextureSize(); + } + + public void loadWorldConfig() { + // load world specific config file + File worldConfigFile = new File(this.worldDir, worldDirConfigName); + this.worldConfig = new MwConfig(worldConfigFile); + this.worldConfig.load(); + + this.dimensionList.clear(); + this.worldConfig.getIntList(catWorld, "dimensionList", this.dimensionList); + this.addDimension(0); + this.cleanDimensionList(); + } + + public void saveConfig() { + this.config.setBoolean(catOptions, "linearTextureScaling", this.linearTextureScalingEnabled); + this.config.setBoolean(catOptions, "useSavedBlockColours", this.useSavedBlockColours); + this.config.setInt(catOptions, "textureSize", this.configTextureSize); + this.config.setInt(catOptions, "coordsMode", this.coordsMode); + this.config.setInt(catOptions, "maxChunkSaveDistSq", this.maxChunkSaveDistSq); + this.config.setBoolean(catOptions, "mapPixelSnapEnabled", this.mapPixelSnapEnabled); + this.config.setInt(catOptions, "maxDeathMarkers", this.maxDeathMarkers); + this.config.setInt(catOptions, "chunksPerTick", this.chunksPerTick); + this.config.setBoolean(catOptions, "undergroundMode", this.undergroundMode); + this.config.setInt(catOptions, "backgroundTextureMode", this.backgroundTextureMode); + //this.config.setBoolean(catOptions, "lightingEnabled", this.lightingEnabled); + + this.config.save(); + } + + public void saveWorldConfig() { + this.worldConfig.setIntList(catWorld, "dimensionList", this.dimensionList); + this.worldConfig.save(); + } + + public void setTextureSize() { + if (this.configTextureSize != this.textureSize) { + int maxTextureSize = Render.getMaxTextureSize(); + int textureSize = 1024; + while ((textureSize <= maxTextureSize) && (textureSize <= this.configTextureSize)) { + textureSize *= 2; + } + textureSize /= 2; + + MwUtil.log("GL reported max texture size = %d", maxTextureSize); + MwUtil.log("texture size from config = %d", this.configTextureSize); + MwUtil.log("setting map texture size to = %d", textureSize); + + this.textureSize = textureSize; + if (this.ready) { + // if we are already up and running need to close and reinitialize the map texture and + // region manager. + this.reloadMapTexture(); + } + } + } + + // update the saved player position and orientation + // called every tick + public void updatePlayer() { + // get player pos + this.playerX = (double) this.mc.thePlayer.posX; + this.playerY = (double) this.mc.thePlayer.posY; + this.playerZ = (double) this.mc.thePlayer.posZ; + this.playerXInt = (int) Math.floor(this.playerX); + this.playerYInt = (int) Math.floor(this.playerY); + this.playerZInt = (int) Math.floor(this.playerZ); + + // rotationYaw of 0 points due north, we want it to point due east instead + // so add pi/2 radians (90 degrees) + this.playerHeading = Math.toRadians(this.mc.thePlayer.rotationYaw) + (Math.PI / 2.0D); + this.mapRotationDegrees = -this.mc.thePlayer.rotationYaw + 180; + + // set by onWorldLoad + //this.playerDimension = this.mc.theWorld.provider.dimensionId; + } + + public void addDimension(int dimension) { + int i = this.dimensionList.indexOf(dimension); + if (i < 0) { + this.dimensionList.add(dimension); + } + } + + public void cleanDimensionList() { + List dimensionListCopy = new ArrayList(this.dimensionList); + this.dimensionList.clear(); + for (int dimension : dimensionListCopy) { + this.addDimension(dimension); + } + } + + public void toggleMarkerMode() { + this.markerManager.nextGroup(); + this.markerManager.update(); + this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); + } + + // cheap and lazy way to teleport... + public void teleportTo(int x, int y, int z) { + if (this.teleportEnabled) { + this.mc.thePlayer.sendChatMessage(String.format("/%s %d %d %d", this.teleportCommand, x, y, z)); + } else { + MwUtil.printBoth("teleportation is disabled in mapwriter.cfg"); + } + } + + public void warpTo(String name) { + if (this.teleportEnabled) { + //MwUtil.printBoth(String.format("warping to %s", name)); + this.mc.thePlayer.sendChatMessage(String.format("/warp %s", name)); + } else { + MwUtil.printBoth("teleportation is disabled in mapwriter.cfg"); + } + } + + public void teleportToMapPos(MapView mapView, int x, int y, int z) { + if (!this.teleportCommand.equals("warp")) { + double scale = mapView.getDimensionScaling(this.playerDimension); + this.teleportTo((int) (x / scale), y, (int) (z / scale)); + } else { + MwUtil.printBoth("teleport command is set to 'warp', can only warp to markers"); + } + } + + public void teleportToMarker(Marker marker) { + if (this.teleportCommand.equals("warp")) { + this.warpTo(marker.name); + } else if (marker.dimension == this.playerDimension) { + this.teleportTo(marker.x, marker.y, marker.z); + } else { + MwUtil.printBoth("cannot teleport to marker in different dimension"); + } + } + + public void loadBlockColourOverrides(BlockColours bc) { + File f = new File(this.configDir, blockColourOverridesFileName); + if (f.isFile()) { + MwUtil.logInfo("loading block colour overrides file %s", f); + bc.loadFromFile(f); + } else { + MwUtil.logInfo("recreating block colour overrides file %s", f); + BlockColours.writeOverridesFile(f); + if (f.isFile()) { + bc.loadFromFile(f); + } else { + MwUtil.logError("could not load block colour overrides from file %s", f); + } + } + } + + public void saveBlockColours(BlockColours bc) { + File f = new File(this.configDir, blockColourSaveFileName); + MwUtil.logInfo("saving block colours to '%s'", f); + bc.saveToFile(f); + } + + public void reloadBlockColours() { + BlockColours bc = new BlockColours(); + File f = new File(this.configDir, blockColourSaveFileName); + if (this.useSavedBlockColours && f.isFile()) { + // load block colours from file + MwUtil.logInfo("loading block colours from %s", f); + bc.loadFromFile(f); + this.loadBlockColourOverrides(bc); + } else { + // generate block colours from current texture pack + MwUtil.logInfo("generating block colours"); + // block type overrides need to be loaded before the block colours are generated + this.loadBlockColourOverrides(bc); + BlockColourGen.genBlockColours(bc); + // load overrides again to override block and biome colours + this.loadBlockColourOverrides(bc); + this.saveBlockColours(bc); + } + this.blockColours = bc; + } + + public void reloadMapTexture() { + this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); + this.executor.close(); + MapTexture oldMapTexture = this.mapTexture; + MapTexture newMapTexture = new MapTexture(this.textureSize, this.linearTextureScalingEnabled); + this.mapTexture = newMapTexture; + if (oldMapTexture != null) { + oldMapTexture.close(); + } + this.executor = new BackgroundExecutor(); + this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, this.minZoom, this.maxZoom); + + UndergroundTexture oldTexture = this.undergroundMapTexture; + UndergroundTexture newTexture = new UndergroundTexture(this, this.textureSize, this.linearTextureScalingEnabled); + this.undergroundMapTexture = newTexture; + if (oldTexture != null) { + this.undergroundMapTexture.close(); + } + } + + public void setCoordsMode(int mode) { + this.coordsMode = Math.min(Math.max(0, mode), 2); + } + + public int toggleCoords() { + this.setCoordsMode((this.coordsMode + 1) % 3); + return this.coordsMode; + } + + public void toggleUndergroundMode() { + this.undergroundMode = !this.undergroundMode; + this.miniMap.view.setUndergroundMode(this.undergroundMode); + } + + public void setServerDetails(String hostname, int port) { + this.serverName = hostname; + this.serverPort = port; + } + + //////////////////////////////// + // Initialization and Cleanup + //////////////////////////////// + + public void load() { + + if (this.ready) { + return; + } + + if ((this.mc.theWorld == null) || (this.mc.thePlayer == null)) { + MwUtil.log("Mw.load: world or player is null, cannot load yet"); + return; + } + + MwUtil.log("Mw.load: loading..."); + + IntegratedServer server = this.mc.getIntegratedServer(); + this.multiplayer = (server == null); + + this.loadConfig(); + + this.worldName = this.getWorldName(); + + // get world and image directories + File saveDir = this.saveDir; + if (this.saveDirOverride.length() > 0) { + File d = new File(this.saveDirOverride); + if (d.isDirectory()) { + saveDir = d; + } else { + MwUtil.log("error: no such directory %s", this.saveDirOverride); + } + } + + if (this.multiplayer) { + this.worldDir = new File(new File(saveDir, "mapwriter_mp_worlds"), this.worldName); + } else { + this.worldDir = new File(new File(saveDir, "mapwriter_sp_worlds"), this.worldName); + } + + this.loadWorldConfig(); + + // create directories + this.imageDir = new File(this.worldDir, "images"); + if (!this.imageDir.exists()) { + this.imageDir.mkdirs(); + } + if (!this.imageDir.isDirectory()) { + MwUtil.log("Mapwriter: ERROR: could not create images directory '%s'", this.imageDir.getPath()); + } + + this.tickCounter = 0; + this.onPlayerDeathAlreadyFired = false; + + //this.multiplayer = !this.mc.isIntegratedServerRunning(); + + // marker manager only depends on the config being loaded + this.markerManager = new MarkerManager(); + this.markerManager.load(this.worldConfig, catMarkers); + + this.playerTrail = new Trail(this, "player"); + + // executor does not depend on anything + this.executor = new BackgroundExecutor(); + + // mapTexture depends on config being loaded + this.mapTexture = new MapTexture(this.textureSize, this.linearTextureScalingEnabled); + this.undergroundMapTexture = new UndergroundTexture(this, this.textureSize, this.linearTextureScalingEnabled); + this.reloadBlockColours(); + // region manager depends on config, mapTexture, and block colours + this.regionManager = new RegionManager(this.worldDir, this.imageDir, this.blockColours, this.minZoom, this.maxZoom); + // overlay manager depends on mapTexture + this.miniMap = new MiniMap(this); + this.miniMap.view.setDimension(this.mc.thePlayer.dimension); + + this.chunkManager = new ChunkManager(this); + + this.ready = true; + + //if (!zoomLevelsExist) { + //printBoth("recreating zoom levels"); + //this.regionManager.recreateAllZoomLevels(); + //} + } + + public void close() { + + MwUtil.log("Mw.close: closing..."); + + if (this.ready) { + this.ready = false; + + this.chunkManager.close(); + this.chunkManager = null; + + // close all loaded regions, saving modified images. + // this will create extra tasks that need to be completed. + this.executor.addTask(new CloseRegionManagerTask(this.regionManager)); + this.regionManager = null; + + MwUtil.log("waiting for %d tasks to finish...", this.executor.tasksRemaining()); + if (this.executor.close()) { + MwUtil.log("error: timeout waiting for tasks to finish"); + } + MwUtil.log("done"); + + this.playerTrail.close(); + + this.markerManager.save(this.worldConfig, catMarkers); + this.markerManager.clear(); + + // close overlay + this.miniMap.close(); + this.miniMap = null; + + this.undergroundMapTexture.close(); + this.mapTexture.close(); + + this.saveWorldConfig(); + this.saveConfig(); + + this.tickCounter = 0; + + OverlaySlime.reset(); //Reset the state so the seed will be asked again when we log in + } + } + + //////////////////////////////// + // Event handlers + //////////////////////////////// + + public void onWorldLoad(World world) { + //MwUtil.log("onWorldLoad: %s, name %s, dimension %d", + // world, + // world.getWorldInfo().getWorldName(), + // world.provider.dimensionId); + + this.playerDimension = world.provider.dimensionId; + if (this.ready) { + this.addDimension(this.playerDimension); + this.miniMap.view.setDimension(this.playerDimension); + } + } + + public void onWorldUnload(World world) { + //MwUtil.log("onWorldUnload: %s, name %s, dimension %d", + // world, + // world.getWorldInfo().getWorldName(), + // world.provider.dimensionId); + } + + public void onTick() { + this.load(); + if (this.ready && (this.mc.thePlayer != null)) { + + this.updatePlayer(); + + if (this.undergroundMode && ((this.tickCounter % 30) == 0)) { + this.undergroundMapTexture.update(); + } + + // check if the game over screen is being displayed and if so + // (thanks to Chrixian for this method of checking when the player is dead) + if (this.mc.currentScreen instanceof GuiGameOver) { + if (!this.onPlayerDeathAlreadyFired) { + this.onPlayerDeath(); + this.onPlayerDeathAlreadyFired = true; + } + } else if (!(this.mc.currentScreen instanceof MwGui)) { + // if the player is not dead + this.onPlayerDeathAlreadyFired = false; + // if in game (no gui screen) center the minimap on the player and render it. + this.miniMap.view.setViewCentreScaled(this.playerX, this.playerZ, this.playerDimension); + this.miniMap.drawCurrentMap(); + } + + // process background tasks + int maxTasks = 50; + while (!this.executor.processTaskQueue() && (maxTasks > 0)) { + maxTasks--; + } + + this.chunkManager.onTick(); + + // update GL texture of mapTexture if updated + this.mapTexture.processTextureUpdates(); + + // let the renderEngine know we have changed the bound texture. + //this.mc.renderEngine.resetBoundTexture(); + + //if (this.tickCounter % 100 == 0) { + // MwUtil.log("tick %d", this.tickCounter); + //} + this.playerTrail.onTick(); + + this.tickCounter++; + } + } + + // add chunk to the set of loaded chunks + public void onChunkLoad(Chunk chunk) { + this.load(); + if ((chunk != null) && (chunk.worldObj instanceof net.minecraft.client.multiplayer.WorldClient)) { + if (this.ready) { + this.chunkManager.addChunk(chunk); + } else { + MwUtil.logInfo("missed chunk (%d, %d)", chunk.xPosition, chunk.zPosition); + } + } + } + + // remove chunk from the set of loaded chunks. + // convert to mwchunk and write chunk to region file if in multiplayer. + public void onChunkUnload(Chunk chunk) { + if (this.ready && (chunk != null) && (chunk.worldObj instanceof net.minecraft.client.multiplayer.WorldClient)) { + this.chunkManager.removeChunk(chunk); + } + } + + // from onTick when mc.currentScreen is an instance of GuiGameOver + // it's the only option to detect death client side + public void onPlayerDeath() { + if (this.ready && (this.maxDeathMarkers > 0)) { + this.updatePlayer(); + int deleteCount = this.markerManager.countMarkersInGroup("playerDeaths") - this.maxDeathMarkers + 1; + for (int i = 0; i < deleteCount; i++) { + // delete the first marker found in the group "playerDeaths". + // as new markers are only ever appended to the marker list this will delete the + // earliest death marker added. + this.markerManager.delMarker(null, "playerDeaths"); + } + this.markerManager.addMarker(MwUtil.getCurrentDateString(), "playerDeaths", this.playerXInt, this.playerYInt, this.playerZInt, this.playerDimension, 0xffff0000); + this.markerManager.setVisibleGroupName("playerDeaths"); + this.markerManager.update(); + } + } + + public void onKeyDown(KeyBinding kb) { + // make sure not in GUI element (e.g. chat box) + if ((this.mc.currentScreen == null) && (this.ready)) { + //Mw.log("client tick: %s key pressed", kb.keyDescription); + + if (kb == MwKeyHandler.keyMapMode) { + // map mode toggle + this.miniMap.nextOverlayMode(1); + + } else if (kb == MwKeyHandler.keyMapGui) { + // open map gui + this.mc.displayGuiScreen(new MwGui(this)); + + } else if (kb == MwKeyHandler.keyNewMarker) { + // open new marker dialog + String group = this.markerManager.getVisibleGroupName(); + if (group.equals("none")) { + group = "group"; + } + this.mc.displayGuiScreen( + new MwGuiMarkerDialog( + null, + this.markerManager, + "", + group, + this.playerXInt, + this.playerYInt, + this.playerZInt, + this.playerDimension + ) + ); + + } else if (kb == MwKeyHandler.keyNextGroup) { + // toggle marker mode + this.markerManager.nextGroup(); + this.markerManager.update(); + this.mc.thePlayer.addChatMessage(new ChatComponentText("group " + this.markerManager.getVisibleGroupName() + " selected")); + + } else if (kb == MwKeyHandler.keyTeleport) { + // set or remove marker + Marker marker = this.markerManager.getNearestMarkerInDirection( + this.playerXInt, + this.playerZInt, + this.playerHeading); + if (marker != null) { + this.teleportToMarker(marker); + } + } else if (kb == MwKeyHandler.keyZoomIn) { + // zoom in + this.miniMap.view.adjustZoomLevel(-1); + } else if (kb == MwKeyHandler.keyZoomOut) { + // zoom out + this.miniMap.view.adjustZoomLevel(1); + } else if (kb == MwKeyHandler.keyUndergroundMode) { + this.toggleUndergroundMode(); + } + } + } +} diff --git a/src/main/java/mapwriter/MwUtil.java b/src/main/java/mapwriter/MwUtil.java new file mode 100644 index 0000000..b6d66f8 --- /dev/null +++ b/src/main/java/mapwriter/MwUtil.java @@ -0,0 +1,121 @@ +package mapwriter; + +import java.io.File; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.regex.Pattern; + +import mapwriter.forge.MwForge; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.util.ChatComponentText; +import net.minecraft.world.chunk.Chunk; + +public class MwUtil { + + public final static Pattern patternInvalidChars = Pattern.compile("[^a-zA-Z0-9_]"); + + public static void logInfo(String s, Object...args) { + MwForge.logger.info(String.format(s, args)); + } + + public static void logWarning(String s, Object...args) { + MwForge.logger.warn(String.format(s, args)); + } + + public static void logError(String s, Object...args) { + MwForge.logger.error(String.format(s, args)); + } + + public static void debug(String s, Object...args) { + MwForge.logger.debug(String.format(s, args)); + } + + public static void log(String s, Object...args) { + logInfo(String.format(s, args)); + } + + public static String mungeString(String s) { + s = s.replace('.', '_'); + s = s.replace('-', '_'); + s = s.replace(' ', '_'); + s = s.replace('/', '_'); + s = s.replace('\\', '_'); + return patternInvalidChars.matcher(s).replaceAll(""); + } + + public static File getFreeFilename(File dir, String baseName, String ext) { + int i = 0; + File outputFile; + if (dir != null) { + outputFile = new File(dir, baseName + "." + ext); + } else { + outputFile = new File(baseName + "." + ext); + } + while (outputFile.exists() && (i < 1000)) { + if (dir != null) { + outputFile = new File(dir, baseName + "." + i + "." + ext); + } else { + outputFile = new File(baseName + "." + i + "." + ext); + } + i++; + } + return (i < 1000) ? outputFile : null; + } + + public static void printBoth(String msg) { + EntityClientPlayerMP thePlayer = Minecraft.getMinecraft().thePlayer; + if (thePlayer != null) { + thePlayer.addChatMessage(new ChatComponentText(msg)); + } + MwUtil.log("%s", msg); + } + + public static File getDimensionDir(File worldDir, int dimension) { + File dimDir; + if (dimension != 0) { + dimDir = new File(worldDir, "DIM" + dimension); + } else { + dimDir = worldDir; + } + return dimDir; + } + + public static IntBuffer allocateDirectIntBuffer(int size) { + return ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer(); + } + + // algorithm from http://graphics.stanford.edu/~seander/bithacks.html (Sean Anderson) + // works by making sure all bits to the right of the highest set bit are 1, then + // adding 1 to get the answer. + public static int nextHighestPowerOf2(int v) { + // decrement by 1 (to handle cases where v is already a power of two) + v--; + + // set all bits to the right of the uppermost set bit. + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + // v |= v >> 32; // uncomment for 64 bit input values + + // add 1 to get the power of two result + return v + 1; + } + + public static String getCurrentDateString() { + DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmm"); + return dateFormat.format(new Date()); + } + + public static int distToChunkSq(int x, int z, Chunk chunk) { + int dx = (chunk.xPosition << 4) + 8 - x; + int dz = (chunk.zPosition << 4) + 8 - z; + return (dx * dx) + (dz * dz); + } +} diff --git a/src/main/java/mapwriter/Render.java b/src/main/java/mapwriter/Render.java new file mode 100644 index 0000000..433612a --- /dev/null +++ b/src/main/java/mapwriter/Render.java @@ -0,0 +1,380 @@ +package mapwriter; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.Tessellator; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +/* +MwRender contains most of the code for drawing the overlay. +This includes: + - loading textures from images + - saving textures to images + - allocating and setting up GL textures + - drawing coloured and textured quads (using minecraft Tesselator class) + +*/ + +public class Render { + public static double zDepth = 0.0D; + public static final double circleSteps = 30.0; + + public static void setColourWithAlphaPercent(int colour, int alphaPercent) { + setColour(((((alphaPercent * 0xff) / 100) & 0xff) << 24) | (colour & 0xffffff)); + } + + public static void setColour(int colour) { + GL11.glColor4f( + (float) ((colour >> 16) & 0xff) / 255.0f, + (float) ((colour >> 8) & 0xff) / 255.0f, + (float) ((colour) & 0xff) / 255.0f, + (float) ((colour >> 24) & 0xff) / 255.0f); + } + + public static void resetColour() { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } + + public static int multiplyColours(int c1, int c2) { + float c1A = (float) ((c1 >> 24) & 0xff); + float c1R = (float) ((c1 >> 16) & 0xff); + float c1G = (float) ((c1 >> 8) & 0xff); + float c1B = (float) ((c1 >> 0) & 0xff); + float c2A = (float) ((c2 >> 24) & 0xff); + float c2R = (float) ((c2 >> 16) & 0xff); + float c2G = (float) ((c2 >> 8) & 0xff); + float c2B = (float) ((c2 >> 0) & 0xff); + int r = (int) (c1R * c2R / 255.0f) & 0xff; + int g = (int) (c1G * c2G / 255.0f) & 0xff; + int b = (int) (c1B * c2B / 255.0f) & 0xff; + int a = (int) (c1A * c2A / 255.0f) & 0xff; + return (a << 24) | (r << 16) | (g << 8) | b; + } + + public static int getAverageOfPixelQuad(int[] pixels, int offset, int scanSize) { + int p00 = pixels[offset]; + int p01 = pixels[offset + 1]; + int p10 = pixels[offset + scanSize]; + int p11 = pixels[offset + scanSize + 1]; + + // ignore alpha channel + int r = ((p00 >> 16) & 0xff) + ((p01 >> 16) & 0xff) + ((p10 >> 16) & 0xff) + ((p11 >> 16) & 0xff); + r >>= 2; + int g = ((p00 >> 8) & 0xff) + ((p01 >> 8) & 0xff) + ((p10 >> 8) & 0xff) + ((p11 >> 8) & 0xff); + g >>= 2; + int b = (p00 & 0xff) + (p01 & 0xff) + (p10 & 0xff) + (p11 & 0xff); + b >>= 2; + return 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); + } + + public static int getAverageColourOfArray(int[] pixels) { + int count = 0; + double totalA = 0.0; + double totalR = 0.0; + double totalG = 0.0; + double totalB = 0.0; + for (int pixel : pixels) { + double a = (double) ((pixel >> 24) & 0xff); + double r = (double) ((pixel >> 16) & 0xff); + double g = (double) ((pixel >> 8) & 0xff); + double b = (double) ((pixel >> 0) & 0xff); + + totalA += a; + totalR += r * a / 255.0; + totalG += g * a / 255.0; + totalB += b * a / 255.0; + + count++; + } + + totalR = totalR * 255.0 / totalA; + totalG = totalG * 255.0 / totalA; + totalB = totalB * 255.0 / totalA; + totalA = totalA / ((double) count); + + return ((((int) (totalA)) & 0xff) << 24) | + ((((int) (totalR)) & 0xff) << 16) | + ((((int) (totalG)) & 0xff) << 8) | + ((((int) (totalB)) & 0xff)); + } + + public static int adjustPixelBrightness(int colour, int brightness) { + int r = ((colour >> 16) & 0xff); + int g = ((colour >> 8) & 0xff); + int b = ((colour >> 0) & 0xff); + r = Math.min(Math.max(0, r + brightness), 0xff); + g = Math.min(Math.max(0, g + brightness), 0xff); + b = Math.min(Math.max(0, b + brightness), 0xff); + return (colour & 0xff000000) | (r << 16) | (g << 8) | (b); + } + + public static int getTextureWidth() { + return GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); + } + + public static int getTextureHeight() { + return GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); + } + + public static int getBoundTextureId() { + return GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + } + + public static void printBoundTextureInfo(int texture) { + int w = getTextureWidth(); + int h = getTextureHeight(); + int depth = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL12.GL_TEXTURE_DEPTH); + int format = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_INTERNAL_FORMAT); + MwUtil.log("texture %d parameters: width=%d, height=%d, depth=%d, format=%08x", texture, w, h, depth, format); + } + + public static int getMaxTextureSize() { + return GL11.glGetInteger(GL11.GL_MAX_TEXTURE_SIZE); + } + + /* + Drawing Methods + + Note that EntityRenderer.setupOverlayRendering must be called before drawing for the scene + to appear correctly on the overlay. + If these functions are called from the hookUpdateCameraAndRender method of Mw this + will have already been done. + */ + + // draw rectangle with texture stretched to fill the shape + public static void drawTexturedRect(double x, double y, double w, double h) { + drawTexturedRect(x, y, w, h, 0.0D, 0.0D, 1.0D, 1.0D); + } + + // draw rectangle with texture UV coordinates specified (so only part of the texture fills the rectangle). + public static void drawTexturedRect(double x, double y, double w, double h, double u1, double v1, double u2, double v2) { + try { + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Tessellator tes = Tessellator.instance; + tes.startDrawingQuads(); + tes.addVertexWithUV(x + w, y, zDepth, u2, v1); + tes.addVertexWithUV(x, y, zDepth, u1, v1); + tes.addVertexWithUV(x, y + h, zDepth, u1, v2); + tes.addVertexWithUV(x + w, y + h, zDepth, u2, v2); + tes.draw(); + GL11.glDisable(GL11.GL_BLEND); + } catch (NullPointerException e) { + MwUtil.log("MwRender.drawTexturedRect: null pointer exception"); + } + } + + public static void drawArrow(double x, double y, double angle, double length) { + // angle the back corners will be drawn at relative to the pointing angle + double arrowBackAngle = 0.75D * Math.PI; + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Tessellator tes = Tessellator.instance; + tes.startDrawing(GL11.GL_TRIANGLE_FAN); + tes.addVertex(x + (length * Math.cos(angle)), y + (length * Math.sin(angle)), zDepth); + tes.addVertex(x + (length * 0.5D * Math.cos(angle - arrowBackAngle)), y + (length * 0.5D * Math.sin(angle - arrowBackAngle)), zDepth); + tes.addVertex(x + (length * 0.3D * Math.cos(angle + Math.PI)), y + (length * 0.3D * Math.sin(angle + Math.PI)), zDepth); + tes.addVertex(x + (length * 0.5D * Math.cos(angle + arrowBackAngle)), y + (length * 0.5D * Math.sin(angle + arrowBackAngle)), zDepth); + tes.draw(); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_BLEND); + } + + public static void drawTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Tessellator tes = Tessellator.instance; + tes.startDrawing(GL11.GL_TRIANGLES); + tes.addVertex(x1, y1, zDepth); + tes.addVertex(x2, y2, zDepth); + tes.addVertex(x3, y3, zDepth); + tes.draw(); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_BLEND); + } + + public static void drawRect(double x, double y, double w, double h) { + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Tessellator tes = Tessellator.instance; + tes.startDrawingQuads(); + tes.addVertex(x + w, y, zDepth); + tes.addVertex(x, y, zDepth); + tes.addVertex(x, y + h, zDepth); + tes.addVertex(x + w, y + h, zDepth); + tes.draw(); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_BLEND); + } + + public static void drawCircle(double x, double y, double r) { + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Tessellator tes = Tessellator.instance; + tes.startDrawing(GL11.GL_TRIANGLE_FAN); + tes.addVertex(x, y, zDepth); + // for some the circle is only drawn if theta is decreasing rather than ascending + double end = Math.PI * 2.0; + double incr = end / circleSteps; + for (double theta = -incr; theta < end; theta += incr) { + tes.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); + } + tes.draw(); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_BLEND); + } + + public static void drawCircleBorder(double x, double y, double r, double width) { + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Tessellator tes = Tessellator.instance; + tes.startDrawing(GL11.GL_TRIANGLE_STRIP); + // for some the circle is only drawn if theta is decreasing rather than ascending + double end = Math.PI * 2.0; + double incr = end / circleSteps; + double r2 = r + width; + for (double theta = -incr; theta < end; theta += incr) { + tes.addVertex(x + (r * Math.cos(-theta)), y + (r * Math.sin(-theta)), zDepth); + tes.addVertex(x + (r2 * Math.cos(-theta)), y + (r2 * Math.sin(-theta)), zDepth); + } + tes.draw(); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_BLEND); + } + + public static void drawRectBorder(double x, double y, double w, double h, double bw) { + // top border + Render.drawRect(x - bw, y - bw, w + bw + bw, bw); + // bottom border + Render.drawRect(x - bw, y + h, w + bw + bw, bw); + // left border + Render.drawRect(x - bw, y, bw, h); + // right border + Render.drawRect(x + w, y, bw, h); + } + + public static void drawString(int x, int y, int colour, String formatString, Object...args) { + Minecraft mc = Minecraft.getMinecraft(); + //mc.renderEngine.resetBoundTexture(); + FontRenderer fr = mc.fontRenderer; + String s = String.format(formatString, args); + fr.drawStringWithShadow(s, x, y, colour); + } + + public static void drawCentredString(int x, int y, int colour, String formatString, Object...args) { + Minecraft mc = Minecraft.getMinecraft(); + //mc.renderEngine.resetBoundTexture(); + FontRenderer fr = mc.fontRenderer; + String s = String.format(formatString, args); + int w = fr.getStringWidth(s); + fr.drawStringWithShadow(s, x - (w / 2), y, colour); + } + + public static void setCircularStencil(double x, double y, double r) { + GL11.glEnable(GL11.GL_DEPTH_TEST); + // disable drawing to the color buffer. + // circle will only be drawn to depth buffer. + GL11.glColorMask(false, false, false, false); + // enable writing to depth buffer + GL11.glDepthMask(true); + + // Clearing the depth buffer causes problems with shader mods. + // I guess we just have to hope that the rest of the depth buffer + // contains z values greater than 2000 at this stage in the frame + // render. + // It would be much easier to use the stencil buffer instead, but it is + // not specifically requested in the Minecraft LWJGL display setup code. + // So the stencil buffer is only available on GL implementations that + // set it up by default. + + // clear depth buffer to z = 3000.0 + //GL11.glClearDepth(3000.0); + //GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); + + // always write to depth buffer + GL11.glDepthFunc(GL11.GL_ALWAYS); + + // draw stencil pattern (filled circle at z = 1000.0) + Render.setColour(0xffffffff); + Render.zDepth = 1000.0; + Render.drawCircle(x, y, r); + Render.zDepth = 0.0; + + // re-enable drawing to colour buffer + GL11.glColorMask(true, true, true, true); + // disable drawing to depth buffer + GL11.glDepthMask(false); + // only draw pixels with z values that are greater + // than the value in the depth buffer. + // The overlay is drawn at 2000 so this will pass inside + // the circle (2000 > 1000) but not outside (2000 <= 3000). + GL11.glDepthFunc(GL11.GL_GREATER); + } + + public static void disableStencil() { + GL11.glDepthMask(true); + GL11.glDepthFunc(GL11.GL_LEQUAL); + GL11.glDisable(GL11.GL_DEPTH_TEST); + } + + // A better implementation of a circular stencil using the stencil buffer + // rather than the depth buffer can be found below. It works only on GL + // implementations that attach a stencil buffer by default (e.g. Intel, but + // not on Nvidia). + // + // To fix this we would need to change the display create line in + // 'Minecraft.java' file from: + // Display.create((new PixelFormat()).withDepthBits(24)); + // to: + // Display.create((new PixelFormat()).withDepthBits(24).withStencilBits(8)); + // + // Then we could use the stencil buffer and the the circular map would have + // far less problems. + // + // I suppose it would also be possible to detect the number of stencil bits + // available at runtime using GL11.glGetInteger(GL11.GL_STENCIL_BITS) and + // only use the depth buffer stencil algorithm if it returns 0. But this + // doesn't solve the problem of the stencil buffer not being initialized by + // default on some systems. + + /*public static void setCircularStencil(double x, double y, double r) { + GL11.glEnable(GL11.GL_STENCIL_TEST); + // disable drawing to the color and depth buffers. + // circle will only be drawn to stencil buffer. + GL11.glColorMask(false, false, false, false); + GL11.glDepthMask(false); + // set up stencil func and op so that a 1 is always written to the stencil buffer + // whenever a pixel is drawn. + GL11.glStencilFunc(GL11.GL_NEVER, 1, 0x01); + // replace stencil buffer value with 1 whenever stencil test fails. + // keep stencil buffer value otherwise. + GL11.glStencilOp(GL11.GL_REPLACE, GL11.GL_KEEP, GL11.GL_KEEP); + // enable writing to 8 bits of the stencil buffer + GL11.glStencilMask(0x01); + // clear stencil buffer, with mask 0xff + GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT); + // draw stencil pattern + Render.setColour(0xffffffff); + Render.drawCircle(x, y, r); + + // re-enable drawing to colour and depth buffers + GL11.glColorMask(true, true, true, true); + // probably shouldn't enable? -> GL11.glDepthMask(true); + // disable writing to stencil buffer + GL11.glStencilMask(0x00); + // draw only when stencil buffer value == 1 (inside circle) + GL11.glStencilFunc(GL11.GL_EQUAL, 1, 0x01); + } + + public static void disableStencil() { + GL11.glDisable(GL11.GL_STENCIL_TEST); + }*/ +} \ No newline at end of file diff --git a/src/main/java/mapwriter/Texture.java b/src/main/java/mapwriter/Texture.java new file mode 100644 index 0000000..b4944b4 --- /dev/null +++ b/src/main/java/mapwriter/Texture.java @@ -0,0 +1,155 @@ +package mapwriter; + +import java.nio.IntBuffer; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +public class Texture { + + private int id; + public final int w; + public final int h; + private final IntBuffer pixelBuf; + + // allocate new texture and fill from IntBuffer + public Texture(int w, int h, int fillColour, int minFilter, int maxFilter, int textureWrap) { + this.id = GL11.glGenTextures(); + this.w = w; + this.h = h; + this.pixelBuf = MwUtil.allocateDirectIntBuffer(w * h); + this.fillRect(0, 0, w, h, fillColour); + this.pixelBuf.position(0); + this.bind(); + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, w, h, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); + this.setTexParameters(minFilter, maxFilter, textureWrap); + } + + public Texture(int w, int h, int fillColour) { + this(w, h, fillColour, GL11.GL_LINEAR, GL11.GL_NEAREST, GL12.GL_CLAMP_TO_EDGE); + } + + // create from existing texture + public Texture(int id) { + this.id = id; + this.bind(); + this.w = Render.getTextureWidth(); + this.h = Render.getTextureHeight(); + this.pixelBuf = MwUtil.allocateDirectIntBuffer(this.w * this.h); + this.getPixelsFromExistingTexture(); + MwUtil.log("created new MwTexture from GL texture id %d (%dx%d) (%d pixels)", this.id, this.w, this.h, this.pixelBuf.limit()); + } + + // free up the resources used by the GL texture + public synchronized void close() { + if (this.id != 0) { + try { + GL11.glDeleteTextures(this.id); + } catch (NullPointerException e) { + MwUtil.log("MwTexture.close: null pointer exception (texture %d)", this.id); + } + this.id = 0; + } + } + + public void setPixelBufPosition(int i) { + this.pixelBuf.position(i); + } + + public void pixelBufPut(int pixel) { + this.pixelBuf.put(pixel); + } + + public synchronized void fillRect(int x, int y, int w, int h, int colour) { + int offset = (y * this.w) + x; + for (int j = 0; j < h; j++) { + this.pixelBuf.position(offset + (j * this.w)); + for (int i = 0; i < w; i++) { + this.pixelBuf.put(colour); + } + } + } + + // Copy a rectangular sub-region of dimensions 'w' x 'h' from the pixel buffer to the array 'pixels'. + public synchronized void getRGB(int x, int y, int w, int h, int[] pixels, int offset, int scanSize) { + int bufOffset = (y * this.w) + x; + for (int i = 0; i < h; i++) { + this.pixelBuf.position(bufOffset + (i * this.w)); + this.pixelBuf.get(pixels, offset + (i * scanSize), w); + } + } + + // Copy a rectangular sub-region of dimensions 'w' x 'h' from the array 'pixels' to the pixel buffer. + public synchronized void setRGB(int x, int y, int w, int h, int[] pixels, int offset, int scanSize) { + int bufOffset = (y * this.w) + x; + for (int i = 0; i < h; i++) { + this.pixelBuf.position(bufOffset + (i * this.w)); + this.pixelBuf.put(pixels, offset + (i * scanSize), w); + } + } + + public synchronized void setRGB(int x, int y, int colour) { + this.pixelBuf.put((y * this.w) + x, colour); + } + + public synchronized int getRGB(int x, int y) { + return this.pixelBuf.get((y * this.w) + x); + } + + public void bind() { + GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.id); + } + + // set texture scaling and wrapping parameters + public void setTexParameters(int minFilter, int maxFilter, int textureWrap) { + this.bind(); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, textureWrap); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, textureWrap); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, minFilter); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, maxFilter); + } + + public void setLinearScaling(boolean enabled) { + this.bind(); + if (enabled) { + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); + } else { + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + } + } + + // update texture from pixels in pixelBuf + public synchronized void updateTextureArea(int x, int y, int w, int h) { + try { + this.bind(); + GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, this.w); + this.pixelBuf.position((y * this.w) + x); + GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, x, y, w, h, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); + GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 0); + } catch (NullPointerException e) { + MwUtil.log("MwTexture.updatePixels: null pointer exception (texture %d)", this.id); + } + } + + public synchronized void updateTexture() { + this.bind(); + this.pixelBuf.position(0); + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, this.w, this.h, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); + } + + // copy pixels from GL texture to pixelBuf + private synchronized void getPixelsFromExistingTexture() { + try { + this.bind(); + this.pixelBuf.clear(); + GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, this.pixelBuf); + // getTexImage does not seem to advance the buffer position, so flip does not work here + // this.pixelBuf.flip() + this.pixelBuf.limit(this.w * this.h); + } catch (NullPointerException e) { + MwUtil.log("MwTexture.getPixels: null pointer exception (texture %d)", this.id); + } + } +} diff --git a/src/main/java/mapwriter/api/IMwChunkOverlay.java b/src/main/java/mapwriter/api/IMwChunkOverlay.java new file mode 100644 index 0000000..4fa51d8 --- /dev/null +++ b/src/main/java/mapwriter/api/IMwChunkOverlay.java @@ -0,0 +1,12 @@ +package mapwriter.api; + +import java.awt.Point; + +public interface IMwChunkOverlay { + public Point getCoordinates(); + public int getColor(); + public float getFilling(); + public boolean hasBorder(); + public float getBorderWidth(); + public int getBorderColor(); +} diff --git a/src/main/java/mapwriter/api/IMwDataProvider.java b/src/main/java/mapwriter/api/IMwDataProvider.java new file mode 100644 index 0000000..5ff9505 --- /dev/null +++ b/src/main/java/mapwriter/api/IMwDataProvider.java @@ -0,0 +1,31 @@ +package mapwriter.api; + +import java.util.ArrayList; + +import mapwriter.map.MapView; +import mapwriter.map.mapmode.MapMode; + +public interface IMwDataProvider { + public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ); + + //Returns what should be added to the status bar by the addon. + public String getStatusString(int dim, int bX, int bY, int bZ); + + //Call back for middle click. + public void onMiddleClick(int dim, int bX, int bZ, MapView mapview); + + //Callback for dimension change on the map + public void onDimensionChanged(int dimension, MapView mapview); + + public void onMapCenterChanged(double vX, double vZ, MapView mapview); + + public void onZoomChanged(int level, MapView mapview); + + public void onOverlayActivated(MapView mapview); + + public void onOverlayDeactivated(MapView mapview); + + public void onDraw(MapView mapview, MapMode mapmode); + + public boolean onMouseInput(MapView mapview, MapMode mapmode); +} diff --git a/src/main/java/mapwriter/api/MwAPI.java b/src/main/java/mapwriter/api/MwAPI.java new file mode 100644 index 0000000..01efc6d --- /dev/null +++ b/src/main/java/mapwriter/api/MwAPI.java @@ -0,0 +1,85 @@ +package mapwriter.api; + +import java.util.ArrayList; +import java.util.Collection; + +import com.google.common.collect.HashBiMap; + +public class MwAPI { + + private static HashBiMap dataProviders = HashBiMap.create(); + private static IMwDataProvider currentProvider = null; + private static ArrayList providerKeys = new ArrayList(); + + public static void registerDataProvider(String name, IMwDataProvider handler){ + dataProviders.put(name, handler); + providerKeys.add(name); + } + + public static Collection getDataProviders(){ + return dataProviders.values(); + } + + // Returns the data provider based on its name // + public static IMwDataProvider getDataProvider(String name){ + return dataProviders.get(name); + } + + // Returns the name based on the data provider // + public static String getProviderName(IMwDataProvider provider){ + return dataProviders.inverse().get(provider); + } + + public static IMwDataProvider getCurrentDataProvider(){ + return currentProvider; + } + + public static String getCurrentProviderName(){ + if (currentProvider != null) + return getProviderName(currentProvider); + else + return "None"; + } + + public static IMwDataProvider setCurrentDataProvider(String name){ + currentProvider = dataProviders.get(name); + return currentProvider; + } + + public static IMwDataProvider setCurrentDataProvider(IMwDataProvider provider){ + currentProvider = provider; + return currentProvider; + } + + public static IMwDataProvider setNextProvider(){ + if (currentProvider != null){ + int index = providerKeys.indexOf(getCurrentProviderName()); + if (index + 1 >= providerKeys.size()){ + currentProvider = null; + } else { + String nextKey = providerKeys.get(index + 1); + currentProvider = getDataProvider(nextKey); + } + } else { + if (providerKeys.size() > 0) + currentProvider = getDataProvider(providerKeys.get(0)); + } + return currentProvider; + } + + public static IMwDataProvider setPrevProvider(){ + if (currentProvider != null){ + int index = providerKeys.indexOf(getCurrentProviderName()); + if (index - 1 < 0){ + currentProvider = null; + } else { + String prevKey = providerKeys.get(index - 1); + currentProvider = getDataProvider(prevKey); + } + } else { + if (providerKeys.size() > 0) + currentProvider = getDataProvider(providerKeys.get(providerKeys.size() - 1)); + } + return currentProvider; + } +} diff --git a/src/main/java/mapwriter/forge/ClientProxy.java b/src/main/java/mapwriter/forge/ClientProxy.java new file mode 100644 index 0000000..2ffdb17 --- /dev/null +++ b/src/main/java/mapwriter/forge/ClientProxy.java @@ -0,0 +1,37 @@ +package mapwriter.forge; + +import java.io.File; + +import mapwriter.Mw; +import mapwriter.api.MwAPI; +import mapwriter.overlay.OverlayGrid; +import mapwriter.overlay.OverlaySlime; +import net.minecraft.client.Minecraft; +import net.minecraftforge.common.MinecraftForge; +import cpw.mods.fml.common.FMLCommonHandler; + +public class ClientProxy extends CommonProxy { + + private MwConfig config; + + public void preInit(File configFile) { + this.config = new MwConfig(configFile); + } + + public void load() { + Mw mw = new Mw(this.config); + MinecraftForge.EVENT_BUS.register(new EventHandler(mw)); + FMLCommonHandler.instance().bus().register(new MwKeyHandler()); + // temporary workaround for user defined key bindings not being loaded + // at game start. see https://github.com/MinecraftForge/FML/issues/378 + // for more info. + Minecraft.getMinecraft().gameSettings.loadOptions(); + } + + public void postInit() { + MwAPI.registerDataProvider("Slime", new OverlaySlime()); + MwAPI.registerDataProvider("Grid", new OverlayGrid()); + //MwAPI.registerDataProvider("Checker", new OverlayChecker()); + //MwAPI.setCurrentDataProvider("Slime"); + } +} diff --git a/src/main/java/mapwriter/forge/CommonProxy.java b/src/main/java/mapwriter/forge/CommonProxy.java new file mode 100644 index 0000000..6ef4209 --- /dev/null +++ b/src/main/java/mapwriter/forge/CommonProxy.java @@ -0,0 +1,9 @@ +package mapwriter.forge; + +import java.io.File; + +public class CommonProxy { + public void preInit(File configFile) {} + public void load() {} + public void postInit() {} +} diff --git a/src/main/java/mapwriter/forge/EventHandler.java b/src/main/java/mapwriter/forge/EventHandler.java new file mode 100644 index 0000000..69e38c3 --- /dev/null +++ b/src/main/java/mapwriter/forge/EventHandler.java @@ -0,0 +1,70 @@ +package mapwriter.forge; + +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import mapwriter.Mw; +import mapwriter.overlay.OverlaySlime; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.ChatComponentTranslation; +import net.minecraftforge.client.event.ClientChatReceivedEvent; +import net.minecraftforge.event.world.ChunkEvent; +import net.minecraftforge.event.world.WorldEvent; + +public class EventHandler { + + Mw mw; + + public EventHandler(Mw mw) { + this.mw = mw; + } + + @SubscribeEvent + public void eventChunkLoad(ChunkEvent.Load event){ + if(event.world.isRemote){ + this.mw.onChunkLoad(event.getChunk()); + } + } + + @SubscribeEvent + public void eventChunkUnload(ChunkEvent.Unload event){ + if(event.world.isRemote){ + this.mw.onChunkUnload(event.getChunk()); + } + } + + @SubscribeEvent + public void eventWorldLoad(WorldEvent.Load event){ + if(event.world.isRemote){ + this.mw.onWorldLoad(event.world); + } + } + + @SubscribeEvent + public void eventWorldUnload(WorldEvent.Unload event){ + if(event.world.isRemote){ + this.mw.onWorldUnload(event.world); + } + } + + @SubscribeEvent + public void onClientChat(ClientChatReceivedEvent event){ + if(OverlaySlime.seedFound || !OverlaySlime.seedAsked) return; + try{ //I don't want to crash the game when we derp up in here + if(event.message instanceof ChatComponentTranslation){ + ChatComponentTranslation component = (ChatComponentTranslation) event.message; + if(component.getKey().equals("commands.seed.success")){ + OverlaySlime.setSeed((Long) component.getFormatArgs()[0]); + event.setCanceled(true); //Don't let the player see this seed message, They didn't do /seed, we did + } + }else if(event.message instanceof ChatComponentText){ + ChatComponentText component = (ChatComponentText) event.message; + String msg = component.getUnformattedText(); + if(msg.startsWith("Seed: ")){ //Because bukkit... + OverlaySlime.setSeed(Long.parseLong(msg.substring(6))); + event.setCanceled(true); //Don't let the player see this seed message, They didn't do /seed, we did + } + } + }catch(Exception e){ + //e.printStackTrace(); + } + } +} diff --git a/src/main/java/mapwriter/forge/MwConfig.java b/src/main/java/mapwriter/forge/MwConfig.java new file mode 100644 index 0000000..35673db --- /dev/null +++ b/src/main/java/mapwriter/forge/MwConfig.java @@ -0,0 +1,135 @@ +package mapwriter.forge; + +import java.io.File; +import java.util.List; + +import mapwriter.MwUtil; +import net.minecraftforge.common.config.Configuration; + +public class MwConfig extends Configuration { + + public MwConfig(File file) { + super(file, true); + } + + public boolean getOrSetBoolean(String category, String key, boolean defaultValue) { + return this.get(category, key, defaultValue ? 1 : 0).getInt() != 0; + } + + public void setBoolean(String category, String key, boolean value) { + this.get(category, key, value).set(value ? 1 : 0); + } + + public int getOrSetInt(String category, String key, int defaultValue, int minValue, int maxValue) { + int value = this.get(category, key, defaultValue).getInt(); + return Math.min(Math.max(minValue, value), maxValue); + } + + public void setInt(String category, String key, int value) { + this.get(category, key, value).set(value); + } + + public long getColour(String category, String key) { + long value = -1; + if (this.hasKey(category, key)) { + try { + String valueString = this.get(category, key, "").getString(); + if (valueString.length() > 0) { + value = Long.parseLong(valueString, 16); + value &= 0xffffffffL; + } + } catch (NumberFormatException e) { + MwUtil.log("error: could not read colour from config file %s:%s", category, key); + value = -1; + } + } + return value; + } + + public int getColour(String category, String key, int value) { + long valueLong = this.getColour(category, key); + if (valueLong >= 0L) { + value = (int) (valueLong & 0xffffffffL); + } + return value; + } + + public int getOrSetColour(String category, String key, int value) { + long valueLong = this.getColour(category, key); + if (valueLong >= 0L) { + value = (int) (valueLong & 0xffffffffL); + } else { + this.setColour(category, key, value); + } + return value; + } + + public void setColour(String category, String key, int n) { + this.get(category, key, "00000000").set(String.format("%08x", n)); + } + + public void setColour(String category, String key, int n, String comment) { + this.get(category, key, "00000000", comment).set(String.format("%08x", n)); + } + + public String getSingleWord(String category, String key) { + String value = ""; + if (this.hasKey(category, key)) { + value = this.get(category, key, value).getString().trim(); + int firstSpace = value.indexOf(' '); + if (firstSpace >= 0) { + value = value.substring(0, firstSpace); + } + } + return value; + } + + public void setSingleWord(String category, String key, String value, String comment) { + if ((comment != null) && (comment.length() > 0)) { + value = value + " # " + comment; + } + this.get(category, key, value).set(value); + } + + public void getIntList(String category, String key, List list) { + // convert List of integers to integer array to pass as default value + int size = list.size(); + int[] array = new int[size]; + for (int i = 0; i < size; i++) { + array[i] = list.get(i); + } + + // get integer array from config file + int[] arrayFromConfig = null; + try { + arrayFromConfig = this.get(category, key, array).getIntList(); + } catch (Exception e) { + e.printStackTrace(); + arrayFromConfig = null; + } + if (arrayFromConfig != null) { + array = arrayFromConfig; + } + + // convert integer array back to List of integers + list.clear(); + for (int i = 0; i < array.length; i++) { + list.add(array[i]); + } + } + + public void setIntList(String category, String key, List list) { + // convert List of integers to integer array + int size = list.size(); + String[] array = new String[size]; + for (int i = 0; i < size; i++) { + array[i] = list.get(i).toString(); + } + // write integer array to config file + try { + this.get(category, key, array).set(array); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/mapwriter/forge/MwForge.java b/src/main/java/mapwriter/forge/MwForge.java new file mode 100644 index 0000000..5763409 --- /dev/null +++ b/src/main/java/mapwriter/forge/MwForge.java @@ -0,0 +1,77 @@ +package mapwriter.forge; + +import java.net.InetSocketAddress; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import mapwriter.Mw; +import net.minecraft.client.Minecraft; +import net.minecraftforge.client.event.RenderGameOverlayEvent; +import net.minecraftforge.common.MinecraftForge; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.Mod; +import cpw.mods.fml.common.Mod.EventHandler; +import cpw.mods.fml.common.Mod.Instance; +import cpw.mods.fml.common.SidedProxy; +import cpw.mods.fml.common.event.FMLInitializationEvent; +import cpw.mods.fml.common.event.FMLPostInitializationEvent; +import cpw.mods.fml.common.event.FMLPreInitializationEvent; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.TickEvent; +import cpw.mods.fml.common.network.FMLNetworkEvent; + +@Mod(modid="MapWriter", name="MapWriter", version="2.1.1") +public class MwForge { + + @Instance("MapWriter") + public static MwForge instance; + + @SidedProxy(clientSide="mapwriter.forge.ClientProxy", serverSide="mapwriter.forge.CommonProxy") + public static CommonProxy proxy; + + public static Logger logger = LogManager.getLogger("MapWriter"); + + @EventHandler + public void preInit(FMLPreInitializationEvent event) { + FMLCommonHandler.instance().bus().register(this); + MinecraftForge.EVENT_BUS.register(this); + proxy.preInit(event.getSuggestedConfigurationFile()); + } + + @EventHandler + public void load(FMLInitializationEvent event) { + proxy.load(); + } + + @EventHandler + public void postInit(FMLPostInitializationEvent event) { + proxy.postInit(); + } + + @SubscribeEvent + public void renderMap(RenderGameOverlayEvent.Post event){ + if(event.type == RenderGameOverlayEvent.ElementType.ALL){ + Mw.instance.onTick(); + } + } + + @SubscribeEvent + public void onConnected(FMLNetworkEvent.ClientConnectedToServerEvent event){ + if (!event.isLocal) { + InetSocketAddress address = (InetSocketAddress) event.manager.getSocketAddress(); + Mw.instance.setServerDetails(address.getHostName(), address.getPort()); + } + } + + @SubscribeEvent + public void onTick(TickEvent.ClientTickEvent event){ + if (event.phase == TickEvent.Phase.START){ + // run the cleanup code when Mw is loaded and the player becomes null. + // a bit hacky, but simpler than checking if the connection has closed. + if ((Mw.instance.ready) && (Minecraft.getMinecraft().thePlayer == null)) { + Mw.instance.close(); + } + } + } +} diff --git a/src/main/java/mapwriter/forge/MwKeyHandler.java b/src/main/java/mapwriter/forge/MwKeyHandler.java new file mode 100644 index 0000000..32e3ca2 --- /dev/null +++ b/src/main/java/mapwriter/forge/MwKeyHandler.java @@ -0,0 +1,70 @@ +package mapwriter.forge; + +import mapwriter.Mw; +import net.minecraft.client.settings.KeyBinding; + +import org.lwjgl.input.Keyboard; + +import cpw.mods.fml.client.registry.ClientRegistry; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.InputEvent; + +public class MwKeyHandler { + + public static KeyBinding keyMapGui = new KeyBinding("key.mw_open_gui", Keyboard.KEY_M, "Mapwriter"); + public static KeyBinding keyNewMarker = new KeyBinding("key.mw_new_marker", Keyboard.KEY_INSERT, "Mapwriter"); + public static KeyBinding keyMapMode = new KeyBinding("key.mw_next_map_mode", Keyboard.KEY_N, "Mapwriter"); + public static KeyBinding keyNextGroup = new KeyBinding("key.mw_next_marker_group", Keyboard.KEY_COMMA, "Mapwriter"); + public static KeyBinding keyTeleport = new KeyBinding("key.mw_teleport", Keyboard.KEY_PERIOD, "Mapwriter"); + public static KeyBinding keyZoomIn = new KeyBinding("key.mw_zoom_in", Keyboard.KEY_PRIOR, "Mapwriter"); + public static KeyBinding keyZoomOut = new KeyBinding("key.mw_zoom_out", Keyboard.KEY_NEXT, "Mapwriter"); + public static KeyBinding keyUndergroundMode = new KeyBinding("key.mw_underground_mode", Keyboard.KEY_U, "Mapwriter"); + //public static KeyBinding keyQuickLargeMap = new KeyBinding("key.mw_quick_large_map", Keyboard.KEY_NONE); + + public MwKeyHandler(){ + ClientRegistry.registerKeyBinding(keyMapGui); + ClientRegistry.registerKeyBinding(keyNewMarker); + ClientRegistry.registerKeyBinding(keyMapMode); + ClientRegistry.registerKeyBinding(keyNextGroup); + ClientRegistry.registerKeyBinding(keyTeleport); + ClientRegistry.registerKeyBinding(keyZoomIn); + ClientRegistry.registerKeyBinding(keyZoomOut); + ClientRegistry.registerKeyBinding(keyUndergroundMode); + } + + @SubscribeEvent + public void onKeyPress(InputEvent.KeyInputEvent event){ + if(keyMapGui.getIsKeyPressed()){ + KeyBinding.setKeyBindState(keyMapGui.getKeyCode(), false); + Mw.instance.onKeyDown(keyMapGui); + } + if(keyNewMarker.getIsKeyPressed()){ + KeyBinding.setKeyBindState(keyNewMarker.getKeyCode(), false); + Mw.instance.onKeyDown(keyNewMarker); + } + if(keyMapMode.getIsKeyPressed()){ + KeyBinding.setKeyBindState(keyMapMode.getKeyCode(), false); + Mw.instance.onKeyDown(keyMapMode); + } + if(keyNextGroup.getIsKeyPressed()){ + KeyBinding.setKeyBindState(keyNextGroup.getKeyCode(), false); + Mw.instance.onKeyDown(keyNextGroup); + } + if(keyTeleport.getIsKeyPressed()){ + KeyBinding.setKeyBindState(keyTeleport.getKeyCode(), false); + Mw.instance.onKeyDown(keyTeleport); + } + if(keyZoomIn.getIsKeyPressed()){ + KeyBinding.setKeyBindState(keyZoomIn.getKeyCode(), false); + Mw.instance.onKeyDown(keyZoomIn); + } + if(keyZoomOut.getIsKeyPressed()){ + KeyBinding.setKeyBindState(keyZoomOut.getKeyCode(), false); + Mw.instance.onKeyDown(keyZoomOut); + } + if(keyUndergroundMode.getIsKeyPressed()){ + KeyBinding.setKeyBindState(keyUndergroundMode.getKeyCode(), false); + Mw.instance.onKeyDown(keyUndergroundMode); + } + } +} diff --git a/src/main/java/mapwriter/gui/MwGui.java b/src/main/java/mapwriter/gui/MwGui.java new file mode 100644 index 0000000..c7afe9e --- /dev/null +++ b/src/main/java/mapwriter/gui/MwGui.java @@ -0,0 +1,635 @@ +package mapwriter.gui; + +import java.awt.Point; + +import mapwriter.Mw; +import mapwriter.MwUtil; +import mapwriter.api.IMwDataProvider; +import mapwriter.api.MwAPI; +import mapwriter.forge.MwKeyHandler; +import mapwriter.map.MapRenderer; +import mapwriter.map.MapView; +import mapwriter.map.Marker; +import mapwriter.map.mapmode.FullScreenMapMode; +import mapwriter.map.mapmode.MapMode; +import mapwriter.tasks.MergeTask; +import mapwriter.tasks.RebuildRegionsTask; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class MwGui extends GuiScreen { + private Mw mw; + private MapMode mapMode; + private MapView mapView; + private MapRenderer map; + + private final static double PAN_FACTOR = 0.3D; + + private static final int menuY = 5; + private static final int menuX = 5; + + private int mouseLeftHeld = 0; + //private int mouseRightHeld = 0; + //private int mouseMiddleHeld = 0; + private int mouseLeftDragStartX = 0; + private int mouseLeftDragStartY = 0; + private double viewXStart; + private double viewZStart; + private Marker movingMarker = null; + private int movingMarkerXStart = 0; + private int movingMarkerZStart = 0; + private int mouseBlockX = 0; + private int mouseBlockY = 0; + private int mouseBlockZ = 0; + + private int exit = 0; + + private Label helpLabel; + private Label optionsLabel; + private Label dimensionLabel; + private Label groupLabel; + private Label overlayLabel; + + class Label { + int x = 0, y = 0, w = 1, h = 12; + public Label() { + } + + public void draw(int x, int y, String s) { + this.x = x; + this.y = y; + this.w = MwGui.this.fontRendererObj.getStringWidth(s) + 4; + MwGui.drawRect(this.x, this.y, this.x + this.w, this.y + this.h, 0x80000000); + MwGui.this.drawString(MwGui.this.fontRendererObj, s, this.x + 2, this.y + 2, 0xffffff); + } + + public void drawToRightOf(Label label, String s) { + this.draw(label.x + label.w + 5, label.y, s); + } + + public boolean posWithin(int x, int y) { + return (x >= this.x) && (y >= this.y) && (x <= (this.x + this.w)) && (y <= (this.y + this.h)); + } + } + + public MwGui(Mw mw) { + this.mw = mw; + this.mapMode = new FullScreenMapMode(mw.config); + this.mapView = new MapView(this.mw); + this.map = new MapRenderer(this.mw, this.mapMode, this.mapView); + + this.mapView.setDimension(this.mw.miniMap.view.getDimension()); + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); + this.mapView.setZoomLevel(0); + + this.helpLabel = new Label(); + this.optionsLabel = new Label(); + this.dimensionLabel = new Label(); + this.groupLabel = new Label(); + this.overlayLabel = new Label(); + } + + public MwGui(Mw mw, int dim, int x, int z){ + this(mw); + this.mapView.setDimension(dim); + this.mapView.setViewCentreScaled(x, z, dim); + this.mapView.setZoomLevel(0); + } + + // called when gui is displayed and every time the screen + // is resized + public void initGui() { + } + + // called when a button is pressed + protected void actionPerformed(GuiButton button) { + + } + + public void exitGui() { + //MwUtil.log("closing GUI"); + // set the mini map dimension to the GUI map dimension when closing + this.mw.miniMap.view.setDimension(this.mapView.getDimension()); + this.mapMode.close(); + Keyboard.enableRepeatEvents(false); + this.mc.displayGuiScreen((GuiScreen) null); + this.mc.setIngameFocus(); + this.mc.getSoundHandler().resumeSounds(); + } + + // get a marker near the specified block pos if it exists. + // the maxDistance is based on the view width so that you need to click closer + // to a marker when zoomed in to select it. + public Marker getMarkerNearScreenPos(int x, int y) { + Marker nearMarker = null; + for (Marker marker : this.mw.markerManager.visibleMarkerList) { + if (marker.screenPos != null) { + if (marker.screenPos.distanceSq(x, y) < 6.0) { + nearMarker = marker; + } + } + } + return nearMarker; + } + + public int getHeightAtBlockPos(int bX, int bZ) { + int bY = 0; + int worldDimension = this.mw.mc.theWorld.provider.dimensionId; + if ((worldDimension == this.mapView.getDimension()) && (worldDimension != -1)) { + bY = this.mw.mc.theWorld.getChunkFromBlockCoords(bX, bZ).getHeightValue(bX & 0xf, bZ & 0xf); + } + return bY; + } + + public boolean isPlayerNearScreenPos(int x, int y) { + Point.Double p = this.map.playerArrowScreenPos; + return p.distanceSq(x, y) < 9.0; + } + + public void deleteSelectedMarker() { + if (this.mw.markerManager.selectedMarker != null) { + //MwUtil.log("deleting marker %s", this.mw.markerManager.selectedMarker.name); + this.mw.markerManager.delMarker(this.mw.markerManager.selectedMarker); + this.mw.markerManager.update(); + this.mw.markerManager.selectedMarker = null; + } + } + + public void mergeMapViewToImage() { + this.mw.chunkManager.saveChunks(); + this.mw.executor.addTask(new MergeTask(this.mw.regionManager, + (int) this.mapView.getX(), + (int) this.mapView.getZ(), + (int) this.mapView.getWidth(), + (int) this.mapView.getHeight(), + this.mapView.getDimension(), + this.mw.worldDir, + this.mw.worldDir.getName())); + + MwUtil.printBoth("merging to '" + this.mw.worldDir.getAbsolutePath() + "'"); + } + + public void regenerateView() { + MwUtil.printBoth(String.format("regenerating %dx%d blocks starting from (%d, %d)", + (int) this.mapView.getWidth(), + (int) this.mapView.getHeight(), + (int) this.mapView.getMinX(), + (int) this.mapView.getMinZ())); + this.mw.reloadBlockColours(); + this.mw.executor.addTask(new RebuildRegionsTask( + this.mw, + (int) this.mapView.getMinX(), + (int) this.mapView.getMinZ(), + (int) this.mapView.getWidth(), + (int) this.mapView.getHeight(), + this.mapView.getDimension())); + } + + // c is the ascii equivalent of the key typed. + // key is the lwjgl key code. + protected void keyTyped(char c, int key) { + //MwUtil.log("MwGui.keyTyped(%c, %d)", c, key); + switch(key) { + case Keyboard.KEY_ESCAPE: + this.exitGui(); + break; + + case Keyboard.KEY_DELETE: + this.deleteSelectedMarker(); + break; + + case Keyboard.KEY_SPACE: + // next marker group + this.mw.markerManager.nextGroup(); + this.mw.markerManager.update(); + break; + + case Keyboard.KEY_C: + // cycle selected marker colour + if (this.mw.markerManager.selectedMarker != null) { + this.mw.markerManager.selectedMarker.colourNext(); + } + break; + + case Keyboard.KEY_N: + // select next visible marker + this.mw.markerManager.selectNextMarker(); + break; + + case Keyboard.KEY_HOME: + // centre map on player + this.mapView.setViewCentreScaled(this.mw.playerX, this.mw.playerZ, this.mw.playerDimension); + break; + + case Keyboard.KEY_END: + // centre map on selected marker + if (this.mw.markerManager.selectedMarker != null) { + this.mapView.setViewCentreScaled( + this.mw.markerManager.selectedMarker.x, + this.mw.markerManager.selectedMarker.z, + 0 + ); + } + break; + + case Keyboard.KEY_P: + this.mergeMapViewToImage(); + this.exitGui(); + break; + + case Keyboard.KEY_T: + if (this.mw.markerManager.selectedMarker != null) { + this.mw.teleportToMarker(this.mw.markerManager.selectedMarker); + this.exitGui(); + } else { + this.mc.displayGuiScreen( + new MwGuiTeleportDialog( + this, + this.mw, + this.mapView, + this.mouseBlockX, + this.mw.defaultTeleportHeight, + this.mouseBlockZ + ) + ); + } + break; + + case Keyboard.KEY_LEFT: + this.mapView.panView(-PAN_FACTOR, 0); + break; + case Keyboard.KEY_RIGHT: + this.mapView.panView(PAN_FACTOR, 0); + break; + case Keyboard.KEY_UP: + this.mapView.panView(0, -PAN_FACTOR); + break; + case Keyboard.KEY_DOWN: + this.mapView.panView(0, PAN_FACTOR); + break; + + case Keyboard.KEY_R: + this.regenerateView(); + this.exitGui(); + break; + + //case Keyboard.KEY_9: + // MwUtil.log("refreshing maptexture"); + // this.mw.mapTexture.updateTexture(); + // break; + + default: + if (key == MwKeyHandler.keyMapGui.getKeyCode()) { + // exit on the next tick + this.exit = 1; + } else if (key == MwKeyHandler.keyZoomIn.getKeyCode()) { + this.mapView.adjustZoomLevel(-1); + } else if (key == MwKeyHandler.keyZoomOut.getKeyCode()) { + this.mapView.adjustZoomLevel(1); + } else if (key == MwKeyHandler.keyNextGroup.getKeyCode()) { + this.mw.markerManager.nextGroup(); + this.mw.markerManager.update(); + } else if (key == MwKeyHandler.keyUndergroundMode.getKeyCode()) { + this.mw.toggleUndergroundMode(); + this.mapView.setUndergroundMode(this.mw.undergroundMode); + } + break; + } + } + + // override GuiScreen's handleMouseInput to process + // the scroll wheel. + @Override + public void handleMouseInput() { + if (MwAPI.getCurrentDataProvider() != null && MwAPI.getCurrentDataProvider().onMouseInput(this.mapView, this.mapMode)) + return; + + int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; + int direction = Mouse.getEventDWheel(); + if (direction != 0) { + this.mouseDWheelScrolled(x, y, direction); + } + super.handleMouseInput(); + } + + // mouse button clicked. 0 = LMB, 1 = RMB, 2 = MMB + protected void mouseClicked(int x, int y, int button) { + //MwUtil.log("MwGui.mouseClicked(%d, %d, %d)", x, y, button); + + //int bX = this.mouseToBlockX(x); + //int bZ = this.mouseToBlockZ(y); + //int bY = this.getHeightAtBlockPos(bX, bZ); + + Marker marker = this.getMarkerNearScreenPos(x, y); + Marker prevMarker = this.mw.markerManager.selectedMarker; + + if (button == 0) { + if (this.dimensionLabel.posWithin(x, y)) { + this.mc.displayGuiScreen( + new MwGuiDimensionDialog( + this, + this.mw, + this.mapView, + this.mapView.getDimension() + ) + ); + } else if (this.optionsLabel.posWithin(x, y)) { + this.mc.displayGuiScreen(new MwGuiOptions(this, this.mw)); + } else { + this.mouseLeftHeld = 1; + this.mouseLeftDragStartX = x; + this.mouseLeftDragStartY = y; + this.mw.markerManager.selectedMarker = marker; + + if ((marker != null) && (prevMarker == marker)) { + // clicked previously selected marker. + // start moving the marker. + this.movingMarker = marker; + this.movingMarkerXStart = marker.x; + this.movingMarkerZStart = marker.z; + } + } + + } else if (button == 1) { + //this.mouseRightHeld = 1; + if ((marker != null) && (prevMarker == marker)) { + // right clicked previously selected marker. + // edit the marker + this.mc.displayGuiScreen( + new MwGuiMarkerDialog( + this, + this.mw.markerManager, + marker + ) + ); + + } else if (marker == null) { + // open new marker dialog + String group = this.mw.markerManager.getVisibleGroupName(); + if (group.equals("none")) { + group = "group"; + } + + int mx, my, mz; + if (this.isPlayerNearScreenPos(x, y)) { + // marker at player's locations + mx = this.mw.playerXInt; + my = this.mw.playerYInt; + mz = this.mw.playerZInt; + + } else { + // marker at mouse pointer location + mx = this.mouseBlockX; + my = (this.mouseBlockY > 0) ? this.mouseBlockY : this.mw.defaultTeleportHeight; + mz = this.mouseBlockZ; + } + this.mc.displayGuiScreen( + new MwGuiMarkerDialog( + this, + this.mw.markerManager, + "", + group, + mx, my, mz, + this.mapView.getDimension() + ) + ); + } + } + + else if (button == 2) { + Point blockPoint = this.mapMode.screenXYtoBlockXZ(this.mapView, x, y); + + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) + provider.onMiddleClick(this.mapView.getDimension(), blockPoint.x, blockPoint.y, this.mapView); + } + + this.viewXStart = this.mapView.getX(); + this.viewZStart = this.mapView.getZ(); + //this.viewSizeStart = this.mapManager.getViewSize(); + } + + // mouse button released. 0 = LMB, 1 = RMB, 2 = MMB + // not called on mouse movement. + protected void mouseMovedOrUp(int x, int y, int button) { + //MwUtil.log("MwGui.mouseMovedOrUp(%d, %d, %d)", x, y, button); + if (button == 0) { + this.mouseLeftHeld = 0; + this.movingMarker = null; + } else if (button == 1) { + //this.mouseRightHeld = 0; + } + } + + // zoom on mouse direction wheel scroll + public void mouseDWheelScrolled(int x, int y, int direction) { + Marker marker = this.getMarkerNearScreenPos(x, y); + if ((marker != null) && (marker == this.mw.markerManager.selectedMarker)) { + if (direction > 0) { + marker.colourNext(); + } else { + marker.colourPrev(); + } + + } else if (this.dimensionLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + this.mapView.nextDimension(this.mw.dimensionList, n); + + } else if (this.groupLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + this.mw.markerManager.nextGroup(n); + this.mw.markerManager.update(); + } else if (this.overlayLabel.posWithin(x, y)) { + int n = (direction > 0) ? 1 : -1; + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onOverlayDeactivated(this.mapView); + + if (n == 1) + MwAPI.setNextProvider(); + else + MwAPI.setPrevProvider(); + + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onOverlayActivated(this.mapView); + + } else { + int zF = (direction > 0) ? -1 : 1; + this.mapView.zoomToPoint(this.mapView.getZoomLevel() + zF, this.mouseBlockX, this.mouseBlockZ); + } + } + + // called every frame + public void updateScreen() { + //MwUtil.log("MwGui.updateScreen() " + Thread.currentThread().getName()); + // need to wait one tick before exiting so that the game doesn't + // handle the 'm' key and re-open the gui. + // there should be a better way. + if (this.exit > 0) { + this.exit++; + } + if (this.exit > 2) { + this.exitGui(); + } + super.updateScreen(); + } + + public void drawStatus(int bX, int bY, int bZ) { + String s; + if (bY != 0) { + s = String.format("cursor: (%d, %d, %d)", bX, bY, bZ); + } else { + s = String.format("cursor: (%d, ?, %d)", bX, bZ); + } + if (this.mc.theWorld != null) { + if (!this.mc.theWorld.getChunkFromBlockCoords(bX, bZ).isEmpty()) { + s += String.format(", biome: %s", this.mc.theWorld.getBiomeGenForCoords(bX, bZ).biomeName); + } + } + + /*if (this.mw.markerManager.selectedMarker != null) { + s += ", current marker: " + this.mw.markerManager.selectedMarker.name; + }*/ + + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) + s += provider.getStatusString(this.mapView.getDimension(), bX, bY, bZ); + + drawRect(10, this.height - 21, this.width - 20, this.height - 6, 0x80000000); + this.drawCenteredString(this.fontRendererObj, + s, this.width / 2, this.height - 18, 0xffffff); + } + + public void drawHelp() { + drawRect(10, 20, this.width - 20, this.height - 30, 0x80000000); + this.fontRendererObj.drawSplitString( + "Keys:\n\n" + + " Space\n" + + " Delete\n" + + " C\n" + + " Home\n" + + " End\n" + + " N\n" + + " T\n" + + " P\n" + + " R\n" + + " U\n\n" + + "Left click drag or arrow keys pan the map.\n" + + "Mouse wheel or Page Up/Down zooms map.\n" + + "Right click map to create a new marker.\n" + + "Left click drag a selected marker to move it.\n" + + "Mouse wheel over selected marker to cycle colour.\n" + + "Mouse wheel over dimension or group box to cycle.\n", + 15, 24, this.width - 30, 0xffffff); + this.fontRendererObj.drawSplitString( + "| Next marker group\n" + + "| Delete selected marker\n" + + "| Cycle selected marker colour\n" + + "| Centre map on player\n" + + "| Centre map on selected marker\n" + + "| Select next marker\n" + + "| Teleport to cursor or selected marker\n" + + "| Save PNG of visible map area\n" + + "| Regenerate visible map area from region files\n" + + "| Underground map mode\n", + 75, 42, this.width - 90, 0xffffff); + } + + public void drawMouseOverHint(int x, int y, String title, int mX, int mY, int mZ) { + String desc = String.format("(%d, %d, %d)", mX, mY, mZ); + int stringW = Math.max( + this.fontRendererObj.getStringWidth(title), + this.fontRendererObj.getStringWidth(desc)); + + x = Math.min(x, this.width - (stringW + 16)); + y = Math.min(Math.max(10, y), this.height - 14); + + drawRect(x + 8, y - 10, x + stringW + 16, y + 14, 0x80000000); + this.drawString(this.fontRendererObj, + title, + x + 10, y - 8, 0xffffff); + this.drawString(this.fontRendererObj, + desc, + x + 10, y + 4, 0xcccccc); + } + + // also called every frame + public void drawScreen(int mouseX, int mouseY, float f) { + + this.drawDefaultBackground(); + double xOffset = 0.0; + double yOffset = 0.0; + //double zoomFactor = 1.0; + + if (this.mouseLeftHeld > 2) { + xOffset = (this.mouseLeftDragStartX - mouseX) * this.mapView.getWidth() / this.mapMode.w; + yOffset = (this.mouseLeftDragStartY - mouseY) * this.mapView.getHeight() / this.mapMode.h; + + if (this.movingMarker != null) { + double scale = this.mapView.getDimensionScaling(this.movingMarker.dimension); + this.movingMarker.x = this.movingMarkerXStart - (int) (xOffset / scale); + this.movingMarker.z = this.movingMarkerZStart - (int) (yOffset / scale); + } else { + this.mapView.setViewCentre(this.viewXStart + xOffset, this.viewZStart + yOffset); + } + } + + if (this.mouseLeftHeld > 0) { + this.mouseLeftHeld++; + } + + // draw the map + this.map.draw(); + + // let the renderEngine know we have changed the texture. + //this.mc.renderEngine.resetBoundTexture(); + + // get the block the mouse is currently hovering over + Point p = this.mapMode.screenXYtoBlockXZ(this.mapView, mouseX, mouseY); + this.mouseBlockX = p.x; + this.mouseBlockZ = p.y; + this.mouseBlockY = this.getHeightAtBlockPos(this.mouseBlockX, this.mouseBlockZ); + + // draw name of marker under mouse cursor + Marker marker = this.getMarkerNearScreenPos(mouseX, mouseY); + if (marker != null) { + this.drawMouseOverHint(mouseX, mouseY, marker.name, marker.x, marker.y, marker.z); + } + + // draw name of player under mouse cursor + if (this.isPlayerNearScreenPos(mouseX, mouseY)) { + this.drawMouseOverHint(mouseX, mouseY, this.mc.thePlayer.getDisplayName(), + this.mw.playerXInt, + this.mw.playerYInt, + this.mw.playerZInt); + } + + // draw status message + this.drawStatus(this.mouseBlockX, this.mouseBlockY, this.mouseBlockZ); + + // draw labels + this.helpLabel.draw(menuX, menuY, "[help]"); + this.optionsLabel.drawToRightOf(this.helpLabel, "[options]"); + String dimString = String.format("[dimension: %d]", this.mapView.getDimension()); + this.dimensionLabel.drawToRightOf(this.optionsLabel, dimString); + String groupString = String.format("[group: %s]", this.mw.markerManager.getVisibleGroupName()); + this.groupLabel.drawToRightOf(this.dimensionLabel, groupString); + String overlayString = String.format("[overlay : %s]", MwAPI.getCurrentProviderName()); + this.overlayLabel.drawToRightOf(this.groupLabel, overlayString); + + // help message on mouse over + if (this.helpLabel.posWithin(mouseX, mouseY)) { + this.drawHelp(); + } + + super.drawScreen(mouseX, mouseY, f); + } +} + diff --git a/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java new file mode 100644 index 0000000..18d8c84 --- /dev/null +++ b/src/main/java/mapwriter/gui/MwGuiDimensionDialog.java @@ -0,0 +1,35 @@ +package mapwriter.gui; + +import mapwriter.Mw; +import mapwriter.map.MapView; +import net.minecraft.client.gui.GuiScreen; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class MwGuiDimensionDialog extends MwGuiTextDialog { + + final Mw mw; + final MapView mapView; + final int dimension; + + public MwGuiDimensionDialog(GuiScreen parentScreen, Mw mw, MapView mapView, int dimension) { + super(parentScreen, "Set dimension to:", "" + dimension, "invalid dimension"); + this.mw = mw; + this.mapView = mapView; + this.dimension = dimension; + } + + @Override + public boolean submit() { + boolean done = false; + int dimension = this.getInputAsInt(); + if (this.inputValid) { + this.mapView.setDimensionAndAdjustZoom(dimension); + this.mw.miniMap.view.setDimension(dimension); + this.mw.addDimension(dimension); + done = true; + } + return done; + } +} diff --git a/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java new file mode 100644 index 0000000..2e57115 --- /dev/null +++ b/src/main/java/mapwriter/gui/MwGuiMarkerDialog.java @@ -0,0 +1,105 @@ +package mapwriter.gui; + +import mapwriter.map.Marker; +import mapwriter.map.MarkerManager; +import net.minecraft.client.gui.GuiScreen; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class MwGuiMarkerDialog extends MwGuiTextDialog { + private final MarkerManager markerManager; + private Marker editingMarker; + private String markerName = "name"; + private String markerGroup = "group"; + private int markerX = 0; + private int markerY = 80; + private int markerZ = 0; + private int state = 0; + private int dimension = 0; + + public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, String markerName, String markerGroup, int x, int y, int z, int dimension) { + super(parentScreen, "Marker Name:", markerName, "marker must have a name"); + this.markerManager = markerManager; + this.markerName = markerName; + this.markerGroup = markerGroup; + this.markerX = x; + this.markerY = y; + this.markerZ = z; + this.editingMarker = null; + this.dimension = dimension; + } + + public MwGuiMarkerDialog(GuiScreen parentScreen, MarkerManager markerManager, Marker editingMarker) { + super(parentScreen, "Edit Marker Name:", editingMarker.name, "marker must have a name"); + this.markerManager = markerManager; + this.editingMarker = editingMarker; + this.markerName = editingMarker.name; + this.markerGroup = editingMarker.groupName; + this.markerX = editingMarker.x; + this.markerY = editingMarker.y; + this.markerZ = editingMarker.z; + this.dimension = editingMarker.dimension; + } + + @Override + public boolean submit() { + boolean done = false; + switch(this.state) { + case 0: + this.markerName = this.getInputAsString(); + if (this.inputValid) { + this.title = "Marker Group:"; + this.setText(this.markerGroup); + this.error = "marker must have a group name"; + this.state++; + } + break; + case 1: + this.markerGroup = this.getInputAsString(); + if (this.inputValid) { + this.title = "Marker X:"; + this.setText("" + this.markerX); + this.error = "invalid value"; + this.state++; + } + break; + case 2: + this.markerX = this.getInputAsInt(); + if (this.inputValid) { + this.title = "Marker Y:"; + this.setText("" + this.markerY); + this.error = "invalid value"; + this.state++; + } + break; + case 3: + this.markerY = this.getInputAsInt(); + if (this.inputValid) { + this.title = "Marker Z:"; + this.setText("" + this.markerZ); + this.error = "invalid value"; + this.state++; + } + break; + case 4: + this.markerZ = this.getInputAsInt(); + if (this.inputValid) { + done = true; + int colour = Marker.getCurrentColour(); + if (this.editingMarker != null) { + colour = this.editingMarker.colour; + this.markerManager.delMarker(this.editingMarker); + this.editingMarker = null; + } + this.markerManager.addMarker(this.markerName, this.markerGroup, + this.markerX, this.markerY, this.markerZ, + this.dimension, colour); + this.markerManager.setVisibleGroupName(this.markerGroup); + this.markerManager.update(); + } + break; + } + return done; + } +} diff --git a/src/main/java/mapwriter/gui/MwGuiOptionSlot.java b/src/main/java/mapwriter/gui/MwGuiOptionSlot.java new file mode 100644 index 0000000..a1e35a5 --- /dev/null +++ b/src/main/java/mapwriter/gui/MwGuiOptionSlot.java @@ -0,0 +1,232 @@ +package mapwriter.gui; + +import mapwriter.Mw; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiSlot; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.ResourceLocation; + +public class MwGuiOptionSlot extends GuiSlot { + + //private GuiScreen parentScreen; + private Minecraft mc; + private Mw mw; + + private int mouseX = 0; + private int mouseY = 0; + + private int miniMapPositionIndex = 0; + private static final String[] miniMapPositionStringArray = { + "unchanged", + "top right", + "top left", + "bottom right", + "bottom left" + }; + private static final String[] coordsModeStringArray = { + "disabled", + "small", + "large" + }; + private static final String[] backgroundModeStringArray = { + "none", + "static", + "panning" + }; + + private GuiButton[] buttons = new GuiButton[12]; + + static final ResourceLocation WIDGET_TEXTURE_LOC = new ResourceLocation("textures/gui/widgets.png"); + + public void updateButtonLabel(int i) { + switch(i) { + case 0: + this.buttons[i].displayString = "Draw coords: " + coordsModeStringArray[this.mw.coordsMode]; + break; + case 1: + this.buttons[i].displayString = "Circular mode: " + this.mw.miniMap.smallMapMode.circular; + break; + case 2: + this.buttons[i].displayString = "Texture size: " + this.mw.configTextureSize; + break; + case 3: + this.buttons[i].displayString = "Texture scaling: " + (this.mw.linearTextureScalingEnabled ? "linear" : "nearest"); + break; + case 4: + this.buttons[i].displayString = "Trail markers: " + (this.mw.playerTrail.enabled); + break; + case 5: + this.buttons[i].displayString = "Map colours: " + (this.mw.useSavedBlockColours ? "frozen" : "auto"); + break; + case 6: + this.buttons[i].displayString = "Max draw distance: " + Math.round(Math.sqrt(this.mw.maxChunkSaveDistSq)); + break; + case 7: + this.buttons[i].displayString = "Mini map size: " + this.mw.miniMap.smallMapMode.heightPercent; + break; + case 8: + this.buttons[i].displayString = "Mini map position: " + miniMapPositionStringArray[this.miniMapPositionIndex]; + break; + case 9: + this.buttons[i].displayString = "Map pixel snapping: " + (this.mw.mapPixelSnapEnabled ? "enabled" : "disabled"); + break; + case 10: + this.buttons[i].displayString = "Max death markers: " + this.mw.maxDeathMarkers; + break; + case 11: + this.buttons[i].displayString = "Background mode: " + backgroundModeStringArray[this.mw.backgroundTextureMode]; + break; + //case 11: + // this.buttons[i].displayString = "Map Lighting: " + (this.mw.lightingEnabled ? "enabled" : "disabled"); + // break; + default: + break; + } + } + + public MwGuiOptionSlot(GuiScreen parentScreen, Minecraft mc, Mw mw) { + // GuiSlot(minecraft, width, height, top, bottom, slotHeight) + super(mc, parentScreen.width, parentScreen.height, 16, parentScreen.height - 32, 25); + //this.parentScreen = parentScreen; + this.mw = mw; + this.mc = mc; + for (int i = 0; i < this.buttons.length; i++) { + this.buttons[i] = new GuiButton(300 + i, 0, 0, ""); + this.updateButtonLabel(i); + } + } + + protected boolean keyTyped(char c, int k) { + return false; + } + + @Override + protected int getSize() { + // number of slots + return this.buttons.length; + } + + @Override + protected void elementClicked(int i, boolean doubleClicked, int x, int y) { + switch(i) { + case 0: + // toggle coords + this.mw.toggleCoords(); + break; + case 1: + // toggle circular + this.mw.miniMap.toggleRotating(); + break; + case 2: + // toggle texture size + this.mw.configTextureSize *= 2; + if (this.mw.configTextureSize > 4096) { + this.mw.configTextureSize = 1024; + } + break; + case 3: + // linear scaling + this.mw.linearTextureScalingEnabled = !this.mw.linearTextureScalingEnabled; + this.mw.mapTexture.setLinearScaling(this.mw.linearTextureScalingEnabled); + //this.mw.undergroundMapTexture.setLinearScaling(this.mw.linearTextureScalingEnabled); + break; + case 4: + // player trail + this.mw.playerTrail.enabled = !this.mw.playerTrail.enabled; + break; + case 5: + // map colours + this.mw.useSavedBlockColours = !this.mw.useSavedBlockColours; + // reload block colours before saving in case player changed + // texture packs before pressing button. + this.mw.reloadBlockColours(); + break; + case 6: + // toggle max chunk save dist + int d = Math.round((float) Math.sqrt(this.mw.maxChunkSaveDistSq)); + d += 32; + if (d > 256) { + d = 64; + } + this.mw.maxChunkSaveDistSq = d * d; + break; + case 7: + this.mw.miniMap.smallMapMode.toggleHeightPercent(); + break; + case 8: + this.miniMapPositionIndex++; + if (this.miniMapPositionIndex >= miniMapPositionStringArray.length) { + // don't go back to the "unchanged" setting + this.miniMapPositionIndex = 1; + } + switch (this.miniMapPositionIndex) { + case 1: + // top right position + this.mw.miniMap.smallMapMode.setMargins(10, -1, -1, 10); + break; + case 2: + // top left position + this.mw.miniMap.smallMapMode.setMargins(10, -1, 10, -1); + break; + case 3: + // bottom right position + this.mw.miniMap.smallMapMode.setMargins(-1, 40, -1, 10); + break; + case 4: + // bottom left position + this.mw.miniMap.smallMapMode.setMargins(-1, 40, 10, -1); + break; + default: + break; + } + case 9: + // map scroll pixel snapping + this.mw.mapPixelSnapEnabled = !this.mw.mapPixelSnapEnabled; + break; + case 10: + // max death markers + this.mw.maxDeathMarkers++; + if (this.mw.maxDeathMarkers > 10) { + this.mw.maxDeathMarkers = 0; + } + break; + case 11: + // background texture mode + this.mw.backgroundTextureMode = (this.mw.backgroundTextureMode + 1) % 3; + break; + //case 11: + // // lighting + // this.mw.lightingEnabled = !this.mw.lightingEnabled; + // break; + default: + break; + } + this.updateButtonLabel(i); + } + + @Override + public void drawScreen(int mouseX, int mouseY, float f) { + this.mouseX = mouseX; + this.mouseY = mouseY; + super.drawScreen(mouseX, mouseY, f); + } + + @Override + protected boolean isSelected(int i) { + return false; + } + + @Override + protected void drawBackground() { + } + + @Override + protected void drawSlot(int i, int x, int y, int i4, Tessellator tessellator, int i5, int i6){ + GuiButton button = buttons[i]; + button.xPosition = x; + button.yPosition = y; + button.drawButton(this.mc, this.mouseX, this.mouseY); + } +} diff --git a/src/main/java/mapwriter/gui/MwGuiOptions.java b/src/main/java/mapwriter/gui/MwGuiOptions.java new file mode 100644 index 0000000..52709fa --- /dev/null +++ b/src/main/java/mapwriter/gui/MwGuiOptions.java @@ -0,0 +1,51 @@ +package mapwriter.gui; + +import mapwriter.Mw; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; + +public class MwGuiOptions extends GuiScreen { + + private final Mw mw; + private final GuiScreen parentScreen; + private MwGuiOptionSlot optionSlot = null; + + public MwGuiOptions(GuiScreen parentScreen, Mw mw) { + this.mw = mw; + this.parentScreen = parentScreen; + } + + @SuppressWarnings("unchecked") + public void initGui() { + this.optionSlot = new MwGuiOptionSlot(this, this.mc, this.mw); + this.optionSlot.registerScrollButtons(7, 8); + + this.buttonList.add(new GuiButton(200, (this.width / 2) - 50, this.height - 28, 100, 20, "Done")); + } + + protected void actionPerformed(GuiButton button) { + if (button.id == 200) { + // done + // reconfigure texture size + this.mw.setTextureSize(); + this.mc.displayGuiScreen(this.parentScreen); + } + } + + public void drawScreen(int mouseX, int mouseY, float f) { + this.drawDefaultBackground(); + this.optionSlot.drawScreen(mouseX, mouseY, f); + this.drawCenteredString(this.fontRendererObj, "MapWriter Options", this.width / 2, 10, 0xffffff); + super.drawScreen(mouseX, mouseY, f); + } + + protected void mouseClicked(int x, int y, int button) { + super.mouseClicked(x, y, button); + } + + protected void keyTyped(char c, int k) { + if (this.optionSlot.keyTyped(c, k)) { + super.keyTyped(c, k); + } + } +} diff --git a/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java new file mode 100644 index 0000000..77e965e --- /dev/null +++ b/src/main/java/mapwriter/gui/MwGuiTeleportDialog.java @@ -0,0 +1,37 @@ +package mapwriter.gui; + +import mapwriter.Mw; +import mapwriter.map.MapView; +import net.minecraft.client.gui.GuiScreen; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class MwGuiTeleportDialog extends MwGuiTextDialog { + + final Mw mw; + final MapView mapView; + final int teleportX, teleportZ; + + public MwGuiTeleportDialog(GuiScreen parentScreen, Mw mw, MapView mapView, int x, int y, int z) { + super(parentScreen, "Teleport Height:", "" + y, "invalid height"); + this.mw = mw; + this.mapView = mapView; + this.teleportX = x; + this.teleportZ = z; + this.backToGameOnSubmit = true; + } + + @Override + public boolean submit() { + boolean done = false; + int height = this.getInputAsInt(); + if (this.inputValid) { + height = Math.min(Math.max(0, height), 255); + this.mw.defaultTeleportHeight = height; + this.mw.teleportToMapPos(this.mapView, this.teleportX, height, this.teleportZ); + done = true; + } + return done; + } +} diff --git a/src/main/java/mapwriter/gui/MwGuiTextDialog.java b/src/main/java/mapwriter/gui/MwGuiTextDialog.java new file mode 100644 index 0000000..42e7c73 --- /dev/null +++ b/src/main/java/mapwriter/gui/MwGuiTextDialog.java @@ -0,0 +1,158 @@ +package mapwriter.gui; + +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiTextField; + +import org.lwjgl.input.Keyboard; + +public class MwGuiTextDialog extends GuiScreen { + + private final GuiScreen parentScreen; + + String title; + String text; + String error; + GuiTextField textField = null; + boolean inputValid = false; + boolean showError = false; + boolean backToGameOnSubmit = false; + static final int textDialogWidthPercent = 50; + static final int textDialogTitleY = 80; + static final int textDialogY = 92; + static final int textDialogErrorY = 108; + + public MwGuiTextDialog(GuiScreen parentScreen, String title, String text, String error) { + this.parentScreen = parentScreen; + this.title = title; + this.text = text; + this.error = error; + } + + private void newTextField() { + if (this.textField != null) { + this.text = this.textField.getText(); + } + int w = this.width * textDialogWidthPercent / 100; + this.textField = new GuiTextField(this.fontRendererObj, + (this.width - w) / 2 + 5, + textDialogY, + w - 10, + 12); + this.textField.setMaxStringLength(32); + this.textField.setFocused(true); + this.textField.setCanLoseFocus(false); + //this.textField.setEnableBackgroundDrawing(false); + this.textField.setText(this.text); + } + + public void setText(String s) { + this.textField.setText(s); + this.text = s; + } + + public String getInputAsString() { + String s = this.textField.getText().trim(); + this.inputValid = (s.length() > 0); + this.showError = !this.inputValid; + return s; + } + + public int getInputAsInt() { + String s = this.getInputAsString(); + int value = 0; + try { + value = Integer.parseInt(s); + this.inputValid = true; + this.showError = false; + } catch (NumberFormatException e) { + this.inputValid = false; + this.showError = true; + } + return value; + } + + public int getInputAsHexInt() { + String s = this.getInputAsString(); + int value = 0; + try { + value = Integer.parseInt(s, 16); + this.inputValid = true; + this.showError = false; + } catch (NumberFormatException e) { + this.inputValid = false; + this.showError = true; + } + return value; + } + + public boolean submit() { + return false; + } + + public void initGui() { + this.newTextField(); + } + + public void drawScreen(int mouseX, int mouseY, float f) { + + if (this.parentScreen != null) { + this.parentScreen.drawScreen(mouseX, mouseY, f); + } else { + this.drawDefaultBackground(); + } + + int w = this.width * textDialogWidthPercent / 100; + drawRect( + (this.width - w) / 2, + textDialogTitleY - 4, + (this.width - w) / 2 + w, + textDialogErrorY + 14, + 0x80000000); + this.drawCenteredString( + this.fontRendererObj, + this.title, + this.width / 2, + textDialogTitleY, + 0xffffff); + this.textField.drawTextBox(); + if (this.showError) { + this.drawCenteredString( + this.fontRendererObj, + this.error, + this.width / 2, + textDialogErrorY, + 0xffffff); + } + + super.drawScreen(mouseX, mouseY, f); + } + + protected void mouseClicked(int x, int y, int button) { + super.mouseClicked(x, y, button); + } + + protected void keyTyped(char c, int key) { + switch (key) { + case Keyboard.KEY_ESCAPE: + this.mc.displayGuiScreen(this.parentScreen); + break; + + case Keyboard.KEY_RETURN: + // when enter pressed, submit current input + if (this.submit()) { + if (!this.backToGameOnSubmit) { + this.mc.displayGuiScreen(this.parentScreen); + } else { + this.mc.displayGuiScreen(null); + } + } + break; + + default: + // other characters are processed by the text box + this.textField.textboxKeyTyped(c, key); + this.text = this.textField.getText(); + break; + } + } +} diff --git a/src/main/java/mapwriter/map/MapRenderer.java b/src/main/java/mapwriter/map/MapRenderer.java new file mode 100644 index 0000000..40458fc --- /dev/null +++ b/src/main/java/mapwriter/map/MapRenderer.java @@ -0,0 +1,319 @@ +package mapwriter.map; + +import java.awt.Point; +import java.util.ArrayList; + +import mapwriter.Mw; +import mapwriter.Render; +import mapwriter.api.IMwChunkOverlay; +import mapwriter.api.IMwDataProvider; +import mapwriter.api.MwAPI; +import mapwriter.map.mapmode.MapMode; +import net.minecraft.util.ResourceLocation; + +import org.lwjgl.opengl.GL11; + +public class MapRenderer { + private Mw mw; + private MapMode mapMode; + private MapView mapView; + // accessed by the MwGui to check whether the mouse cursor is near the + // player arrow on the rendered map + public Point.Double playerArrowScreenPos = new Point.Double(0, 0); + + private ResourceLocation backgroundTexture = new ResourceLocation("mapwriter", "textures/map/background.png"); + private ResourceLocation roundMapTexture = new ResourceLocation("mapwriter", "textures/map/border_round.png"); + private ResourceLocation squareMapTexture = new ResourceLocation("mapwriter", "textures/map/border_square.png"); + private ResourceLocation playerArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_player.png"); + private ResourceLocation northArrowTexture = new ResourceLocation("mapwriter", "textures/map/arrow_north.png"); + + public MapRenderer(Mw mw, MapMode mapMode, MapView mapView) { + this.mw = mw; + this.mapMode = mapMode; + this.mapView = mapView; + } + + private void drawMap() { + + int regionZoomLevel = Math.max(0, this.mapView.getZoomLevel()); + double tSize = (double) this.mw.textureSize; + double zoomScale = (double) (1 << regionZoomLevel); + + // if the texture UV coordinates do not line up with the texture pixels then the texture + // will look blurry when it is drawn to the screen. + // to fix this we round the texture coordinates to the nearest pixel boundary. + // this is unnecessary when zoomed in as the texture will be upscaled and look blurry + // anyway, so it is disabled in this case. + // also the rounding causes the map to noticeably (and unpleasantly) 'snap' to texture + // pixel boundaries when zoomed in. + + double u, v, w, h; + if ((!this.mapMode.circular) && (this.mw.mapPixelSnapEnabled) && (this.mapView.getZoomLevel() >= 0)) { + u = (Math.round(this.mapView.getMinX() / zoomScale) / tSize) % 1.0; + v = (Math.round(this.mapView.getMinZ() / zoomScale) / tSize) % 1.0; + w = Math.round(this.mapView.getWidth() / zoomScale) / tSize; + h = Math.round(this.mapView.getHeight() / zoomScale) / tSize; + } else { + double tSizeInBlocks = tSize * zoomScale; + u = (this.mapView.getMinX() / tSizeInBlocks) % 1.0; + v = (this.mapView.getMinZ() / tSizeInBlocks) % 1.0; + w = (this.mapView.getWidth() / tSizeInBlocks); + h = (this.mapView.getHeight() / tSizeInBlocks); + } + + GL11.glPushMatrix(); + + if (this.mapMode.rotate) { + GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + } + if (this.mapMode.circular) { + Render.setCircularStencil(0, 0, this.mapMode.h / 2.0); + } + + if ((this.mapView.getUndergroundMode()) && (regionZoomLevel == 0)) { + // draw the underground map + this.mw.undergroundMapTexture.requestView(this.mapView); + // underground map needs to have a black background + Render.setColourWithAlphaPercent(0x000000, this.mapMode.alphaPercent); + Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); + Render.setColourWithAlphaPercent(0xffffff, this.mapMode.alphaPercent); + this.mw.undergroundMapTexture.bind(); + Render.drawTexturedRect( + this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, + u, v, u + w, v + h + ); + } else { + // draw the surface map + MapViewRequest req = new MapViewRequest(this.mapView); + this.mw.mapTexture.requestView(req, this.mw.executor, this.mw.regionManager); + + // draw the background texture + if (this.mw.backgroundTextureMode > 0) { + double bu1 = 0.0; double bu2 = 1.0; + double bv1 = 0.0; double bv2 = 1.0; + if (this.mw.backgroundTextureMode == 2) { + // background moves with map if mode is 2 + double bSize = tSize / 256.0; + bu1 = u * bSize; bu2 = (u + w) * bSize; + bv1 = v * bSize; bv2 = (v + h) * bSize; + } + this.mw.mc.renderEngine.bindTexture(this.backgroundTexture); + Render.setColourWithAlphaPercent(0xffffff, this.mapMode.alphaPercent); + Render.drawTexturedRect( + this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, + bu1, bv1, bu2, bv2 + ); + } else { + // mode 0, no background texture + Render.setColourWithAlphaPercent(0x000000, this.mapMode.alphaPercent); + Render.drawRect(this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h); + } + + // only draw surface map if the request is loaded (view requests are + // loaded by the background thread) + if (this.mw.mapTexture.isLoaded(req)) { + this.mw.mapTexture.bind(); + Render.setColourWithAlphaPercent(0xffffff, this.mapMode.alphaPercent); + Render.drawTexturedRect( + this.mapMode.x, this.mapMode.y, this.mapMode.w, this.mapMode.h, + u, v, u + w, v + h + ); + } + } + + // draw ProfMobius chunk overlay + IMwDataProvider provider = this.drawOverlay(); + + // overlay onDraw event + if (provider != null) { + GL11.glPushMatrix(); + provider.onDraw(this.mapView, this.mapMode); + GL11.glPopMatrix(); + } + + if (this.mapMode.circular) { + Render.disableStencil(); + } + + GL11.glPopMatrix(); + } + + private void drawBorder() { + if (this.mapMode.circular) { + this.mw.mc.renderEngine.bindTexture(this.roundMapTexture); + } else { + this.mw.mc.renderEngine.bindTexture(this.squareMapTexture); + } + Render.setColour(0xffffffff); + Render.drawTexturedRect( + this.mapMode.x / 0.75, this.mapMode.y / 0.75, + this.mapMode.w / 0.75, this.mapMode.h / 0.75, + 0.0, 0.0, 1.0, 1.0 + ); + } + + private void drawPlayerArrow() { + GL11.glPushMatrix(); + double scale = this.mapView.getDimensionScaling(this.mw.playerDimension); + Point.Double p = this.mapMode.getClampedScreenXY(this.mapView, this.mw.playerX * scale, this.mw.playerZ * scale); + this.playerArrowScreenPos.setLocation(p.x + this.mapMode.xTranslation, p.y + this.mapMode.yTranslation); + + // the arrow only needs to be rotated if the map is NOT rotated + GL11.glTranslated(p.x, p.y, 0.0); + if (!this.mapMode.rotate) { + GL11.glRotated(-this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + } + + double arrowSize = this.mapMode.playerArrowSize; + Render.setColour(0xffffffff); + this.mw.mc.renderEngine.bindTexture(this.playerArrowTexture); + Render.drawTexturedRect( + -arrowSize, -arrowSize, arrowSize * 2, arrowSize * 2, + 0.0, 0.0, 1.0, 1.0 + ); + GL11.glPopMatrix(); + } + + private void drawIcons() { + GL11.glPushMatrix(); + + if (this.mapMode.rotate) { + GL11.glRotated(this.mw.mapRotationDegrees, 0.0f, 0.0f, 1.0f); + } + + // draw markers + this.mw.markerManager.drawMarkers(this.mapMode, this.mapView); + + // draw player trail + if (this.mw.playerTrail.enabled) { + this.mw.playerTrail.draw(this.mapMode, this.mapView); + } + + // draw north arrow + if (this.mapMode.rotate) { + double y = this.mapMode.h / 2.0; + double arrowSize = this.mapMode.playerArrowSize; + Render.setColour(0xffffffff); + this.mw.mc.renderEngine.bindTexture(this.northArrowTexture); + Render.drawTexturedRect( + -arrowSize, -y - (arrowSize * 2), arrowSize * 2, arrowSize * 2, + 0.0, 0.0, 1.0, 1.0 + ); + } + + GL11.glPopMatrix(); + + // outside of the matrix pop as theplayer arrow + // needs to be drawn without rotation + this.drawPlayerArrow(); + } + + private void drawCoords() { + // draw coordinates + if (this.mapMode.coordsEnabled) { + GL11.glPushMatrix(); + GL11.glTranslatef(this.mapMode.textX, this.mapMode.textY, 0); + if (this.mw.coordsMode != 2) { + GL11.glScalef(0.5f, 0.5f, 1.0f); + } + int offset = 0; + if (this.mw.coordsMode > 0) { + Render.drawCentredString(0, 0, this.mapMode.textColour, + "%d, %d, %d", + this.mw.playerXInt, + this.mw.playerYInt, + this.mw.playerZInt + ); + offset += 12; + } + if (this.mw.undergroundMode) { + Render.drawCentredString( + 0, offset, this.mapMode.textColour,"underground mode" + ); + } + GL11.glPopMatrix(); + } + } + + private IMwDataProvider drawOverlay() { + // draw overlays from registered providers + //for (IMwDataProvider provider : MwAPI.getDataProviders()) + IMwDataProvider provider = MwAPI.getCurrentDataProvider(); + if (provider != null) { + ArrayList overlays = provider.getChunksOverlay( + this.mapView.getDimension(), + this.mapView.getX(), this.mapView.getZ(), + this.mapView.getMinX(), this.mapView.getMinZ(), + this.mapView.getMaxX(), this.mapView.getMaxZ() + ); + if (overlays != null) { + for (IMwChunkOverlay overlay : overlays) { + paintChunk(this.mapMode, this.mapView, overlay); + } + } + } + return provider; + } + + public void draw() { + + this.mapMode.setScreenRes(); + this.mapView.setMapWH(this.mapMode); + this.mapView.setTextureSize(this.mw.textureSize); + + GL11.glPushMatrix(); + GL11.glLoadIdentity(); + + // translate to center of minimap + // z is -2000 so that it is drawn above the 3D world, but below GUI + // elements which are typically at -3000 + GL11.glTranslated(this.mapMode.xTranslation, this.mapMode.yTranslation, -2000.0); + + // draw background, the map texture, and enabled overlays + this.drawMap(); + + if (this.mapMode.borderMode > 0) { + this.drawBorder(); + } + this.drawIcons(); + + this.drawCoords(); + + // some shader mods seem to need depth testing re-enabled + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glPopMatrix(); + } + + private static void paintChunk(MapMode mapMode, MapView mapView, IMwChunkOverlay overlay){ + int chunkX = overlay.getCoordinates().x; + int chunkZ = overlay.getCoordinates().y; + float filling = overlay.getFilling(); + + Point.Double topCorner = mapMode.blockXZtoScreenXY(mapView, chunkX << 4, chunkZ << 4); + Point.Double botCorner = mapMode.blockXZtoScreenXY(mapView, (chunkX + 1) << 4, (chunkZ + 1 << 4)); + + topCorner.x = Math.max(mapMode.x, topCorner.x); + topCorner.x = Math.min(mapMode.x + mapMode.w, topCorner.x); + topCorner.y = Math.max(mapMode.y, topCorner.y); + topCorner.y = Math.min(mapMode.y + mapMode.h, topCorner.y); + + botCorner.x = Math.max(mapMode.x, botCorner.x); + botCorner.x = Math.min(mapMode.x + mapMode.w, botCorner.x); + botCorner.y = Math.max(mapMode.y, botCorner.y); + botCorner.y = Math.min(mapMode.y + mapMode.h, botCorner.y); + + double sizeX = (botCorner.x - topCorner.x) * filling; + double sizeY = (botCorner.y - topCorner.y) * filling; + double offsetX = ((botCorner.x - topCorner.x) - sizeX) / 2; + double offsetY = ((botCorner.y - topCorner.y) - sizeY) / 2; + + if (overlay.hasBorder()) { + Render.setColour(overlay.getBorderColor()); + Render.drawRectBorder(topCorner.x + 1, topCorner.y + 1, botCorner.x - topCorner.x - 1, botCorner.y - topCorner.y - 1, overlay.getBorderWidth()); + } + + Render.setColour(overlay.getColor()); + Render.drawRect(topCorner.x + offsetX + 1, topCorner.y + offsetY + 1, sizeX - 1, sizeY - 1); + } +} + diff --git a/src/main/java/mapwriter/map/MapTexture.java b/src/main/java/mapwriter/map/MapTexture.java new file mode 100644 index 0000000..921f4e3 --- /dev/null +++ b/src/main/java/mapwriter/map/MapTexture.java @@ -0,0 +1,169 @@ +package mapwriter.map; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.BackgroundExecutor; +import mapwriter.Texture; +import mapwriter.region.Region; +import mapwriter.region.RegionManager; + +import org.lwjgl.opengl.GL11; + +public class MapTexture extends Texture { + + public int textureRegions; + public int textureSize; + + private MapViewRequest loadedView = null; + private MapViewRequest requestedView = null; + + private Region[] regionArray; + + // accessed from both render and background thread. + // make sure all methods using it are synchronized. + //private int[] regionModifiedArray; + + private class Rect { + final int x, y, w, h; + Rect(int x, int y, int w, int h) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + } + } + + private List textureUpdateQueue = new ArrayList(); + + public MapTexture(int textureSize, boolean linearScaling) { + super(textureSize, textureSize, 0x00000000, GL11.GL_LINEAR, GL11.GL_LINEAR, GL11.GL_REPEAT); + + this.setLinearScaling(linearScaling); + + this.textureRegions = textureSize >> Region.SHIFT; + this.textureSize = textureSize; + this.regionArray = new Region[this.textureRegions * this.textureRegions]; + } + + public void requestView(MapViewRequest req, BackgroundExecutor executor, RegionManager regionManager) { + if ((this.requestedView == null) || (!this.requestedView.equals(req))) { + this.requestedView = req; + executor.addTask(new MapUpdateViewTask(this, regionManager, req)); + } + } + + public void processTextureUpdates() { + synchronized (this.textureUpdateQueue) { + for (Rect rect : this.textureUpdateQueue) { + //MwUtil.log("MwMapTexture.processTextureUpdates: %d %d %d %d", rect.x, rect.y, rect.w, rect.h); + this.updateTextureArea(rect.x, rect.y, rect.w, rect.h); + } + this.textureUpdateQueue.clear(); + } + } + + public void setLoaded(MapViewRequest req) { + this.loadedView = req; + } + + public boolean isLoaded(MapViewRequest req) { + return (this.loadedView != null) && (this.loadedView.mostlyEquals(req)); + } + + // + // methods below this point run in the background thread + // + + public synchronized void setRGBOpaque(int x, int y, int w, int h, int[] pixels, int offset, int scanSize) { + // TODO: Remove the need for this function. It would better if the + // region pixels were stored as normal pixels (without the height in + // the alpha channel). Then we could just directly copy the pixels + // to the texture pixelBuf. + int bufOffset = (y * this.w) + x; + for (int i = 0; i < h; i++) { + this.setPixelBufPosition(bufOffset + (i * this.w)); + int rowOffset = offset + (i * scanSize); + for (int j = 0; j < w; j++) { + int colour = pixels[rowOffset + j]; + if(colour != 0) { + colour |= 0xff000000; + } + this.pixelBufPut(colour); + } + } + } + + public void addTextureUpdate(int x, int z, int w, int h) { + synchronized (this.textureUpdateQueue) { + this.textureUpdateQueue.add(new Rect(x, z, w, h)); + } + } + + public void updateTextureFromRegion(Region region, int x, int z, int w, int h) { + int tx = (x >> region.zoomLevel) & (this.w - 1); + int ty = (z >> region.zoomLevel) & (this.h - 1); + int tw = (w >> region.zoomLevel); + int th = (h >> region.zoomLevel); + + // make sure we don't write outside texture + tw = Math.min(tw, this.w - tx); + th = Math.min(th, this.h - th); + + //MwUtil.log("updateTextureFromRegion: region %s, %d %d %d %d -> %d %d %d %d", region, x, z, w, h, tx, ty, tw, th); + + int[] pixels = region.getPixels(); + if (pixels != null) { + this.setRGBOpaque(tx, ty, tw, th, pixels, region.getPixelOffset(x, z), Region.SIZE); + } else { + this.fillRect(tx, ty, tw, th, 0x00000000); + } + + this.addTextureUpdate(tx, ty, tw, th); + } + + public int getRegionIndex(int x, int z, int zoomLevel) { + x = (x >> (Region.SHIFT + zoomLevel)) & (this.textureRegions - 1); + z = (z >> (Region.SHIFT + zoomLevel)) & (this.textureRegions - 1); + return (z * this.textureRegions) + x; + } + + public boolean loadRegion(RegionManager regionManager, int x, int z, int zoomLevel, int dimension) { + //MwUtil.log("mapTexture.loadRegion %d %d %d %d", x, z, zoomLevel, dimension); + boolean loaded = false; + int index = this.getRegionIndex(x, z, zoomLevel); + Region currentRegion = this.regionArray[index]; + if ((currentRegion == null) || (!currentRegion.equals(x, z, zoomLevel, dimension))) { + Region newRegion = regionManager.getRegion(x, z, zoomLevel, dimension); + this.regionArray[index] = newRegion; + this.updateTextureFromRegion( + newRegion, newRegion.x, newRegion.z, newRegion.size, newRegion.size + ); + //regionManager.logInfo("regionArray[%d] = %s", index, newRegion); + loaded = true; + } + return loaded; + } + + public int loadRegions(RegionManager regionManager, MapViewRequest req) { + int size = Region.SIZE << req.zoomLevel; + int loadedCount = 0; + for (int z = req.zMin; z <= req.zMax; z += size) { + for (int x = req.xMin; x <= req.xMax; x += size) { + if (this.loadRegion(regionManager, x, z, req.zoomLevel, req.dimension)) { + loadedCount++; + } + } + } + return loadedCount; + } + + public void updateArea(RegionManager regionManager, int x, int z, int w, int h, int dimension) { + for (int i = 0; i < this.regionArray.length; i++) { + Region region = this.regionArray[i]; + if ((region != null) && (region.isAreaWithin(x, z, w, h, dimension))) { + this.updateTextureFromRegion(region, x, z, w, h); + } + } + } +} diff --git a/src/main/java/mapwriter/map/MapUpdateViewTask.java b/src/main/java/mapwriter/map/MapUpdateViewTask.java new file mode 100644 index 0000000..4a91042 --- /dev/null +++ b/src/main/java/mapwriter/map/MapUpdateViewTask.java @@ -0,0 +1,31 @@ +package mapwriter.map; + +import mapwriter.region.RegionManager; +import mapwriter.tasks.Task; + +public class MapUpdateViewTask extends Task { + final MapViewRequest req; + RegionManager regionManager; + MapTexture mapTexture; + + // chunkmanager will need to keep a list of chunks to update. + // it should also keep a 2D chunkSum array so that only modified chunks are updated. + public MapUpdateViewTask(MapTexture mapTexture, RegionManager regionManager, MapViewRequest req) { + + this.mapTexture = mapTexture; + this.regionManager = regionManager; + this.req = req; + } + + @Override + public void run() { + // load regions for view + this.mapTexture.loadRegions(this.regionManager, this.req); + } + + @Override + public void onComplete() { + // set currentView in mapTexture to requestedView + this.mapTexture.setLoaded(this.req); + } +} diff --git a/src/main/java/mapwriter/map/MapView.java b/src/main/java/mapwriter/map/MapView.java new file mode 100644 index 0000000..c2c335a --- /dev/null +++ b/src/main/java/mapwriter/map/MapView.java @@ -0,0 +1,271 @@ +package mapwriter.map; + +import java.util.List; + +import mapwriter.Mw; +import mapwriter.api.MwAPI; +import mapwriter.map.mapmode.MapMode; + +public class MapView { + + private int zoomLevel = 0; + private int dimension = 0; + private int textureSize = 2048; + + // the position of the centre of the 'view' of the map using game (block) coordinates + private double x = 0; + private double z = 0; + + // width and height of map to display in pixels + private int mapW = 0; + private int mapH = 0; + + // the width and height of the map in blocks at zoom level 0. + // updated when map width, map height, or texture size changes. + private int baseW = 1; + private int baseH = 1; + + // the width and height of the map in blocks at the current + // zoom level. + private double w = 1; + private double h = 1; + + private int minZoom; + private int maxZoom; + + private boolean undergroundMode; + + public MapView(Mw mw) { + this.minZoom = mw.minZoom; + this.maxZoom = mw.maxZoom; + this.undergroundMode = mw.undergroundMode; + this.setZoomLevel(0); + this.setViewCentre(mw.playerX, mw.playerZ); + } + + public void setViewCentre(double vX, double vZ) { + this.x = vX; + this.z = vZ; + + if (MwAPI.getCurrentDataProvider() != null) { + MwAPI.getCurrentDataProvider().onMapCenterChanged(vX, vZ, this); + } + + } + + public double getX() { + return this.x; + } + + public double getZ() { + return this.z; + } + + public double getWidth() { + return this.w; + } + + public double getHeight() { + return this.h; + } + + public void panView(double relX, double relZ) { + this.setViewCentre( + this.x + (relX * this.w), + this.z + (relZ * this.h) + ); + } + + public int setZoomLevel(int zoomLevel) { + //MwUtil.log("MapView.setZoomLevel(%d)", zoomLevel); + int prevZoomLevel = this.zoomLevel; + if (this.undergroundMode) { + this.zoomLevel = Math.min(Math.max(this.minZoom, zoomLevel), 0); + } else { + this.zoomLevel = Math.min(Math.max(this.minZoom, zoomLevel), this.maxZoom); + } + if (prevZoomLevel != this.zoomLevel) { + this.updateZoom(); + } + return this.zoomLevel; + } + + private void updateZoom() { + if (this.zoomLevel >= 0) { + this.w = this.baseW << this.zoomLevel; + this.h = this.baseH << this.zoomLevel; + } else { + this.w = this.baseW >> (-this.zoomLevel); + this.h = this.baseH >> (-this.zoomLevel); + } + + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onZoomChanged(this.getZoomLevel(), this); + } + + public int adjustZoomLevel(int n) { + return this.setZoomLevel(this.zoomLevel + n); + } + + public int getZoomLevel() { + return this.zoomLevel; + } + + public int getRegionZoomLevel() { + return Math.max(0, this.zoomLevel); + } + + // bX and bZ are the coordinates of the block the zoom is centred on. + // The relative position of the block in the view will remain the same + // as before the zoom. + public void zoomToPoint(int newZoomLevel, double bX, double bZ) { + int prevZoomLevel = this.zoomLevel; + newZoomLevel = this.setZoomLevel(newZoomLevel); + double zF = Math.pow(2, newZoomLevel - prevZoomLevel); + this.setViewCentre( + bX - ((bX - this.x) * zF), + bZ - ((bZ - this.z) * zF)); + } + + public void setDimension(int dimension) { + double scale = 1.0; + if (dimension != this.dimension) { + if ((this.dimension != -1) && (dimension == -1)) { + scale = 0.125; + } else if ((this.dimension == -1) && (dimension != -1)) { + scale = 8.0; + } + this.dimension = dimension; + this.setViewCentre(this.x * scale, this.z * scale); + } + + if (MwAPI.getCurrentDataProvider() != null) + MwAPI.getCurrentDataProvider().onDimensionChanged(this.dimension, this); + } + + public void setDimensionAndAdjustZoom(int dimension) { + int zoomLevelChange = 0; + if ((this.dimension != -1) && (dimension == -1)) { + zoomLevelChange = -3; + } else if ((this.dimension == -1) && (dimension != -1)) { + zoomLevelChange = 3; + } + this.setZoomLevel(this.getZoomLevel() + zoomLevelChange); + this.setDimension(dimension); + } + + public void nextDimension(List dimensionList, int n) { + int i = dimensionList.indexOf(this.dimension); + i = Math.max(0, i); + int size = dimensionList.size(); + int dimension = dimensionList.get((i + size + n) % size); + this.setDimensionAndAdjustZoom(dimension); + } + + public int getDimension() { + return this.dimension; + } + + public void setMapWH(int w, int h) { + if ((this.mapW != w) || (this.mapH != h)) { + this.mapW = w; + this.mapH = h; + this.updateBaseWH(); + } + } + + public void setMapWH(MapMode mapMode) { + this.setMapWH(mapMode.wPixels, mapMode.hPixels); + } + + public double getMinX() { + return this.x - (this.w / 2); + } + + public double getMaxX() { + return this.x + (this.w / 2); + } + + public double getMinZ() { + return this.z - (this.h / 2); + } + + public double getMaxZ() { + return this.z + (this.h / 2); + } + + public double getDimensionScaling(int playerDimension) { + double scale; + if ((this.dimension != -1) && (playerDimension == -1)) { + scale = 8.0; + } else if ((this.dimension == -1) && (playerDimension != -1)) { + scale = 0.125; + } else { + scale = 1.0; + } + return scale; + } + + public void setViewCentreScaled(double vX, double vZ, int playerDimension) { + double scale = this.getDimensionScaling(playerDimension); + this.setViewCentre(vX * scale, vZ * scale); + } + + public void setTextureSize(int n) { + if (this.textureSize != n) { + this.textureSize = n; + this.updateBaseWH(); + } + } + + private void updateBaseWH() { + int w = this.mapW; + int h = this.mapH; + int halfTextureSize = this.textureSize / 2; + + // if we cannot display the map at 1x1 pixel per block, then + // try 2x2 pixels per block, then 4x4 and so on + while ((w > halfTextureSize) || (h > halfTextureSize)) { + w /= 2; + h /= 2; + } + + //MwUtil.log("MapView.updateBaseWH: map = %dx%d, tsize = %d, base = %dx%d", this.mapW, this.mapH, this.textureSize, w, h); + + this.baseW = w; + this.baseH = h; + + this.updateZoom(); + } + + public int getPixelsPerBlock() { + return this.mapW / this.baseW; + } + + public boolean isBlockWithinView(double bX, double bZ, boolean circular) { + boolean inside; + if (!circular) { + inside = (bX > this.getMinX()) || (bX < this.getMaxX()) || + (bZ > this.getMinZ()) || (bZ < this.getMaxZ()); + } else { + double x = (bX - this.x); + double z = (bZ - this.z); + double r = this.getHeight() / 2; + inside = ((x * x) + (z * z)) < (r * r); + } + return inside; + } + + public boolean getUndergroundMode() { + return this.undergroundMode; + } + + public void setUndergroundMode(boolean enabled) { + if (enabled) { + if (this.zoomLevel >= 0) { + this.setZoomLevel(-1); + } + } + this.undergroundMode = enabled; + } +} diff --git a/src/main/java/mapwriter/map/MapViewRequest.java b/src/main/java/mapwriter/map/MapViewRequest.java new file mode 100644 index 0000000..4c0b777 --- /dev/null +++ b/src/main/java/mapwriter/map/MapViewRequest.java @@ -0,0 +1,33 @@ +package mapwriter.map; + +import mapwriter.region.Region; + +public class MapViewRequest { + public final int xMin, xMax, zMin, zMax, zoomLevel, dimension; + + public MapViewRequest(MapView view) { + this.zoomLevel = view.getRegionZoomLevel(); + int size = Region.SIZE << this.zoomLevel; + this.xMin = ((int) view.getMinX()) & (-size); + this.zMin = ((int) view.getMinZ()) & (-size); + this.xMax = ((int) view.getMaxX()) & (-size); + this.zMax = ((int) view.getMaxZ()) & (-size); + this.dimension = view.getDimension(); + } + + public boolean equals(MapViewRequest req) { + return (req != null) && + (req.zoomLevel == this.zoomLevel) && + (req.dimension == this.dimension) && + (req.xMin == this.xMin) && + (req.xMax == this.xMax) && + (req.zMin == this.zMin) && + (req.zMax == this.zMax); + } + + public boolean mostlyEquals(MapViewRequest req) { + return (req != null) && + (req.zoomLevel == this.zoomLevel) && + (req.dimension == this.dimension); + } +} diff --git a/src/main/java/mapwriter/map/Marker.java b/src/main/java/mapwriter/map/Marker.java new file mode 100644 index 0000000..e195865 --- /dev/null +++ b/src/main/java/mapwriter/map/Marker.java @@ -0,0 +1,79 @@ +package mapwriter.map; + +import java.awt.Point; + +import mapwriter.Render; +import mapwriter.map.mapmode.MapMode; + +public class Marker { + public final String name; + public final String groupName; + public int x; + public int y; + public int z; + public int dimension; + public int colour; + + public Point.Double screenPos = new Point.Double(0, 0); + + private static int[] colours = new int[] { + 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff, + 0xff8000, 0x8000ff}; + // static so that current index is shared between all markers + private static int colourIndex = 0; + + public Marker(String name, String groupName, int x, int y, int z, int dimension, int colour) { + this.name = name; + this.x = x; + this.y = y; + this.z = z; + this.dimension = dimension; + this.colour = colour; + this.groupName = groupName; + } + + public String getString() { + return String.format("%s %s (%d, %d, %d) %d %06x", + this.name, this.groupName, this.x, this.y, this.z, this.dimension, this.colour & 0xffffff); + } + + public static int getCurrentColour() { + return 0xff000000 | colours[colourIndex]; + } + + public void colourNext() { + colourIndex = (colourIndex + 1) % colours.length; + this.colour = getCurrentColour(); + } + + public void colourPrev() { + colourIndex = (colourIndex + colours.length - 1) % colours.length; + this.colour = getCurrentColour(); + } + + public void draw(MapMode mapMode, MapView mapView, int borderColour) { + double scale = mapView.getDimensionScaling(this.dimension); + Point.Double p = mapMode.getClampedScreenXY(mapView, this.x * scale, this.z * scale); + this.screenPos.setLocation(p.x + mapMode.xTranslation, p.y + mapMode.yTranslation); + + // draw a coloured rectangle centered on the calculated (x, y) + double mSize = mapMode.markerSize; + double halfMSize = mapMode.markerSize / 2.0; + Render.setColour(borderColour); + Render.drawRect(p.x - halfMSize, p.y - halfMSize, mSize, mSize); + Render.setColour(this.colour); + Render.drawRect(p.x - halfMSize + 0.5, p.y - halfMSize + 0.5, mSize - 1.0, mSize - 1.0); + } + + // arraylist.contains was producing unexpected results in some situations + // rather than figure out why i'll just control how two markers are compared + @Override + public boolean equals(final Object o) { + if (this == o) { return true; } + if (o instanceof Marker) { + Marker m = (Marker) o; + return (name == m.name) && (groupName == m.groupName) && (x == m.x) && (y == m.y) && (z == m.z) && (dimension == m.dimension); + } + return false; + } +} \ No newline at end of file diff --git a/src/main/java/mapwriter/map/MarkerManager.java b/src/main/java/mapwriter/map/MarkerManager.java new file mode 100644 index 0000000..83e49d5 --- /dev/null +++ b/src/main/java/mapwriter/map/MarkerManager.java @@ -0,0 +1,279 @@ +package mapwriter.map; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.MwUtil; +import mapwriter.forge.MwConfig; +import mapwriter.map.mapmode.MapMode; + +public class MarkerManager { + + public List markerList = new ArrayList(); + public List groupList = new ArrayList(); + + public List visibleMarkerList = new ArrayList(); + + private String visibleGroupName = "none"; + + public Marker selectedMarker = null; + + public MarkerManager() { + } + + public void load(MwConfig config, String category) { + this.markerList.clear(); + + if (config.hasCategory(category)) { + int markerCount = config.get(category, "markerCount", 0).getInt(); + this.visibleGroupName = config.get(category, "visibleGroup", "").getString(); + + if (markerCount > 0) { + for (int i = 0; i < markerCount; i++) { + String key = "marker" + i; + String value = config.get(category, key, "").getString(); + Marker marker = this.stringToMarker(value); + if (marker != null) { + this.addMarker(marker); + } else { + MwUtil.log("error: could not load " + key + " from config file"); + } + } + } + } + + this.update(); + } + + public void save(MwConfig config, String category) { + config.get(category, "markerCount", 0).set(this.markerList.size()); + config.get(category, "visibleGroup", "").set(this.visibleGroupName); + + int i = 0; + for (Marker marker : this.markerList) { + String key = "marker" + i; + String value = this.markerToString(marker); + config.get(category, key, "").set(value); + i++; + } + } + + public void setVisibleGroupName(String groupName) { + if (groupName != null) { + this.visibleGroupName = MwUtil.mungeString(groupName); + } else { + this.visibleGroupName = "none"; + } + } + + public String getVisibleGroupName() { + return this.visibleGroupName; + } + + public void clear() { + this.markerList.clear(); + this.groupList.clear(); + this.visibleMarkerList.clear(); + this.visibleGroupName = "none"; + } + + public String markerToString(Marker marker) { + return String.format("%s:%d:%d:%d:%d:%06x:%s", + marker.name, + marker.x, marker.y, marker.z, + marker.dimension, + marker.colour & 0xffffff, + marker.groupName + ); + } + + public Marker stringToMarker(String s) { + // new style delimited with colons + String[] split = s.split(":"); + if (split.length != 7) { + // old style was space delimited + split = s.split(" "); + } + Marker marker = null; + if (split.length == 7) { + try { + int x = Integer.parseInt(split[1]); + int y = Integer.parseInt(split[2]); + int z = Integer.parseInt(split[3]); + int dimension = Integer.parseInt(split[4]); + int colour = 0xff000000 | Integer.parseInt(split[5], 16); + + marker = new Marker(split[0], split[6], x, y, z, dimension, colour); + + } catch (NumberFormatException e) { + marker = null; + } + } else { + MwUtil.log("Marker.stringToMarker: invalid marker '%s'", s); + } + return marker; + } + + public void addMarker(Marker marker) { + this.markerList.add(marker); + } + + public void addMarker(String name, String groupName, int x, int y, int z, int dimension, int colour) { + name = name.replace(":", ""); + groupName = groupName.replace(":", ""); + this.addMarker(new Marker(name, groupName, x, y, z, dimension, colour)); + } + + // returns true if the marker exists in the arraylist. + // safe to pass null. + public boolean delMarker(Marker markerToDelete) { + return this.markerList.remove(markerToDelete); + } + + // deletes the first marker with matching name and group. + // if null is passed as either name or group it means "any". + public boolean delMarker(String name, String group) { + Marker markerToDelete = null; + for (Marker marker : this.markerList) { + if (((name == null) || marker.name.equals(name)) && + ((group == null) || marker.groupName.equals(group))) { + markerToDelete = marker; + break; + } + } + // will return false if a marker matching the criteria is not found + // (i.e. if markerToDelete is null) + return this.delMarker(markerToDelete); + } + + /*public boolean delGroup(String groupName) { + boolean error = !this.groupList.remove(groupName); + Iterator it = this.markerMap.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + Marker marker = (Marker) entry.getValue(); + if (marker.groupName.equals(groupName)) { + it.remove(); + } + } + if (groupName == this.visibleGroupName) { + this.nextGroup(); + } + return error; + }*/ + + public void update() { + this.visibleMarkerList.clear(); + this.groupList.clear(); + this.groupList.add("none"); + this.groupList.add("all"); + for (Marker marker : this.markerList) { + if (marker.groupName.equals(this.visibleGroupName) || this.visibleGroupName.equals("all")) { + this.visibleMarkerList.add(marker); + } + if (!this.groupList.contains(marker.groupName)) { + this.groupList.add(marker.groupName); + } + } + if (!this.groupList.contains(this.visibleGroupName)) { + this.visibleGroupName = "none"; + } + } + + public void nextGroup(int n) { + if (this.groupList.size() > 0) { + int i = this.groupList.indexOf(this.visibleGroupName); + int size = this.groupList.size(); + if (i != -1) { + i = (i + size + n) % size; + } else { + i = 0; + } + this.visibleGroupName = this.groupList.get(i); + } else { + this.visibleGroupName = "none"; + this.groupList.add("none"); + } + } + + public void nextGroup() { + this.nextGroup(1); + } + + public int countMarkersInGroup(String group) { + int count = 0; + if (group.equals("all")) { + count = this.markerList.size(); + } else { + for (Marker marker : this.markerList) { + if (marker.groupName.equals(group)) { + count++; + } + } + } + return count; + } + + public void selectNextMarker() { + if (this.visibleMarkerList.size() > 0) { + int i = 0; + if (this.selectedMarker != null) { + i = this.visibleMarkerList.indexOf(this.selectedMarker); + if (i == -1) { + i = 0; + } + } + i = (i + 1) % this.visibleMarkerList.size(); + this.selectedMarker = this.visibleMarkerList.get(i); + } else { + this.selectedMarker = null; + } + } + + public Marker getNearestMarker(int x, int z, int maxDistance) { + int nearestDistance = maxDistance * maxDistance; + Marker nearestMarker = null; + for (Marker marker : this.visibleMarkerList) { + int dx = x - marker.x; + int dz = z - marker.z; + int d = (dx * dx) + (dz * dz); + if (d < nearestDistance) { + nearestMarker = marker; + nearestDistance = d; + } + } + return nearestMarker; + } + + public Marker getNearestMarkerInDirection(int x, int z, double desiredAngle) { + int nearestDistance = 10000 * 10000; + Marker nearestMarker = null; + for (Marker marker : this.visibleMarkerList) { + int dx = marker.x - x; + int dz = marker.z - z; + int d = (dx * dx) + (dz * dz); + double angle = Math.atan2(dz, dx); + // use cos instead of abs as it will wrap at 2 * Pi. + // cos will be closer to 1.0 the closer desiredAngle and angle are. + // 0.8 is the threshold corresponding to a maximum of + // acos(0.8) = 37 degrees difference between the two angles. + if ((Math.cos(desiredAngle - angle) > 0.8D) && (d < nearestDistance) && (d > 4)) { + nearestMarker = marker; + nearestDistance = d; + } + } + return nearestMarker; + } + + public void drawMarkers(MapMode mapMode, MapView mapView) { + for (Marker marker : this.visibleMarkerList) { + // only draw markers that were set in the current dimension + if (mapView.getDimension() == marker.dimension) { + marker.draw(mapMode, mapView, 0xff000000); + } + } + if (this.selectedMarker != null) { + this.selectedMarker.draw(mapMode, mapView, 0xffffffff); + } + } +} diff --git a/src/main/java/mapwriter/map/MiniMap.java b/src/main/java/mapwriter/map/MiniMap.java new file mode 100644 index 0000000..feacec3 --- /dev/null +++ b/src/main/java/mapwriter/map/MiniMap.java @@ -0,0 +1,99 @@ +package mapwriter.map; + +import java.util.ArrayList; +import java.util.List; + +import mapwriter.Mw; +import mapwriter.map.mapmode.LargeMapMode; +import mapwriter.map.mapmode.MapMode; +import mapwriter.map.mapmode.SmallMapMode; + +public class MiniMap { + private Mw mw; + + public static final String catSmallMap = "smallMap"; + public static final String catLargeMap = "largeMap"; + public static final String catUndergroundMap = "undergroundMap"; + + public MapMode smallMapMode; + public MapMode largeMapMode; + public MapMode guiMapMode; + + public MapView view; + + public MapRenderer smallMap; + public MapRenderer largeMap; + + private List mapList; + private MapRenderer currentMap = null; + + public int modeIndex = 0; + + public MiniMap(Mw mw) { + this.mw = mw; + + // load config file options + this.modeIndex = mw.config.getOrSetInt(Mw.catOptions, "overlayModeIndex", this.modeIndex, 0, 1000); + int zoomLevel = mw.config.getOrSetInt(Mw.catOptions, "overlayZoomLevel", 0, mw.minZoom, mw.maxZoom); + + // map view shared between large and small map modes + this.view = new MapView(mw); + this.view.setZoomLevel(zoomLevel); + + // small map mode + this.smallMapMode = new SmallMapMode(this.mw.config); + this.smallMap = new MapRenderer(mw, this.smallMapMode, this.view); + + // large map mode + this.largeMapMode = new LargeMapMode(this.mw.config); + this.largeMap = new MapRenderer(mw, this.largeMapMode, this.view); + + this.mapList = new ArrayList(); + + // add small, large and underground map modes if they + // are enabled. + if (this.smallMapMode.enabled) { + this.mapList.add(this.smallMap); + } + if (this.largeMapMode.enabled) { + this.mapList.add(this.largeMap); + } + // add a null entry (hides the overlay when selected) + this.mapList.add(null); + + // sanitize overlayModeIndex loaded from config + this.nextOverlayMode(0); + this.currentMap = this.mapList.get(this.modeIndex); + } + + public void close() { + this.mapList.clear(); + this.currentMap = null; + + this.smallMapMode.close(); + this.largeMapMode.close(); + + this.mw.config.setInt(Mw.catOptions, "overlayModeIndex", this.modeIndex); + this.mw.config.setInt(Mw.catOptions, "overlayZoomLevel", this.view.getZoomLevel()); + } + + // toggle between small map, underground map and no map + public MapRenderer nextOverlayMode(int increment) { + int size = this.mapList.size(); + this.modeIndex = (this.modeIndex + size + increment) % size; + this.currentMap = this.mapList.get(this.modeIndex); + return this.currentMap; + } + + public void toggleRotating() { + boolean rotate = this.smallMapMode.toggleRotating(); + this.largeMapMode.setRotating(rotate); + } + + // draw the map overlay, player arrow, and markers + public void drawCurrentMap() { + if (this.currentMap != null) { + this.currentMap.draw(); + } + } +} \ No newline at end of file diff --git a/src/main/java/mapwriter/map/Trail.java b/src/main/java/mapwriter/map/Trail.java new file mode 100644 index 0000000..641d3a4 --- /dev/null +++ b/src/main/java/mapwriter/map/Trail.java @@ -0,0 +1,98 @@ +package mapwriter.map; + +import java.awt.Point; +import java.util.LinkedList; + +import mapwriter.Mw; +import mapwriter.Render; +import mapwriter.map.mapmode.MapMode; + +public class Trail { + + class TrailMarker { + + double x, y, z, heading; + int alphaPercent; + + static final int borderColour = 0xff000000; + static final int colour = 0xff00ffff; + + public TrailMarker(double x, double y, double z, double heading) { + this.set(x, y, z, heading); + } + + public void set(double x, double y, double z, double heading) { + this.x = x; + this.y = y; + this.z = z; + this.heading = heading; + this.alphaPercent = 100; + } + + public void draw(MapMode mapMode, MapView mapView) { + if (mapView.isBlockWithinView(this.x, this.z, mapMode.circular)) { + Point.Double p = mapMode.blockXZtoScreenXY(mapView, this.x, this.z); + + // draw a coloured arrow centered on the calculated (x, y) + Render.setColourWithAlphaPercent(borderColour, this.alphaPercent); + Render.drawArrow(p.x, p.y, this.heading, mapMode.trailMarkerSize); + Render.setColourWithAlphaPercent(colour, this.alphaPercent); + Render.drawArrow(p.x, p.y, this.heading, mapMode.trailMarkerSize - 1.0); + } + } + } + + private Mw mw; + public LinkedList trailMarkerList = new LinkedList(); + public int maxLength = 30; + public String name; + public boolean enabled; + public long lastMarkerTime = 0; + public long intervalMillis = 5000; + + public Trail(Mw mw, String name) { + this.mw = mw; + this.name = name; + this.enabled = this.mw.config.getOrSetBoolean(Mw.catOptions, this.name + "TrailEnabled", false); + this.maxLength = this.mw.config.getOrSetInt(Mw.catOptions, this.name + "TrailMaxLength", this.maxLength, 1, 200); + this.intervalMillis = (long) this.mw.config.getOrSetInt(Mw.catOptions, this.name + "TrailMarkerIntervalMillis", (int) this.intervalMillis, 100, 360000); + } + + public void close() { + this.mw.config.setBoolean(Mw.catOptions, this.name + "TrailEnabled", this.enabled); + this.mw.config.setInt(Mw.catOptions, this.name + "TrailMaxLength", this.maxLength); + this.mw.config.setInt(Mw.catOptions, this.name + "TrailMarkerIntervalMillis", (int) this.intervalMillis); + this.trailMarkerList.clear(); + } + + // for other types of trails will need to extend Trail and override this method + public void onTick() { + long time = System.currentTimeMillis(); + if ((time - this.lastMarkerTime) > this.intervalMillis) { + this.lastMarkerTime = time; + this.addMarker(this.mw.playerX, this.mw.playerY, this.mw.playerZ, this.mw.playerHeading); + } + } + + public void addMarker(double x, double y, double z, double heading) { + this.trailMarkerList.add(new TrailMarker(x, y, z, heading)); + // remove elements from beginning of list until the list has at most + // maxTrailLength elements + while (this.trailMarkerList.size() > this.maxLength) { + this.trailMarkerList.poll(); + } + int i = this.maxLength - this.trailMarkerList.size(); + for (TrailMarker marker : this.trailMarkerList) { + marker.alphaPercent = (i * 100) / this.maxLength; + i++; + } + } + + public void draw(MapMode mapMode, MapView mapView) { + for (TrailMarker marker : this.trailMarkerList) { + marker.draw(mapMode, mapView); + } + } + + +} diff --git a/src/main/java/mapwriter/map/UndergroundTexture.java b/src/main/java/mapwriter/map/UndergroundTexture.java new file mode 100644 index 0000000..f8d603b --- /dev/null +++ b/src/main/java/mapwriter/map/UndergroundTexture.java @@ -0,0 +1,220 @@ +package mapwriter.map; + +import java.awt.Point; +import java.util.Arrays; + +import mapwriter.Mw; +import mapwriter.Texture; +import mapwriter.region.ChunkRender; +import mapwriter.region.IChunk; +import net.minecraft.block.Block; +import net.minecraft.client.multiplayer.WorldClient; +import net.minecraft.world.chunk.Chunk; + +import org.lwjgl.opengl.GL11; + +public class UndergroundTexture extends Texture { + + private Mw mw; + private int px = 0; + private int py = 0; + private int pz = 0; + private int dimension = 0; + private int updateX; + private int updateZ; + private byte[][] updateFlags = new byte[9][256]; + private Point[] loadedChunkArray; + private int textureSize; + private int textureChunks; + private int[] pixels; + + class RenderChunk implements IChunk { + Chunk chunk; + + public RenderChunk(Chunk chunk) { + this.chunk = chunk; + } + + @Override + public int getMaxY() { + return this.chunk.getTopFilledSegment() + 15; + } + + @Override + public int getBlockAndMetadata(int x, int y, int z) { + Block block = this.chunk.getBlock(x, y, z); + int blockid = Block.blockRegistry.getIDForObject(block); + int meta = this.chunk.getBlockMetadata(x, y, z); + return ((blockid & 0xfff) << 4) | (meta & 0xf); + } + + @Override + public int getBiome(int x, int z) { + return (int) this.chunk.getBiomeArray()[(z * 16) + x]; + } + + @Override + public int getLightValue(int x, int y, int z) { + return this.chunk.getBlockLightValue(x, y, z, 0); + } + } + + public UndergroundTexture(Mw mw, int textureSize, boolean linearScaling) { + super(textureSize, textureSize, 0x00000000, GL11.GL_NEAREST, GL11.GL_NEAREST, GL11.GL_REPEAT); + this.setLinearScaling(false); + this.textureSize = textureSize; + this.textureChunks = textureSize >> 4; + this.loadedChunkArray = new Point[this.textureChunks * this.textureChunks]; + this.pixels = new int[textureSize * textureSize]; + Arrays.fill(this.pixels, 0xff000000); + this.mw = mw; + } + + public void clear() { + Arrays.fill(this.pixels, 0xff000000); + this.updateTexture(); + } + + public void clearChunkPixels(int cx, int cz) { + int tx = (cx << 4) & (this.textureSize - 1); + int tz = (cz << 4) & (this.textureSize - 1); + for (int j = 0; j < 16; j++) { + int offset = ((tz + j) * this.textureSize) + tx; + Arrays.fill(this.pixels, offset, offset + 16, 0xff000000); + } + this.updateTextureArea(tx, tz, 16, 16); + } + + void renderToTexture(int y) { + this.setPixelBufPosition(0); + for (int i = 0; i < this.pixels.length; i++) { + int colour = this.pixels[i]; + int height = (colour >> 24) & 0xff; + int alpha = (y >= height) ? 255 - ((y - height) * 8) : 0; + if (alpha < 0) { + alpha = 0; + } + this.pixelBufPut(((alpha << 24) & 0xff000000) | (colour & 0xffffff)); + } + this.updateTexture(); + } + + public int getLoadedChunkOffset(int cx, int cz) { + int cxOffset = cx & (this.textureChunks - 1); + int czOffset = cz & (this.textureChunks - 1); + return (czOffset * this.textureChunks) + cxOffset; + } + + public void requestView(MapView view) { + int cxMin = ((int) view.getMinX()) >> 4; + int czMin = ((int) view.getMinZ()) >> 4; + int cxMax = ((int) view.getMaxX()) >> 4; + int czMax = ((int) view.getMaxZ()) >> 4; + for (int cz = czMin; cz <= czMax; cz++) { + for (int cx = cxMin; cx <= cxMax; cx++) { + Point requestedChunk = new Point(cx, cz); + int offset = this.getLoadedChunkOffset(cx, cz); + Point currentChunk = this.loadedChunkArray[offset]; + if ((currentChunk == null) || !currentChunk.equals(requestedChunk)) { + this.clearChunkPixels(cx, cz); + this.loadedChunkArray[offset] = requestedChunk; + } + } + } + } + + public boolean isChunkInTexture(int cx, int cz) { + Point requestedChunk = new Point(cx, cz); + int offset = this.getLoadedChunkOffset(cx, cz); + Point chunk = this.loadedChunkArray[offset]; + return (chunk != null) && chunk.equals(requestedChunk); + } + + public void update() { + this.clearFlags(); + + if (this.dimension != this.mw.playerDimension) { + this.clear(); + this.dimension = this.mw.playerDimension; + } + this.px = this.mw.playerXInt; + this.py = this.mw.playerYInt; + this.pz = this.mw.playerZInt; + + this.updateX = (this.px >> 4) - 1; + this.updateZ = (this.pz >> 4) - 1; + + this.processBlock( + this.px - (this.updateX << 4), + this.py, + this.pz - (this.updateZ << 4) + ); + + int cxMax = this.updateX + 2; + int czMax = this.updateZ + 2; + WorldClient world = this.mw.mc.theWorld; + int flagOffset = 0; + for (int cz = this.updateZ; cz <= czMax; cz++) { + for (int cx = this.updateX; cx <= cxMax; cx++) { + if (this.isChunkInTexture(cx, cz)) { + Chunk chunk = world.getChunkFromChunkCoords(cx, cz); + int tx = (cx << 4) & (this.textureSize - 1); + int tz = (cz << 4) & (this.textureSize - 1); + int pixelOffset = (tz * this.textureSize) + tx; + byte[] mask = this.updateFlags[flagOffset]; + ChunkRender.renderUnderground( + this.mw.blockColours, + new RenderChunk(chunk), + this.pixels, pixelOffset, this.textureSize, + this.py, mask + ); + } + flagOffset += 1; + } + } + + this.renderToTexture(this.py + 1); + } + + private void clearFlags() { + for (byte[] chunkFlags : this.updateFlags) { + Arrays.fill(chunkFlags, ChunkRender.FLAG_UNPROCESSED); + } + } + + private void processBlock(int xi, int y, int zi) { + int x = (this.updateX << 4) + xi; + int z = (this.updateZ << 4) + zi; + + int xDist = this.px - x; + int zDist = this.pz - z; + + if (((xDist * xDist) + (zDist * zDist)) <= 256) { + if (this.isChunkInTexture(x >> 4, z >> 4)) { + int chunkOffset = ((zi >> 4) * 3) + (xi >> 4); + int columnXi = xi & 0xf; + int columnZi = zi & 0xf; + int columnOffset = (columnZi << 4) + columnXi; + byte columnFlag = this.updateFlags[chunkOffset][columnOffset]; + + if (columnFlag == ChunkRender.FLAG_UNPROCESSED) { + // if column not yet processed + WorldClient world = this.mw.mc.theWorld; + Block block = world.getBlock(x, y, z); + if ((block == null) || !block.isOpaqueCube()) { + // if block is not opaque + this.updateFlags[chunkOffset][columnOffset] = (byte) ChunkRender.FLAG_NON_OPAQUE; + this.processBlock(xi + 1, y, zi); + this.processBlock(xi - 1, y, zi); + this.processBlock(xi, y, zi + 1); + this.processBlock(xi, y, zi - 1); + } else { + // block is opaque + this.updateFlags[chunkOffset][columnOffset] = (byte) ChunkRender.FLAG_OPAQUE; + } + } + } + } + } + +} diff --git a/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java new file mode 100644 index 0000000..6a99055 --- /dev/null +++ b/src/main/java/mapwriter/map/mapmode/FullScreenMapMode.java @@ -0,0 +1,26 @@ +package mapwriter.map.mapmode; + +import mapwriter.forge.MwConfig; + +public class FullScreenMapMode extends MapMode { + public FullScreenMapMode(MwConfig config) { + super(config, "fullScreenMap"); + + this.heightPercent = -1; + this.marginTop = 0; + this.marginBottom = 0; + this.marginLeft = 0; + this.marginRight = 0; + + this.borderMode = 0; + this.playerArrowSize = 5; + this.markerSize = 5; + this.alphaPercent = 100; + + this.rotate = false; + this.circular = false; + this.coordsEnabled = false; + + this.loadConfig(); + } +} diff --git a/src/main/java/mapwriter/map/mapmode/LargeMapMode.java b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java new file mode 100644 index 0000000..191ee8b --- /dev/null +++ b/src/main/java/mapwriter/map/mapmode/LargeMapMode.java @@ -0,0 +1,22 @@ +package mapwriter.map.mapmode; + +import mapwriter.forge.MwConfig; + +public class LargeMapMode extends MapMode { + public LargeMapMode(MwConfig config) { + super(config, "largeMap"); + + this.heightPercent = -1; + this.marginTop = 10; + this.marginBottom = 40; + this.marginLeft = 40; + this.marginRight = 40; + + this.playerArrowSize = 5; + this.markerSize = 5; + + this.coordsEnabled = true; + + this.loadConfig(); + } +} diff --git a/src/main/java/mapwriter/map/mapmode/MapMode.java b/src/main/java/mapwriter/map/mapmode/MapMode.java new file mode 100644 index 0000000..2be8dc3 --- /dev/null +++ b/src/main/java/mapwriter/map/mapmode/MapMode.java @@ -0,0 +1,254 @@ +package mapwriter.map.mapmode; + +import java.awt.Point; + +import mapwriter.forge.MwConfig; +import mapwriter.map.MapView; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.ScaledResolution; + +public class MapMode { + private final MwConfig config; + public final String configCategory; + + private int sw = 320; + private int sh = 240; + private double screenScalingFactor = 1.0; + + // calculated before every frame drawn by updateMapDimensions + public int xTranslation = 0; + public int yTranslation = 0; + public int x = -25; + public int y = -25; + public int w = 50; + public int h = 50; + public int wPixels = 50; + public int hPixels = 50; + + // config settings + public boolean enabled = true; + public boolean rotate = true; + public boolean circular = true; + public boolean coordsEnabled = false; + public int borderMode = 1; + public int playerArrowSize = 5; + public int markerSize = 5; + public int trailMarkerSize = 3; + public int alphaPercent = 100; + + public int marginTop = 0; + public int marginBottom = 0; + public int marginLeft = 0; + public int marginRight = 0; + public int heightPercent = -1; + + public int textX = 0; + public int textY = 0; + public int textColour = 0xffffffff; + + public MapMode(MwConfig config, String configCategory) { + this.config = config; + this.configCategory = configCategory; + } + + public void loadConfig() { + // get options from config file + this.enabled = this.config.getOrSetBoolean(this.configCategory, "enabled", this.enabled); + this.playerArrowSize = this.config.getOrSetInt(this.configCategory, "playerArrowSize", this.playerArrowSize, 1, 20); + this.markerSize = this.config.getOrSetInt(this.configCategory, "markerSize", this.markerSize, 1, 20); + this.alphaPercent = this.config.getOrSetInt(this.configCategory, "alphaPercent", this.alphaPercent, 0, 100); + + this.heightPercent = this.config.getOrSetInt(this.configCategory, "heightPercent", this.heightPercent, 0, 100); + this.marginTop = this.config.getOrSetInt(this.configCategory, "marginTop", this.marginTop, -1, 320); + this.marginBottom = this.config.getOrSetInt(this.configCategory, "marginBottom", this.marginBottom, -1, 320); + this.marginLeft = this.config.getOrSetInt(this.configCategory, "marginLeft", this.marginLeft, -1, 320); + this.marginRight = this.config.getOrSetInt(this.configCategory, "marginRight", this.marginRight, -1, 320); + + this.rotate = this.config.getOrSetBoolean(this.configCategory, "rotate", this.rotate); + this.circular = this.config.getOrSetBoolean(this.configCategory, "circular", this.circular); + this.coordsEnabled = this.config.getOrSetBoolean(this.configCategory, "coordsEnabled", this.coordsEnabled); + this.borderMode = this.config.getOrSetInt(this.configCategory, "borderMode", this.borderMode, 0, 1); + + this.trailMarkerSize = Math.max(1, this.markerSize - 1); + } + + public void saveConfig() { + this.config.setBoolean(this.configCategory, "enabled", this.enabled); + this.config.setInt(this.configCategory, "heightPercent", this.heightPercent); + this.config.setInt(this.configCategory, "marginTop", this.marginTop); + this.config.setInt(this.configCategory, "marginBottom", this.marginBottom); + this.config.setInt(this.configCategory, "marginLeft", this.marginLeft); + this.config.setInt(this.configCategory, "marginRight", this.marginRight); + this.config.setBoolean(this.configCategory, "rotate", this.rotate); + this.config.setBoolean(this.configCategory, "circular", this.circular); + } + + public void close() { + this.saveConfig(); + } + + public void setScreenRes(int dw, int dh, int sw, int sh, double scaling) { + if ((sw != this.sw) || (sh != this.sh) || (scaling != this.screenScalingFactor)) { + this.sw = sw; + this.sh = sh; + this.screenScalingFactor = scaling; + this.update(); + } + } + + public void setScreenRes() { + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution sRes = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight); + this.setScreenRes(mc.displayWidth, mc.displayHeight, sRes.getScaledWidth(), sRes.getScaledHeight(), sRes.getScaleFactor()); + } + + public void setMargins(int marginTop, int marginBottom, int marginLeft, int marginRight) { + this.marginTop = marginTop; + this.marginBottom = marginBottom; + this.marginLeft = marginLeft; + this.marginRight = marginRight; + this.update(); + } + + public void setHeightPercent(int heightPercent) { + this.heightPercent = heightPercent; + this.update(); + } + + public void toggleHeightPercent() { + int i = (this.heightPercent / 5) + 1; + if (i > 12) { + i = 1; + } + this.setHeightPercent(i * 5); + } + + private void update() { + int size = (this.sh * this.heightPercent) / 100; + int x, y; + + // calculate map x position and width + if ((this.marginLeft >= 0) && (this.marginRight >= 0)) { + x = this.marginLeft; + this.w = this.sw - this.marginLeft - this.marginRight; + } else if (this.marginLeft >= 0) { + x = this.marginLeft; + this.w = size; + } else if (this.marginRight >= 0) { + x = this.sw - size - this.marginRight; + this.w = size; + } else { + x = (this.sw - size) / 2; + this.w = size; + } + + // calculate map y position and height + if ((this.marginTop >= 0) && (this.marginBottom >= 0)) { + y = this.marginTop; + this.h = this.sh - this.marginTop - this.marginBottom; + } else if (this.marginTop >= 0) { + y = this.marginTop; + this.h = size; + } else if (this.marginBottom >= 0) { + y = this.sh - size - this.marginBottom; + this.h = size; + } else { + y = (this.sh - size) / 2; + this.h = size; + } + + // make sure width and height are multiples of 2 + this.w &= -2; + this.h &= -2; + + this.xTranslation = x + (this.w >> 1); + this.yTranslation = y + (this.h >> 1); + + if (this.circular) { + this.w = this.h; + } + + this.x = -(this.w >> 1); + this.y = -(this.h >> 1); + + this.wPixels = (int) Math.round(((double) this.w) * this.screenScalingFactor); + this.hPixels = (int) Math.round(((double) this.h) * this.screenScalingFactor); + + // calculate coords display location + this.textX = 0; + this.textY = (this.h >> 1) + 4; + + //MwUtil.log("MapMode: map = %d %d %d %d, screen = %d %d", this.x, this.y, this.w, this.h, this.sw, this.sh); + //MwUtil.log("MapMode: margins = left %d, right %d, top %d, bottom %d, size = %d", + // this.marginLeft, this.marginRight, this.marginTop, this.marginBottom, size); + } + + public void setRotating(boolean enabled) { + this.rotate = enabled; + this.circular = enabled; + this.update(); + } + + public boolean toggleRotating() { + this.setRotating(!this.rotate); + return this.rotate; + } + + public Point screenXYtoBlockXZ(MapView mapView, int sx, int sy) { + double withinMapX = ((double) (sx - this.xTranslation)) / ((double) this.w); + double withinMapY = ((double) (sy - this.yTranslation)) / ((double) this.h); + int bx = (int) Math.floor((mapView.getX() + (withinMapX * mapView.getWidth()))); + int bz = (int) Math.floor((mapView.getZ() + (withinMapY * mapView.getHeight()))); + return new Point(bx, bz); + } + + public Point.Double blockXZtoScreenXY(MapView mapView, double bX, double bZ) { + double xNorm = (bX - mapView.getX()) / mapView.getWidth(); + double zNorm = (bZ - mapView.getZ()) / mapView.getHeight(); + return new Point.Double(this.w * xNorm, this.h * zNorm); + } + + public Point.Double getClampedScreenXY(MapView mapView, double bX, double bZ) { + double xRel = (bX - mapView.getX()) / mapView.getWidth(); + double zRel = (bZ - mapView.getZ()) / mapView.getHeight(); + double limit = 0.49; + + if (!this.circular) { + if (xRel < -limit) { + zRel = -limit * zRel / xRel; + xRel = -limit; + } + if (xRel > limit) { + zRel = limit * zRel / xRel; + xRel = limit; + } + if (zRel < -limit) { + xRel = -limit * xRel / zRel; + zRel = -limit; + } + if (zRel > limit) { + xRel = limit * xRel / zRel; + zRel = limit; + } + if (xRel < -limit) { + zRel = -limit * zRel / xRel; + xRel = -limit; + } + if (xRel > limit) { + zRel = limit * zRel / xRel; + xRel = limit; + } + } else { + double dSq = (xRel * xRel) + (zRel * zRel); + if (dSq > (limit * limit)) { + double a = Math.atan2(zRel, xRel); + xRel = limit * Math.cos(a); + zRel = limit * Math.sin(a); + } + } + + // multiply by the overlay size and add the overlay position to + // get the position within the overlay in screen coordinates + return new Point.Double(this.w * xRel, this.h * zRel); + } +} diff --git a/src/main/java/mapwriter/map/mapmode/SmallMapMode.java b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java new file mode 100644 index 0000000..20f4fd8 --- /dev/null +++ b/src/main/java/mapwriter/map/mapmode/SmallMapMode.java @@ -0,0 +1,22 @@ +package mapwriter.map.mapmode; + +import mapwriter.forge.MwConfig; + +public class SmallMapMode extends MapMode { + public SmallMapMode(MwConfig config) { + super(config, "smallMap"); + + this.heightPercent = 30; + this.marginTop = 10; + this.marginBottom = -1; + this.marginLeft = -1; + this.marginRight = 10; + + this.playerArrowSize = 4; + this.markerSize = 3; + + this.coordsEnabled = true; + + this.loadConfig(); + } +} diff --git a/src/main/java/mapwriter/overlay/OverlayChecker.java b/src/main/java/mapwriter/overlay/OverlayChecker.java new file mode 100644 index 0000000..62c6847 --- /dev/null +++ b/src/main/java/mapwriter/overlay/OverlayChecker.java @@ -0,0 +1,115 @@ +package mapwriter.overlay; + +import java.awt.Point; +import java.util.ArrayList; + +import mapwriter.api.IMwChunkOverlay; +import mapwriter.api.IMwDataProvider; +import mapwriter.map.MapView; +import mapwriter.map.mapmode.MapMode; +import net.minecraft.util.MathHelper; + +public class OverlayChecker implements IMwDataProvider { + + public class ChunkOverlay implements IMwChunkOverlay{ + + Point coord; + + public ChunkOverlay(int x, int z){ + this.coord = new Point(x, z); + } + + @Override + public Point getCoordinates() { return this.coord; } + + @Override + public int getColor() { return 0x90ffffff; } + + @Override + public float getFilling() { return 1.0f; } + + @Override + public boolean hasBorder() { return true; } + + @Override + public float getBorderWidth() { return 0.5f; } + + @Override + public int getBorderColor() { return 0xff000000; } + + } + + @Override + public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) { + + // We should pass the center of the map too to reduce the display like in this case + // and the zoom lvl, to provide higher level informations + + int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; + int minChunkZ = (MathHelper.ceiling_double_int(minZ) >> 4) - 1; + int maxChunkX = (MathHelper.ceiling_double_int(maxX) >> 4) + 1; + int maxChunkZ = (MathHelper.ceiling_double_int(maxZ) >> 4) + 1; + int cX = (MathHelper.ceiling_double_int(centerX) >> 4) + 1; + int cZ = (MathHelper.ceiling_double_int(centerZ) >> 4) + 1; + + int limitMinX = Math.max(minChunkX, cX - 100); + int limitMaxX = Math.min(maxChunkX, cX + 100); + int limitMinZ = Math.max(minChunkZ, cZ - 100); + int limitMaxZ = Math.min(maxChunkZ, cZ + 100); + + ArrayList chunks = new ArrayList(); + for (int x = limitMinX; x <= limitMaxX; x++) + for (int z = limitMinZ; z <= limitMaxZ; z++){ + if ((x+z)%2 == 0) + chunks.add(new ChunkOverlay(x, z)); + }; + + return chunks; + } + + @Override + public String getStatusString(int dim, int bX, int bY, int bZ) { return ""; } + + @Override + public void onMiddleClick(int dim, int bX, int bZ, MapView mapview){ } + + @Override + public void onDimensionChanged(int dimension, MapView mapview) { } + + @Override + public void onMapCenterChanged(double vX, double vZ, MapView mapview) { + // TODO Auto-generated method stub + + } + + @Override + public void onZoomChanged(int level, MapView mapview) { + // TODO Auto-generated method stub + + } + + @Override + public void onOverlayActivated(MapView mapview) { + // TODO Auto-generated method stub + + } + + @Override + public void onOverlayDeactivated(MapView mapview) { + // TODO Auto-generated method stub + + } + + @Override + public void onDraw(MapView mapview, MapMode mapmode) { + // TODO Auto-generated method stub + + } + + @Override + public boolean onMouseInput(MapView mapview, MapMode mapmode) { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/src/main/java/mapwriter/overlay/OverlayGrid.java b/src/main/java/mapwriter/overlay/OverlayGrid.java new file mode 100644 index 0000000..68ae31b --- /dev/null +++ b/src/main/java/mapwriter/overlay/OverlayGrid.java @@ -0,0 +1,109 @@ +package mapwriter.overlay; + +import java.awt.Point; +import java.util.ArrayList; + +import mapwriter.api.IMwChunkOverlay; +import mapwriter.api.IMwDataProvider; +import mapwriter.map.MapView; +import mapwriter.map.mapmode.MapMode; +import net.minecraft.util.MathHelper; + +public class OverlayGrid implements IMwDataProvider { + + public class ChunkOverlay implements IMwChunkOverlay{ + + Point coord; + + public ChunkOverlay(int x, int z){ + this.coord = new Point(x, z); + } + + @Override + public Point getCoordinates() { return this.coord; } + + @Override + public int getColor() { return 0x00ffffff; } + + @Override + public float getFilling() { return 1.0f; } + + @Override + public boolean hasBorder() { return true; } + + @Override + public float getBorderWidth() { return 0.5f; } + + @Override + public int getBorderColor() { return 0xff000000; } + + } + + @Override + public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) { + int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; + int minChunkZ = (MathHelper.ceiling_double_int(minZ) >> 4) - 1; + int maxChunkX = (MathHelper.ceiling_double_int(maxX) >> 4) + 1; + int maxChunkZ = (MathHelper.ceiling_double_int(maxZ) >> 4) + 1; + int cX = (MathHelper.ceiling_double_int(centerX) >> 4) + 1; + int cZ = (MathHelper.ceiling_double_int(centerZ) >> 4) + 1; + + int limitMinX = Math.max(minChunkX, cX - 100); + int limitMaxX = Math.min(maxChunkX, cX + 100); + int limitMinZ = Math.max(minChunkZ, cZ - 100); + int limitMaxZ = Math.min(maxChunkZ, cZ + 100); + + ArrayList chunks = new ArrayList(); + for (int x = limitMinX; x <= limitMaxX; x++) + for (int z = limitMinZ; z <= limitMaxZ; z++) + chunks.add(new ChunkOverlay(x, z)); + + return chunks; + } + + @Override + public String getStatusString(int dim, int bX, int bY, int bZ) { return ""; } + + @Override + public void onMiddleClick(int dim, int bX, int bZ, MapView mapview){ } + + @Override + public void onDimensionChanged(int dimension, MapView mapview) { } + + @Override + public void onMapCenterChanged(double vX, double vZ, MapView mapview) { + // TODO Auto-generated method stub + + } + + @Override + public void onZoomChanged(int level, MapView mapview) { + // TODO Auto-generated method stub + + } + + @Override + public void onOverlayActivated(MapView mapview) { + // TODO Auto-generated method stub + + } + + @Override + public void onOverlayDeactivated(MapView mapview) { + // TODO Auto-generated method stub + + } + + @Override + public void onDraw(MapView mapview, MapMode mapmode) { + // TODO Auto-generated method stub + + } + + @Override + public boolean onMouseInput(MapView mapview, MapMode mapmode) { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/src/main/java/mapwriter/overlay/OverlaySlime.java b/src/main/java/mapwriter/overlay/OverlaySlime.java new file mode 100644 index 0000000..5233a0d --- /dev/null +++ b/src/main/java/mapwriter/overlay/OverlaySlime.java @@ -0,0 +1,157 @@ +package mapwriter.overlay; + +import mapwriter.api.IMwChunkOverlay; +import mapwriter.api.IMwDataProvider; +import mapwriter.map.MapView; +import mapwriter.map.mapmode.MapMode; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.util.MathHelper; + +import java.awt.*; +import java.util.ArrayList; +import java.util.Random; + +public class OverlaySlime implements IMwDataProvider { + + public static boolean seedFound = false; + public static boolean seedAsked = false; + private static long seed = -1; + + public static void setSeed(long seed){ + OverlaySlime.seed = seed; + OverlaySlime.seedFound = true; + } + + public static void askSeed(){ + EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer; + if(player == null) return; + player.sendChatMessage("/seed"); //Send the /seed command to the server + seedAsked = true; + } + + public static void reset(){ + seedFound = false; + seedAsked = false; + seed = -1; + } + + public class ChunkOverlay implements IMwChunkOverlay{ + + Point coord; + + public ChunkOverlay(int x, int z){ + this.coord = new Point(x, z); + } + + @Override + public Point getCoordinates() { return this.coord; } + + @Override + public int getColor() { return 0x5000ff00; } + + @Override + public float getFilling() { return 1.0f; } + + @Override + public boolean hasBorder() { return true; } + + @Override + public float getBorderWidth() { return 0.5f; } + + @Override + public int getBorderColor() { return 0xff000000; } + + } + + @Override + public ArrayList getChunksOverlay(int dim, double centerX, double centerZ, double minX, double minZ, double maxX, double maxZ) { + + // We should pass the center of the map too to reduce the display like in this case + // and the zoom lvl, to provide higher level informations + + if (Minecraft.getMinecraft().thePlayer.getEntityWorld().provider.dimensionId != dim) + return new ArrayList(); + + int minChunkX = (MathHelper.ceiling_double_int(minX) >> 4) - 1; + int minChunkZ = (MathHelper.ceiling_double_int(minZ) >> 4) - 1; + int maxChunkX = (MathHelper.ceiling_double_int(maxX) >> 4) + 1; + int maxChunkZ = (MathHelper.ceiling_double_int(maxZ) >> 4) + 1; + int cX = (MathHelper.ceiling_double_int(centerX) >> 4) + 1; + int cZ = (MathHelper.ceiling_double_int(centerZ) >> 4) + 1; + + int limitMinX = Math.max(minChunkX, cX - 100); + int limitMaxX = Math.min(maxChunkX, cX + 100); + int limitMinZ = Math.max(minChunkZ, cZ - 100); + int limitMaxZ = Math.min(maxChunkZ, cZ + 100); + + if(!seedFound && !seedAsked){ + //We don't have the seed and we didn't ask for it yet. Let's go! + askSeed(); + } + + ArrayList chunks = new ArrayList(); + if(seedFound){ //If we know the seed, then add the overlay + for (int x = limitMinX; x <= limitMaxX; x++) + for (int z = limitMinZ; z <= limitMaxZ; z++){ + + Random rnd = new Random(seed + + (long) (x * x * 0x4c1906) + + (long) (x * 0x5ac0db) + + (long) (z * z) * 0x4307a7L + + (long) (z * 0x5f24f) ^ 0x3ad8025f); + if (rnd.nextInt(10) == 0){ + chunks.add(new ChunkOverlay(x, z)); + } + } + } + + return chunks; + } + + @Override + public String getStatusString(int dim, int bX, int bY, int bZ) { return ""; } + + @Override + public void onMiddleClick(int dim, int bX, int bZ, MapView mapview){ } + + @Override + public void onDimensionChanged(int dimension, MapView mapview) { } + + @Override + public void onMapCenterChanged(double vX, double vZ, MapView mapview) { + // TODO Auto-generated method stub + + } + + @Override + public void onZoomChanged(int level, MapView mapview) { + // TODO Auto-generated method stub + + } + + @Override + public void onOverlayActivated(MapView mapview) { + // TODO Auto-generated method stub + + } + + @Override + public void onOverlayDeactivated(MapView mapview) { + // TODO Auto-generated method stub + + } + + @Override + public void onDraw(MapView mapview, MapMode mapmode) { + // TODO Auto-generated method stub + + } + + @Override + public boolean onMouseInput(MapView mapview, MapMode mapmode) { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/src/main/java/mapwriter/region/BlockColours.java b/src/main/java/mapwriter/region/BlockColours.java new file mode 100644 index 0000000..0a32a37 --- /dev/null +++ b/src/main/java/mapwriter/region/BlockColours.java @@ -0,0 +1,464 @@ +package mapwriter.region; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Scanner; + +public class BlockColours { + + public static final int MAX_BLOCKS = 4096; + public static final int MAX_META = 16; + public static final int MAX_BIOMES = 256; + + public static final String biomeSectionString = "[biomes]"; + public static final String blockSectionString = "[blocks]"; + + private int[] bcArray = new int[MAX_BLOCKS * MAX_META]; + private int[] waterMultiplierArray = new int[MAX_BIOMES]; + private int[] grassMultiplierArray = new int[MAX_BIOMES]; + private int[] foliageMultiplierArray = new int[MAX_BIOMES]; + + public enum BlockType { + NORMAL, + GRASS, + LEAVES, + FOLIAGE, + WATER, + OPAQUE + } + + private BlockType[] blockTypeArray = new BlockType[MAX_BLOCKS * MAX_META]; + + public BlockColours() { + Arrays.fill(this.bcArray, 0); + Arrays.fill(this.waterMultiplierArray, 0xffffff); + Arrays.fill(this.grassMultiplierArray, 0xffffff); + Arrays.fill(this.foliageMultiplierArray, 0xffffff); + Arrays.fill(this.blockTypeArray, BlockType.NORMAL); + } + + public int getColour(int blockAndMeta) { + return this.bcArray[blockAndMeta & 0xffff]; + } + + public void setColour(int blockAndMeta, int colour) { + this.bcArray[blockAndMeta & 0xffff] = colour; + } + + public int getColour(int blockID, int meta) { + return this.bcArray[((blockID & 0xfff) << 4) | (meta & 0xf)]; + } + + public void setColour(int blockID, int meta, int colour) { + this.bcArray[((blockID & 0xfff) << 4) | (meta & 0xf)] = colour; + } + + private int getGrassColourMultiplier(int biome) { + return (this.grassMultiplierArray != null) && (biome >= 0) && (biome < this.grassMultiplierArray.length) ? + this.grassMultiplierArray[biome] : 0xffffff; + } + + private int getWaterColourMultiplier(int biome) { + return (this.waterMultiplierArray != null) && (biome >= 0) && (biome < this.waterMultiplierArray.length) ? + this.waterMultiplierArray[biome] : 0xffffff; + } + + private int getFoliageColourMultiplier(int biome) { + return (this.foliageMultiplierArray != null) && (biome >= 0) && (biome < this.foliageMultiplierArray.length) ? + this.foliageMultiplierArray[biome] : 0xffffff; + } + + public int getBiomeColour(int blockAndMeta, int biome) { + blockAndMeta &= 0xffff; + int colourMultiplier; + switch(this.blockTypeArray[blockAndMeta]) { + case GRASS: + colourMultiplier = getGrassColourMultiplier(biome); + break; + case LEAVES: + case FOLIAGE: + colourMultiplier = getFoliageColourMultiplier(biome); + break; + case WATER: + colourMultiplier = getWaterColourMultiplier(biome); + break; + default: + colourMultiplier = 0xffffff; + break; + } + return colourMultiplier; + } + + public void setBiomeWaterShading(int biomeID, int colour) { + this.waterMultiplierArray[biomeID & 0xff] = colour; + } + + public void setBiomeGrassShading(int biomeID, int colour) { + this.grassMultiplierArray[biomeID & 0xff] = colour; + } + + public void setBiomeFoliageShading(int biomeID, int colour) { + this.foliageMultiplierArray[biomeID & 0xff] = colour; + } + + private static BlockType getBlockTypeFromString(String typeString) { + BlockType blockType = BlockType.NORMAL; + if (typeString.equalsIgnoreCase("normal")) { + blockType = BlockType.NORMAL; + } else if (typeString.equalsIgnoreCase("grass")) { + blockType = BlockType.GRASS; + } else if (typeString.equalsIgnoreCase("leaves")) { + blockType = BlockType.LEAVES; + } else if (typeString.equalsIgnoreCase("foliage")) { + blockType = BlockType.FOLIAGE; + } else if (typeString.equalsIgnoreCase("water")) { + blockType = BlockType.WATER; + } else if (typeString.equalsIgnoreCase("opaque")) { + blockType = BlockType.OPAQUE; + } else { + RegionManager.logWarning("unknown block type '%s'", typeString); + } + return blockType; + } + + private static String getBlockTypeAsString(BlockType blockType) { + String s = "normal"; + switch (blockType) { + case NORMAL: + s = "normal"; + break; + case GRASS: + s = "grass"; + break; + case LEAVES: + s = "leaves"; + break; + case FOLIAGE: + s = "foliage"; + break; + case WATER: + s = "water"; + break; + case OPAQUE: + s = "opaque"; + break; + } + return s; + } + + public BlockType getBlockType(int blockAndMeta) { + return this.blockTypeArray[blockAndMeta & 0xffff]; + } + + public BlockType getBlockType(int blockId, int meta) { + return this.blockTypeArray[((blockId & 0xfff) << 4) | (meta & 0xf)]; + } + + public void setBlockType(int blockId, int meta, BlockType type) { + this.blockTypeArray[((blockId & 0xfff) << 4) | (meta & 0xf)] = type; + } + + public void setBlockType(int blockAndMeta, BlockType type) { + this.blockTypeArray[blockAndMeta & 0xffff] = type; + } + + public static int getColourFromString(String s) { + return (int) (Long.parseLong(s, 16) & 0xffffffffL); + } + + // + // Methods for loading block colours from file: + // + + // read biome colour multiplier values. + // line format is: + // biome + // accepts "*" wildcard for biome id (meaning for all biomes). + private void loadBiomeLine(String[] split) { + try { + int startBiomeId = 0; + int endBiomeId = MAX_BIOMES; + if (!split[1].equals("*")) { + startBiomeId = Integer.parseInt(split[1]); + endBiomeId = startBiomeId + 1; + } + + if ((startBiomeId >= 0) && (startBiomeId < MAX_BIOMES)) { + int waterMultiplier = getColourFromString(split[2]) & 0xffffff; + int grassMultiplier = getColourFromString(split[3]) & 0xffffff; + int foliageMultiplier = getColourFromString(split[4]) & 0xffffff; + + for (int biomeId = startBiomeId; biomeId < endBiomeId; biomeId++) { + this.setBiomeWaterShading(biomeId, waterMultiplier); + this.setBiomeGrassShading(biomeId, grassMultiplier); + this.setBiomeFoliageShading(biomeId, foliageMultiplier); + } + } else { + RegionManager.logWarning("biome ID '%d' out of range", startBiomeId); + } + + } catch (NumberFormatException e) { + RegionManager.logWarning("invalid biome colour line '%s %s %s %s %s'", split[0], split[1], split[2], split[3], split[4]); + } + } + + // read block colour values. + // line format is: + // block + // the biome id, meta value, and colour code are in hex. + // accepts "*" wildcard for biome id and meta (meaning for all blocks and/or meta values). + private void loadBlockLine(String[] split, boolean isBlockColourLine) { + try { + int startBlockId = 0; + int endBlockId = MAX_BLOCKS; + if (!split[1].equals("*")) { + startBlockId = Integer.parseInt(split[1]); + endBlockId = startBlockId + 1; + } + + int startBlockMeta = 0; + int endBlockMeta = MAX_META; + if (!split[2].equals("*")) { + startBlockMeta = Integer.parseInt(split[2]); + endBlockMeta = startBlockMeta + 1; + } + + if ((startBlockId >= 0) && (startBlockId < MAX_BLOCKS) && (startBlockMeta >= 0) && (startBlockMeta < MAX_META)) { + if (isBlockColourLine) { + // block colour line + int colour = getColourFromString(split[3]); + + for (int blockId = startBlockId; blockId < endBlockId; blockId++) { + for (int blockMeta = startBlockMeta; blockMeta < endBlockMeta; blockMeta++) { + this.setColour(blockId, blockMeta, colour); + } + } + } else { + // block type line + BlockType type = getBlockTypeFromString(split[3]); + + for (int blockId = startBlockId; blockId < endBlockId; blockId++) { + for (int blockMeta = startBlockMeta; blockMeta < endBlockMeta; blockMeta++) { + this.setBlockType(blockId, blockMeta, type); + } + } + } + } + + } catch (NumberFormatException e) { + RegionManager.logWarning("invalid block colour line '%s %s %s %s'", split[0], split[1], split[2], split[3]); + } + } + + public void loadFromFile(File f) { + Scanner fin = null; + try { + fin = new Scanner(new FileReader(f)); + + while (fin.hasNextLine()) { + // get next line and remove comments (part of line after #) + String line = fin.nextLine().split("#")[0].trim(); + if (line.length() > 0) { + String[] lineSplit = line.split(" "); + if (lineSplit[0].equals("biome") && (lineSplit.length == 5)) { + this.loadBiomeLine(lineSplit); + } else if (lineSplit[0].equals("block") && (lineSplit.length == 4)) { + this.loadBlockLine(lineSplit, true); + } else if (lineSplit[0].equals("blocktype") && (lineSplit.length == 4)) { + this.loadBlockLine(lineSplit, false); + } else { + RegionManager.logWarning("invalid map colour line '%s'", line); + } + } + } + } catch (IOException e) { + RegionManager.logError("loading block colours: no such file '%s'", f); + + } finally { + if (fin != null) { + fin.close(); + } + } + } + + // + // Methods for saving block colours to file. + // + + // save biome colour multipliers to a file. + public void saveBiomes(Writer fout) throws IOException { + fout.write("biome * ffffff ffffff ffffff\n"); + + for (int biomeId = 0; biomeId < MAX_BIOMES; biomeId++) { + int waterMultiplier = this.getWaterColourMultiplier(biomeId) & 0xffffff; + int grassMultiplier = this.getGrassColourMultiplier(biomeId) & 0xffffff; + int foliageMultiplier = this.getFoliageColourMultiplier(biomeId) & 0xffffff; + + // don't add lines that are covered by the default. + if ((waterMultiplier != 0xffffff) || (grassMultiplier != 0xffffff) || (foliageMultiplier != 0xffffff)) { + fout.write(String.format("biome %d %06x %06x %06x\n", biomeId, waterMultiplier, grassMultiplier, foliageMultiplier)); + } + } + } + + private static String getMostOccurringKey(Map map, String defaultItem) { + // find the most commonly occurring key in a hash map. + // only return a key if there is more than 1. + int maxCount = 1; + String mostOccurringKey = defaultItem; + for (Entry entry : map.entrySet()) { + String key = entry.getKey(); + int count = entry.getValue(); + + if (count > maxCount) { + maxCount = count; + mostOccurringKey = key; + } + } + + return mostOccurringKey; + } + + // to use the least number of lines possible find the most commonly occurring + // item for the 16 different meta values of a block. + // an 'item' is either a block colour or a block type. + // the most commonly occurring item is then used as the wildcard entry for + // the block, and all non matching items added afterwards. + private static void writeMinimalBlockLines(Writer fout, String lineStart, String[] items, String defaultItem) throws IOException { + + Map frequencyMap = new HashMap(); + + // first count the number of occurrences of each item. + for (String item : items) { + int count = 0; + if (frequencyMap.containsKey(item)) { + count = frequencyMap.get(item); + } + frequencyMap.put(item, count + 1); + } + + // then find the most commonly occurring item. + String mostOccurringItem = getMostOccurringKey(frequencyMap, defaultItem); + + // only add a wildcard line if it actually saves lines. + if (!mostOccurringItem.equals(defaultItem)) { + fout.write(String.format("%s * %s\n", lineStart, mostOccurringItem)); + } + + // add lines for items that don't match the wildcard line. + for (int i = 0; i < items.length; i++) { + if (!items[i].equals(mostOccurringItem) && !items[i].equals(defaultItem)) { + fout.write(String.format("%s %d %s\n", lineStart, i, items[i])); + } + } + } + + public void saveBlocks(Writer fout) throws IOException { + fout.write("block * * 00000000\n"); + + String[] colours = new String[MAX_META]; + + for (int blockId = 0; blockId < MAX_BLOCKS; blockId++) { + // build a 16 element list of block colours + for (int meta = 0; meta < MAX_META; meta++) { + colours[meta] = String.format("%08x", this.getColour(blockId, meta)); + } + // write a minimal representation to the file + String lineStart = String.format("block %d", blockId); + writeMinimalBlockLines(fout, lineStart, colours, "00000000"); + } + } + + public void saveBlockTypes(Writer fout) throws IOException { + fout.write("blocktype * * normal\n"); + + String[] blockTypes = new String[MAX_META]; + + for (int blockId = 0; blockId < MAX_BLOCKS; blockId++) { + // build a 16 element list of block types + for (int meta = 0; meta < MAX_META; meta++) { + BlockType bt = this.getBlockType(blockId, meta); + blockTypes[meta] = getBlockTypeAsString(bt); + } + // write a minimal representation to the file + String lineStart = String.format("blocktype %d", blockId); + writeMinimalBlockLines(fout, lineStart, blockTypes, "normal"); + } + } + + // save block colours and biome colour multipliers to a file. + public void saveToFile(File f) { + Writer fout = null; + try { + fout = new OutputStreamWriter(new FileOutputStream(f)); + this.saveBiomes(fout); + this.saveBlockTypes(fout); + this.saveBlocks(fout); + + } catch (IOException e) { + RegionManager.logError("saving block colours: could not write to '%s'", f); + + } finally { + if (fout != null) { + try { + fout.close(); + } catch (IOException e) {} + } + } + } + + public static void writeOverridesFile(File f) { + Writer fout = null; + try { + fout = new OutputStreamWriter(new FileOutputStream(f)); + + fout.write( + "block 37 * 60ffff00 # make dandelions more yellow\n" + + "block 38 * 60ff0000 # make roses more red\n" + + "blocktype 2 * grass # grass block\n" + + "blocktype 8 * water # still water block\n" + + "blocktype 9 * water # flowing water block\n" + + "blocktype 18 * leaves # leaves block\n" + + "blocktype 18 1 opaque # pine leaves (not biome colorized)\n" + + "blocktype 18 2 opaque # birch leaves (not biome colorized)\n" + + "blocktype 31 * grass # tall grass block\n" + + "blocktype 106 * foliage # vines block\n" + + "blocktype 169 * grass # biomes o plenty holy grass\n" + + "blocktype 1920 * grass # biomes o plenty plant\n" + + "blocktype 1923 * opaque # biomes o plenty leaves 1\n" + + "blocktype 1924 * opaque # biomes o plenty leaves 2\n" + + "blocktype 1925 * foliage # biomes o plenty foliage\n" + + "blocktype 1926 * opaque # biomes o plenty fruit leaf block\n" + + "blocktype 1932 * foliage # biomes o plenty tree moss\n" + + "blocktype 1962 * leaves # biomes o plenty colorized leaves\n" + + "blocktype 2164 * leaves # twilight forest leaves\n" + + "blocktype 2177 * leaves # twilight forest magic leaves\n" + + "blocktype 2204 * leaves # extrabiomesXL green leaves\n" + + "blocktype 2200 * opaque # extrabiomesXL autumn leaves\n" + + "blocktype 3257 * opaque # natura berry bush\n" + + "blocktype 3272 * opaque # natura darkwood leaves\n" + + "blocktype 3259 * leaves # natura flora leaves\n" + + "blocktype 3278 * opaque # natura rare leaves\n" + + "blocktype 3258 * opaque # natura sakura leaves\n" + ); + + } catch (IOException e) { + RegionManager.logError("saving block overrides: could not write to '%s'", f); + + } finally { + if (fout != null) { + try { + fout.close(); + } catch (IOException e) {} + } + } + } +} diff --git a/src/main/java/mapwriter/region/ChunkRender.java b/src/main/java/mapwriter/region/ChunkRender.java new file mode 100644 index 0000000..6dc7934 --- /dev/null +++ b/src/main/java/mapwriter/region/ChunkRender.java @@ -0,0 +1,211 @@ +package mapwriter.region; + +public class ChunkRender { + + public static final byte FLAG_UNPROCESSED = 0; + public static final byte FLAG_NON_OPAQUE = 1; + public static final byte FLAG_OPAQUE = 2; + + + // values that change how height shading algorithm works + public static final double brightenExponent = 0.35; + public static final double darkenExponent = 0.35; + public static final double brightenAmplitude = 0.7; + public static final double darkenAmplitude = 1.4; + + // get the height shading of a pixel. + // requires the pixel to the west and the pixel to the north to have their + // heights stored in the alpha channel to work. + // the "height" of a pixel is the y value of the first opaque block in + // the block column that created the pixel. + // height values of 0 and 255 are ignored as these are used as the clear + // values for pixels. + public static double getHeightShading(int height, int heightW, int heightN) { + int samples = 0; + int heightDiff = 0; + + if ((heightW > 0) && (heightW < 255)) { + heightDiff += height - heightW; + samples++; + } + + if ((heightN > 0) && (heightN < 255)) { + heightDiff += height - heightN; + samples++; + } + + double heightDiffFactor = 0.0; + if (samples > 0) { + heightDiffFactor = (double) heightDiff / ((double) samples * 255.0); + } + + // emphasize small differences in height, but as the difference in height increases, + // don't increase so much + // TODO: probably more accurate to use atan here rather than a fractional + // exponent. + return (heightDiffFactor >= 0.0) ? + Math.pow(heightDiffFactor, brightenExponent) * brightenAmplitude : + -Math.pow(-heightDiffFactor, darkenExponent) * darkenAmplitude; + } + + // calculate the colour of a pixel by alpha blending the colour of each block + // in a column until an opaque block is reached. + // y is topmost block height to start rendering at. + // for maps without a ceiling y is simply the height of the highest block in that chunk. + // for maps with a ceiling y is the height of the first non opaque block starting from + // the ceiling. + // + // for every block in the column starting from the highest: + // - get the block colour + // - get the biome shading + // - extract colour components as doubles in the range [0.0, 1.0] + // - the shaded block colour is simply the block colour multiplied + // by the biome shading for each component + // - this shaded block colour is alpha blended with the running + // colour for this column + // + // so the final map colour is an alpha blended stack of all the + // individual shaded block colours in the sequence [yStart .. yEnd] + // + // note that the "front to back" alpha blending algorithm is used + // rather than the more common "back to front". + // + public static int getColumnColour(BlockColours bc, IChunk chunk, int x, int y, int z, int heightW, int heightN) { + double a = 1.0; + double r = 0.0; + double g = 0.0; + double b = 0.0; + for (; y > 0; y--) { + int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); + + int c1 = bc.getColour(blockAndMeta); + int alpha = (c1 >> 24) & 0xff; + // no need to process block if it is transparent + if (alpha > 0) { + int biome = chunk.getBiome(x, z); + int c2 = bc.getBiomeColour(blockAndMeta, biome); + + // extract colour components as normalized doubles + double c1A = (double) (alpha) / 255.0; + double c1R = (double) ((c1 >> 16) & 0xff) / 255.0; + double c1G = (double) ((c1 >> 8) & 0xff) / 255.0; + double c1B = (double) ((c1 >> 0) & 0xff) / 255.0; + + // c2A is implicitly 1.0 (opaque) + double c2R = (double) ((c2 >> 16) & 0xff) / 255.0; + double c2G = (double) ((c2 >> 8) & 0xff) / 255.0; + double c2B = (double) ((c2 >> 0) & 0xff) / 255.0; + + // alpha blend and multiply + r = r + (a * c1A * c1R * c2R); + g = g + (a * c1A * c1G * c2G); + b = b + (a * c1A * c1B * c2B); + a = a * (1.0 - c1A); + } + // break when an opaque block is encountered + if (alpha == 0xff) { + break; + } + } + + /* + // darken blocks depending on how far away they are from this depth slice + if (depth != 0) { + int bottomOfSlice = maxHeight - ((depth + 1) * maxHeight / Mw.HEIGHT_LEVELS) - 1; + if (yRange[0] < bottomOfSlice) { + shading *= 1.0 - 2.0 * ((double) (bottomOfSlice - yRange[0]) / (double) maxHeight); + } + }*/ + + double heightShading = getHeightShading(y, heightW, heightN); + int lightValue = chunk.getLightValue(x, y + 1, z); + double lightShading = (double) lightValue / 15.0; + double shading = (heightShading + 1.0) * lightShading; + + // apply the shading + r = Math.min(Math.max(0.0, r * shading), 1.0); + g = Math.min(Math.max(0.0, g * shading), 1.0); + b = Math.min(Math.max(0.0, b * shading), 1.0); + + // now we have our final RGB values as doubles, convert to a packed ARGB pixel. + return ((y & 0xff) << 24) | + ((((int) (r * 255.0)) & 0xff) << 16) | + ((((int) (g * 255.0)) & 0xff) << 8) | + ((((int) (b * 255.0)) & 0xff)); + } + + static int getPixelHeightN(int[] pixels, int offset, int scanSize) { + return (offset >= scanSize) ? ((pixels[offset - scanSize] >> 24) & 0xff) : -1; + } + + static int getPixelHeightW(int[] pixels, int offset, int scanSize) { + return ((offset & (scanSize - 1)) >= 1) ? ((pixels[offset - 1] >> 24) & 0xff) : -1; + } + + public static void renderSurface(BlockColours bc, IChunk chunk, int[] pixels, int offset, int scanSize, boolean dimensionHasCeiling) { + int chunkMaxY = chunk.getMaxY(); + for (int z = 0; z < MwChunk.SIZE; z++) { + for (int x = 0; x < MwChunk.SIZE; x++) { + // for the nether dimension search for the first non-opaque + // block below the ceiling. + // cannot use y = chunkMaxY as the nether sometimes spawns + // mushrooms above the ceiling height. this fixes the + // rectangular grey areas (ceiling bedrock) on the nether map. + int y; + if (dimensionHasCeiling) { + for (y = 127; y >= 0; y--) { + int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); + int alpha = (bc.getColour(blockAndMeta) >> 24) & 0xff; + if (alpha != 0xff) { + break; + } + } + } else { + y = chunkMaxY; + } + + int pixelOffset = offset + (z * scanSize) + x; + pixels[pixelOffset] = getColumnColour( + bc, chunk, x, y, z, + getPixelHeightW(pixels, pixelOffset, scanSize), + getPixelHeightN(pixels, pixelOffset, scanSize) + ); + } + } + } + + public static void renderUnderground(BlockColours bc, IChunk chunk, int[] pixels, int offset, int scanSize, int startY, byte[] mask) { + startY = Math.min(Math.max(0, startY), 255); + for (int z = 0; z < MwChunk.SIZE; z++) { + for (int x = 0; x < MwChunk.SIZE; x++) { + + // only process columns where the mask bit is set. + // process all columns if mask is null. + if ((mask != null) && ((mask[(z * 16) + x]) != FLAG_NON_OPAQUE)) { + continue; + } + + // get the last non transparent block before the first opaque block searching + // towards the sky from startY + int lastNonTransparentY = startY; + for (int y = startY; y < chunk.getMaxY(); y++) { + int blockAndMeta = chunk.getBlockAndMetadata(x, y, z); + int alpha = (bc.getColour(blockAndMeta) >> 24) & 0xff; + if (alpha == 0xff) { + break; + } + if (alpha > 0) { + lastNonTransparentY = y; + } + } + + int pixelOffset = offset + (z * scanSize) + x; + pixels[pixelOffset] = getColumnColour( + bc, chunk, x, lastNonTransparentY, z, + getPixelHeightW(pixels, pixelOffset, scanSize), + getPixelHeightN(pixels, pixelOffset, scanSize) + ); + } + } + } +} diff --git a/src/main/java/mapwriter/region/IChunk.java b/src/main/java/mapwriter/region/IChunk.java new file mode 100644 index 0000000..f85bf4b --- /dev/null +++ b/src/main/java/mapwriter/region/IChunk.java @@ -0,0 +1,8 @@ +package mapwriter.region; + +public interface IChunk { + public int getBlockAndMetadata(int x, int y, int z); + public int getBiome(int x, int z); + public int getLightValue(int x, int y, int z); + public int getMaxY(); +} diff --git a/src/main/java/mapwriter/region/MergeToImage.java b/src/main/java/mapwriter/region/MergeToImage.java new file mode 100644 index 0000000..79ac3cb --- /dev/null +++ b/src/main/java/mapwriter/region/MergeToImage.java @@ -0,0 +1,92 @@ +package mapwriter.region; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; + +import javax.imageio.ImageIO; + +public class MergeToImage { + public static final int MAX_WIDTH = 8192; + public static final int MAX_HEIGHT = 8192; + + public static BufferedImage mergeRegions(RegionManager regionManager, int x, int z, int w, int h, int dimension) { + // create the image and graphics context + // this is the most likely place to run out of memory + BufferedImage mergedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); + + // copy region PNGs to the image + for (int zi = 0; zi < h; zi += Region.SIZE) { + for (int xi = 0; xi < w; xi += Region.SIZE) { + //MwUtil.log("merging region (%d,%d)", rX << Mw.REGION_SHIFT, rZ << Mw.REGION_SHIFT); + + // get region pixels + Region region = regionManager.getRegion(x + xi, z + zi, 0, dimension); + int[] regionPixels = region.surfacePixels.getPixels(); + if (regionPixels != null) { + mergedImage.setRGB(xi, zi, Region.SIZE, Region.SIZE, regionPixels, 0, Region.SIZE); + } + } + } + + return mergedImage; + } + + public static boolean writeImage(BufferedImage img, File f) { + boolean error = true; + try { + ImageIO.write(img, "png", f); + error = false; + } catch (IOException e) { + } + return error; + } + + public static int merge(RegionManager regionManager, int xCentre, int zCentre, int w, int h, int dimension, File dir, String basename) { + + // round up to nearest 512 block boundary + w = ((w + Region.SIZE - 1) & Region.MASK); + h = ((h + Region.SIZE - 1) & Region.MASK); + + // clamp to an integer between 512 and 8192 inclusive + w = Math.max(Region.SIZE, w); + h = Math.max(Region.SIZE, h); + + int xMin = xCentre - (w / 2); + int zMin = zCentre - (h / 2); + + // round to nearest region boundary + xMin = Math.round(((float) xMin) / ((float) Region.SIZE)) * Region.SIZE; + zMin = Math.round(((float) zMin) / ((float) Region.SIZE)) * Region.SIZE; + + int xMax = xMin + w; + int zMax = zMin + h; + + RegionManager.logInfo("merging area starting at (%d,%d), %dx%d blocks", + xMin, zMin, w, h); + + + int countZ = 0; + int count = 0; + for (int z = zMin; z < zMax; z += MAX_WIDTH) { + int imgH = Math.min(zMax - z, MAX_HEIGHT); + int countX = 0; + for (int x = xMin; x < xMax; x += MAX_WIDTH) { + int imgW = Math.min(xMax - x, MAX_WIDTH); + + String imgName = String.format("%s.%d.%d.png", basename, countX, countZ); + File f = new File(dir, imgName); + RegionManager.logInfo("merging regions to image %s", f); + + BufferedImage img = mergeRegions(regionManager, x, z, imgW, imgH, dimension); + writeImage(img, f); + + countX++; + count++; + } + countZ++; + } + + return count; + } +} diff --git a/src/main/java/mapwriter/region/MwChunk.java b/src/main/java/mapwriter/region/MwChunk.java new file mode 100644 index 0000000..7a0ab72 --- /dev/null +++ b/src/main/java/mapwriter/region/MwChunk.java @@ -0,0 +1,234 @@ +package mapwriter.region; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +public class MwChunk implements IChunk { + public static final int SIZE = 16; + + public final int x; + public final int z; + public final int dimension; + + public final byte[][] msbArray; + public final byte[][] lsbArray; + public final byte[][] metaArray; + public final byte[][] lightingArray; + + public final byte[] biomeArray; + + public final int maxY; + + public MwChunk(int x, int z, int dimension, byte[][] msbArray, byte[][] lsbArray, byte[][] metaArray, byte[][] lightingArray, byte[] biomeArray) { + this.x = x; + this.z = z; + this.dimension = dimension; + this.msbArray = msbArray; + this.lsbArray = lsbArray; + this.metaArray = metaArray; + this.biomeArray = biomeArray; + this.lightingArray = lightingArray; + int maxY = 0; + for (int y = 0; y < 16; y++) { + if (lsbArray[y] != null) { + maxY = (y << 4) + 15; + } + } + this.maxY = maxY; + } + + public String toString() { + return String.format("(%d, %d) dim%d", this.x, this.z, this.dimension); + } + + // load from anvil file + public static MwChunk read(int x, int z, int dimension, RegionFileCache regionFileCache) { + + byte[] biomeArray = null; + byte[][] msbArray = new byte[16][]; + byte[][] lsbArray = new byte[16][]; + byte[][] metaArray = new byte[16][]; + byte[][] lightingArray = new byte[16][]; + + DataInputStream dis = null; + RegionFile regionFile = regionFileCache.getRegionFile(x << 4, z << 4, dimension); + if (!regionFile.isOpen()) { + if (regionFile.exists()) { + regionFile.open(); + } + } + + if (regionFile.isOpen()) { + dis = regionFile.getChunkDataInputStream(x & 31, z & 31); + } + + if (dis != null) { + try { + + //chunk NBT structure: + // + //COMPOUND "" + //COMPOUND "level" + // INT "xPos" + // INT "zPos" + // LONG "LastUpdate" + // BYTE "TerrainPopulated" + // BYTE_ARRAY "Biomes" + // INT_ARRAY "HeightMap" + // LIST(COMPOUND) "Sections" + // BYTE "Y" + // BYTE_ARRAY "Blocks" + // BYTE_ARRAY "Add" + // BYTE_ARRAY "Data" + // BYTE_ARRAY "BlockLight" + // BYTE_ARRAY "SkyLight" + // END + // LIST(COMPOUND) "Entities" + // LIST(COMPOUND) "TileEntities" + // LIST(COMPOUND) "TileTicks" + //END + //END + + Nbt root = Nbt.readNextElement(dis); + Nbt level = root.getChild("Level"); + + int xNbt = level.getChild("xPos").getInt(); + int zNbt = level.getChild("zPos").getInt(); + if ((xNbt != x) || (zNbt != z)) { + RegionManager.logWarning("chunk (%d, %d) has NBT coords (%d, %d)", x, z, xNbt, zNbt); + } + + Nbt sections = level.getChild("Sections"); + + // loop through each of the sections (16 x 16 x 16 block volumes) present + for (int i = 0; i < sections.size(); i++) { + Nbt section = sections.getChild(i); + if (!section.isNull()) { + int y = section.getChild("Y").getByte(); + lsbArray[y & 0xf] = section.getChild("Blocks").getByteArray(); + msbArray[y & 0xf] = section.getChild("Add").getByteArray(); + metaArray[y & 0xf] = section.getChild("Data").getByteArray(); + } + } + biomeArray = level.getChild("Biomes").getByteArray(); + + } catch (IOException e) { + RegionManager.logError("%s: could not read chunk (%d, %d) from region file\n", e, x, z); + } finally { + try { dis.close(); } + catch (IOException e) { + RegionManager.logError("MwChunk.read: %s while closing input stream", e); + } + } + //this.log("MwChunk.read: chunk (%d, %d) empty=%b", this.x, this.z, empty); + } else { + //this.log("MwChunk.read: chunk (%d, %d) input stream is null", this.x, this.z); + } + + return new MwChunk(x, z, dimension, msbArray, lsbArray, metaArray, lightingArray, biomeArray); + } + + public boolean isEmpty() { + return (this.maxY <= 0); + } + + public int getBiome(int x, int z) { + return (this.biomeArray != null) ? (int) (this.biomeArray[((z & 0xf) << 4) | (x & 0xf)]) & 0xff : 0; + } + + public int getLightValue(int x, int y, int z) { + //int yi = (y >> 4) & 0xf; + //int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); + + //int light = ((this.lightingArray != null) && (this.lightingArray[yi] != null)) ? this.lightingArray[yi][offset >> 1] : 15; + + //return ((offset & 1) == 1) ? ((light >> 4) & 0xf) : (light & 0xf); + return 15; + } + + public int getMaxY() { + return this.maxY; + } + + public int getBlockAndMetadata(int x, int y, int z) { + int yi = (y >> 4) & 0xf; + int offset = ((y & 0xf) << 8) | ((z & 0xf) << 4) | (x & 0xf); + + int lsb = ((this.lsbArray != null) && (this.lsbArray[yi] != null)) ? this.lsbArray[yi][offset] : 0; + int msb = ((this.msbArray != null) && (this.msbArray[yi] != null)) ? this.msbArray[yi][offset >> 1] : 0; + int meta = ((this.metaArray != null) && (this.metaArray[yi] != null)) ? this.metaArray[yi][offset >> 1] : 0; + + return ((offset & 1) == 1) ? + ((msb & 0xf0) << 8) | ((lsb & 0xff) << 4) | ((meta & 0xf0) >> 4) : + ((msb & 0x0f) << 12) | ((lsb & 0xff) << 4) | (meta & 0x0f); + } + + public Nbt getNbt() { + Nbt sections = new Nbt(Nbt.TAG_LIST, "Sections", null); + + for (int y = 0; y < 16; y++) { + Nbt section = new Nbt(Nbt.TAG_COMPOUND, "", null); + + section.addChild(new Nbt(Nbt.TAG_BYTE, "Y", (byte) y)); + + if ((this.lsbArray != null) && (this.lsbArray[y] != null)) { + section.addChild(new Nbt(Nbt.TAG_BYTE_ARRAY, "Blocks", this.lsbArray[y])); + } + if ((this.msbArray != null) && (this.msbArray[y] != null)) { + section.addChild(new Nbt(Nbt.TAG_BYTE_ARRAY, "Add", this.msbArray[y])); + } + if ((this.metaArray != null) && (this.metaArray[y] != null)) { + section.addChild(new Nbt(Nbt.TAG_BYTE_ARRAY, "Data", this.metaArray[y])); + } + + sections.addChild(section); + } + + Nbt level = new Nbt(Nbt.TAG_COMPOUND, "Level", null); + level.addChild(new Nbt(Nbt.TAG_INT, "xPos", this.x)); + level.addChild(new Nbt(Nbt.TAG_INT, "zPos", this.z)); + level.addChild(sections); + + if (this.biomeArray != null) { + level.addChild(new Nbt(Nbt.TAG_BYTE_ARRAY, "Biomes", this.biomeArray)); + } + + Nbt root = new Nbt(Nbt.TAG_COMPOUND, "", null); + root.addChild(level); + + return root; + } + + public synchronized boolean write(RegionFileCache regionFileCache) { + boolean error = false; + RegionFile regionFile = regionFileCache.getRegionFile(this.x << 4, this.z << 4, this.dimension); + if (!regionFile.isOpen()) { + error = regionFile.open(); + } + if (!error) { + DataOutputStream dos = regionFile.getChunkDataOutputStream(this.x & 31, this.z & 31); + if (dos != null) { + Nbt chunkNbt = this.getNbt(); + try { + //RegionManager.logInfo("writing chunk (%d, %d) to region file", this.x, this.z); + chunkNbt.writeElement(dos); + } catch (IOException e) { + RegionManager.logError("%s: could not write chunk (%d, %d) to region file", e, this.x, this.z); + error = true; + } finally { + try { dos.close(); } + catch (IOException e) { + RegionManager.logError("%s while closing chunk data output stream", e); + } + } + } else { + RegionManager.logError("error: could not get output stream for chunk (%d, %d)", this.x, this.z); + } + } else { + RegionManager.logError("error: could not open region file for chunk (%d, %d)", this.x, this.z); + } + + return error; + } +} diff --git a/src/main/java/mapwriter/region/Nbt.java b/src/main/java/mapwriter/region/Nbt.java new file mode 100644 index 0000000..62603cf --- /dev/null +++ b/src/main/java/mapwriter/region/Nbt.java @@ -0,0 +1,364 @@ +package mapwriter.region; + + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Nbt { + + // each NBT element has the structure: + // byte tag_id + // short name_length + // byte[name_length] name + // + // use int for tag ID's rather than byte so we can have -1 as + // a 'null' or empty element + // + // tag ID's: + public static final byte TAG_END = 0x00; + public static final byte TAG_BYTE = 0x01; + public static final byte TAG_SHORT = 0x02; + public static final byte TAG_INT = 0x03; + public static final byte TAG_LONG = 0x04; + public static final byte TAG_FLOAT = 0x05; + public static final byte TAG_DOUBLE = 0x06; + public static final byte TAG_BYTE_ARRAY = 0x07; // INT length, then length BYTE's + public static final byte TAG_STRING = 0x08; // SHORT length, UTF-8 string + public static final byte TAG_LIST = 0x09; // BYTE entry id, INT entry count, entries (without tag or name) + public static final byte TAG_COMPOUND = 0x0a; // fully formed tags, ending at TAG_END + public static final byte TAG_INT_ARRAY = 0x0b; // INT length, length INT's + + public static final byte TAG_NULL = -1; + + public static Nbt nullElement = new Nbt(TAG_NULL, "", null); + + public byte tagID; + public String name; + private Object data; + + public Nbt(byte tagID, String name, Object data) { + this.tagID = tagID; + this.name = name; + this.data = data; + } + + public boolean isNull() { + return (this.tagID == TAG_NULL); + } + + public void addChild(Nbt child) { + // for list structures + if (this.tagID == TAG_LIST) { + if (this.data == null) { + this.data = new ArrayList(); + } + @SuppressWarnings("unchecked") + List childrenList = (List) this.data; + childrenList.add(child); + } + + // for compound structures + if (this.tagID == TAG_COMPOUND) { + if (this.data == null) { + this.data = new HashMap(); + } + @SuppressWarnings("unchecked") + Map childrenMap = (Map) this.data; + childrenMap.put(child.name, child); + } + } + + // getChild methods allow for invocation chaining. + // e.g. int child10Data = elem.getChildOrEmpty(10).getInt() + + // for lists, get the child element at index 'index' + public Nbt getChild(int index) { + Nbt child = null; + if ((this.tagID == TAG_LIST) && (this.data != null)) { + @SuppressWarnings("unchecked") + List childrenList = (List) this.data; + if ((index >= 0) && (index < childrenList.size())) { + child = childrenList.get(index); + } + } + return (child != null) ? (child) : (nullElement); + } + + // for compound tags, returns the child with name 'name' + public Nbt getChild(String name) { + Nbt child = null; + if ((this.tagID == TAG_COMPOUND) && (this.data != null)) { + @SuppressWarnings("unchecked") + Map childrenMap = (Map) this.data; + child = childrenMap.get(name); + } + return (child != null) ? (child) : (nullElement); + } + + // for lists, get number of children + public int size() { + int size = 0; + if ((this.tagID == TAG_LIST) && (this.data != null)) { + @SuppressWarnings("unchecked") + List childrenList = (List) this.data; + size = childrenList.size(); + } + return size; + } + + /*public static String readString(DataInputStream dis) throws IOException { + int stringLength = (int) dis.readShort(); + byte[] stringBytes = null; + String s = ""; + if (stringLength > 0) { + stringBytes = new byte[stringLength]; + s = dis.readUTF(); + try { + s = new String(stringBytes, "UTF8"); + } catch (Exception e) { + e.printStackTrace(); + s = ""; + } + } + return s; + } + + public static void writeString(DataOutputStream dos, String s) throws IOException { + dos.writeShort((short) s.length()); + byte[] stringBytes = null; + try { + dos.write(s.getBytes("UTF8")); + } catch (Exception e) { + e.printStackTrace(); + } + }*/ + + public static Nbt readNextElement(DataInputStream dis) throws IOException { + byte tagID; + String name = ""; + + // fully formed tag + tagID = (byte) dis.readByte(); + if (tagID != TAG_END) { + // END tags do not have a name + name = dis.readUTF(); + } + + return readElementData(dis, tagID, name); + } + + // parse the next nbt tag in the data buffer + public static Nbt readElementData(DataInputStream dis, byte tagID, String name) throws IOException{ + Nbt elem = null; + switch (tagID) { + case TAG_END: + //System.out.format("encountered end tag at %d\n", buffer.position()); + break; + case TAG_BYTE: + elem = new Nbt(tagID, name, new Byte(dis.readByte())); + break; + case TAG_SHORT: + elem = new Nbt(tagID, name, new Short(dis.readShort())); + break; + case TAG_INT: + elem = new Nbt(tagID, name, new Integer(dis.readInt())); + break; + case TAG_FLOAT: + elem = new Nbt(tagID, name, new Float(dis.readFloat())); + break; + case TAG_LONG: + elem = new Nbt(tagID, name, new Long(dis.readLong())); + break; + case TAG_DOUBLE: + elem = new Nbt(tagID, name, new Double(dis.readDouble())); + break; + + case TAG_BYTE_ARRAY: + int baLength = dis.readInt(); + byte[] byteArray = null; + if (baLength > 0) { + byteArray = new byte[baLength]; + dis.readFully(byteArray); + } + elem = new Nbt(tagID, name, byteArray); + break; + + case TAG_INT_ARRAY: + int iaLength = dis.readInt(); + int[] intArray = null; + if (iaLength > 0) { + intArray = new int[iaLength]; + for (int i = 0; i < iaLength; i++) { + intArray[i] = dis.readInt(); + } + } + elem = new Nbt(tagID, name, intArray); + break; + + case TAG_STRING: + elem = new Nbt(tagID, name, dis.readUTF()); + break; + + case TAG_LIST: + byte childType = dis.readByte(); + int listLength = dis.readInt(); + elem = new Nbt(tagID, name, null); + //System.out.format("encountered list tag at %d, childType %d, length %d\n", buffer.position(), childType, listLength); + for (int i = 0; i < listLength; i++) { + Nbt child = readElementData(dis, childType, ""); + elem.addChild(child); + } + break; + + case TAG_COMPOUND: + elem = new Nbt(tagID, name, null); + boolean end = false; + while (!end) { + Nbt child = readNextElement(dis); + if (child.isNull()) { + end = true; + } else { + elem.addChild(child); + } + } + break; + + default: + System.out.format("error: encountered unknown tag id\n"); + break; + } + + return (elem != null) ? elem : nullElement; + } + + public byte getByte() { + return ((this.tagID == TAG_BYTE) && (this.data != null)) ? ((Byte) this.data) : ((byte) 0); + } + + public short getShort() { + return ((this.tagID == TAG_SHORT) && (this.data != null)) ? ((Short) this.data) : ((short) 0); + } + + public int getInt() { + return ((this.tagID == TAG_INT) && (this.data != null)) ? ((Integer) this.data) : ((int) 0); + } + + public long getLong() { + return ((this.tagID == TAG_LONG) && (this.data != null)) ? ((Long) this.data) : ((long) 0); + } + + public float getFloat() { + return ((this.tagID == TAG_FLOAT) && (this.data != null)) ? ((Float) this.data) : ((float) 0); + } + + public double getDouble() { + return ((this.tagID == TAG_DOUBLE) && (this.data != null)) ? ((Double) this.data) : ((double) 0); + } + + public byte[] getByteArray() { + return ((this.tagID == TAG_BYTE_ARRAY) && (this.data != null)) ? ((byte[]) this.data) : (null); + } + + public int[] getIntArray() { + return ((this.tagID == TAG_INT_ARRAY) && (this.data != null)) ? ((int[]) this.data) : (null); + } + + public String getString() { + return ((this.tagID == TAG_STRING) && (this.data != null)) ? ((String) this.data) : (null); + } + + + public void writeElement(DataOutputStream dos) throws IOException{ + dos.writeByte(this.tagID); + if (this.tagID != TAG_END) { + dos.writeUTF(this.name); + this.writeElementData(dos); + } + } + + public void writeElementData(DataOutputStream dos) throws IOException { + //Mw.log("Nbt.writeElementData: %02x '%s'", this.tagID, this.name); + switch (this.tagID) { + case TAG_END: + break; + case TAG_BYTE: + dos.writeByte(this.getByte()); + break; + case TAG_SHORT: + dos.writeShort(this.getShort()); + break; + case TAG_INT: + dos.writeInt(this.getInt()); + break; + case TAG_FLOAT: + dos.writeFloat(this.getFloat()); + break; + case TAG_LONG: + dos.writeLong(this.getLong()); + break; + case TAG_DOUBLE: + dos.writeDouble(this.getDouble()); + break; + + case TAG_BYTE_ARRAY: + byte[] byteArray = this.getByteArray(); + if (byteArray != null) { + dos.writeInt(byteArray.length); + dos.write(byteArray); + } else { + dos.writeInt(0); + } + break; + + case TAG_INT_ARRAY: + int[] intArray = this.getIntArray(); + if (intArray != null) { + dos.writeInt(intArray.length); + for (int i = 0; i < intArray.length; i++) { + dos.writeInt(intArray[i]); + } + } else { + dos.writeInt(0); + } + break; + + case TAG_STRING: + dos.writeUTF(this.getString()); + break; + + case TAG_LIST: + int listLength = this.size(); + if (this.size() > 0) { + dos.writeByte(this.getChild(0).tagID); + dos.writeInt(listLength); + for (int i = 0; i < listLength; i++) { + this.getChild(i).writeElementData(dos); + } + } else { + dos.writeByte(TAG_BYTE); + dos.writeInt(0); + } + break; + + case TAG_COMPOUND: + @SuppressWarnings("unchecked") + Map childrenMap = (Map) this.data; + for (Nbt child : childrenMap.values()) { + if (child != null) { + child.writeElement(dos); + } + } + dos.writeByte(TAG_END); + break; + + default: + System.out.format("error: encountered unknown tag id\n"); + break; + } + } +} \ No newline at end of file diff --git a/src/main/java/mapwriter/region/Region.java b/src/main/java/mapwriter/region/Region.java new file mode 100644 index 0000000..29e3491 --- /dev/null +++ b/src/main/java/mapwriter/region/Region.java @@ -0,0 +1,169 @@ +package mapwriter.region; + +import java.io.File; + +/* + MwRegion class + Represents a 32x32 chunk area (512x512 blocks). +*/ +public class Region { + + public RegionManager regionManager; + + public static final int SHIFT = 9; + public static final int SIZE = 1 << SHIFT; + public static final int MASK = -SIZE; + + public final int x; + public final int z; + public final int dimension; + public final int zoomLevel; + public final Long key; + public final int size; + + public SurfacePixels surfacePixels; + + public Region(RegionManager regionManager, int x, int z, int zoomLevel, int dimension) { + + this.regionManager = regionManager; + + this.zoomLevel = Math.min(Math.max(0, zoomLevel), regionManager.maxZoom); + this.dimension = dimension; + this.size = Region.SIZE << zoomLevel; + this.x = x & (-this.size); + this.z = z & (-this.size); + + this.key = getKey(this.x, this.z, this.zoomLevel, this.dimension); + + File surfaceImageFile = this.getImageFile(); + this.surfacePixels = new SurfacePixels(this, surfaceImageFile); + } + + public void close() { + this.surfacePixels.close(); + } + + public void clear() { + this.surfacePixels.clear(); + } + + public String toString() { + return String.format("(%d,%d) z%d dim%d", this.x, this.z, this.zoomLevel, this.dimension); + } + + private static File addDimensionDirToPath(File dir, int dimension) { + if (dimension != 0) { + dir = new File(dir, "DIM" + dimension); + } + return dir; + } + + public File getImageFile() { + File dimDir = addDimensionDirToPath(this.regionManager.imageDir, this.dimension); + File zoomDir = new File(dimDir, "z" + this.zoomLevel); + + zoomDir.mkdirs(); + + String filename = String.format("%d.%d.png", + this.x >> (Region.SHIFT + this.zoomLevel), + this.z >> (Region.SHIFT + this.zoomLevel) + ); + + return new File(zoomDir, filename); + } + + public boolean equals(int x, int z, int zoomLevel, int dimension) { + x &= -this.size; + z &= -this.size; + return (this.x == x) && (this.z == z) && (this.zoomLevel == zoomLevel) && (this.dimension == dimension); + } + + @Override + public boolean equals(Object o) { + boolean equal = false; + if (o != null) { + if (o instanceof Region) { + Region region = (Region) o; + equal = this.equals(region.x, region.z, region.zoomLevel, region.dimension); + } + } + return equal; + } + + public static Long getKey(int x, int z, int zoomLevel, int dimension) { + x = (x >> (Region.SHIFT + zoomLevel)) & 0xffff; + z = (z >> (Region.SHIFT + zoomLevel)) & 0xffff; + zoomLevel = zoomLevel & 0xff; + dimension = dimension & 0xff; + return Long.valueOf( + (((long) dimension) << 40) | + (((long) zoomLevel) << 32) | + (((long) z) << 16) | + ((long) x)); + } + + public int getPixelOffset(int x, int z) { + return (((z >> this.zoomLevel) & (Region.SIZE - 1)) << Region.SHIFT) + + ((x >> this.zoomLevel) & (Region.SIZE - 1)); + } + + public int[] getPixels() { + return this.surfacePixels.getPixels(); + } + + public boolean isAreaWithin(int x, int z, int w, int h, int dimension) { + return (x >= this.x) && (z >= this.z) && + ((x + w) <= (this.x + this.size)) && ((z + h) <= (this.z + this.size)) && + (dimension == this.dimension); + } + + // scale an area of pixels by half in this region and write them + // to the pixels of the next zoom level region. + // x, z, w, h, in world block coordinates + // returns the region the scaled pixels were written to, or null + // on failure. + public Region updateNextZoomLevel(int x, int z, int w, int h) { + int[] srcPixels = this.surfacePixels.getPixels(); + Region dstRegion = null; + if (srcPixels != null) { + int dstZoomLevel = this.zoomLevel + 1; + if (dstZoomLevel <= this.regionManager.maxZoom) { + dstRegion = this.regionManager.getRegion(x, z, dstZoomLevel, this.dimension); + int dstW = Math.max(1, (w >> dstRegion.zoomLevel)); + int dstH = Math.max(1, (h >> dstRegion.zoomLevel)); + + // AND srcX and srcZ by -2 (0xfffffffe) to make sure that + // they are always even. This prevents out of bounds exceptions + // at higher zoom levels. + int srcX = (x >> this.zoomLevel) & (Region.SIZE - 1) & (-2); + int srcZ = (z >> this.zoomLevel) & (Region.SIZE - 1) & (-2); + int dstX = (x >> dstRegion.zoomLevel) & (Region.SIZE - 1); + int dstZ = (z >> dstRegion.zoomLevel) & (Region.SIZE - 1); + + dstRegion.surfacePixels.updateScaled(srcPixels, srcX, srcZ, dstX, dstZ, dstW, dstH); + } + } + + return dstRegion; + } + + // update all higher zoom level regions that this region + // lies within + public void updateZoomLevels(int x, int z, int w, int h) { + Region nextRegion = this; + while (nextRegion != null) { + nextRegion = nextRegion.updateNextZoomLevel(x, z, w, h); + } + } + + // update this entire region in the next zoom level + public void updateZoomLevels() { + this.updateZoomLevels(this.x, this.z, this.size, this.size); + } + + public void updateChunk(MwChunk chunk) { + if (this.zoomLevel == 0) { + this.surfacePixels.updateChunk(chunk); + } + } +} diff --git a/src/main/java/mapwriter/region/RegionFile.java b/src/main/java/mapwriter/region/RegionFile.java new file mode 100644 index 0000000..2804783 --- /dev/null +++ b/src/main/java/mapwriter/region/RegionFile.java @@ -0,0 +1,372 @@ +package mapwriter.region; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.zip.DeflaterOutputStream; +import java.util.zip.InflaterInputStream; + +/* +Anvil region file reader/writer implementation. +This code is very similar to RegionFile and RegionFileChunkBuffer from Minecraft. +Not sure if it would have been better just to use the Minecraft code. +*/ + +public class RegionFile { + + private final File file; + private int lengthInSectors = 0; + private RandomAccessFile fin = null; + + private Section[] chunkSectionsArray = new Section[4096]; + private int[] timestampArray = new int[4096]; + private List filledSectorArray = null; + + private class Section { + final int startSector; + final int length; + Section(int startSector, int length) { + this.startSector = startSector; + this.length = length; + } + Section(int sectorAndSize) { + this((sectorAndSize >> 8) & 0xffffff, sectorAndSize & 0xff); + } + int getSectorAndSize() { + return (this.startSector << 8) | (this.length & 0xff); + } + } + + public RegionFile(File file) { + this.file = file; + } + + public String toString() { + return String.format("%s", this.file); + } + + public boolean exists() { + return this.file.isFile(); + } + + public boolean isOpen() { + return (this.fin != null); + } + + // set the corresponding bits in filledSectorArray to 'filled' + // for 'count' sectors, starting at 'firstSector'. + private void setFilledSectorArray(Section section, boolean filled) { + int endSector = section.startSector + section.length; + int sectorsToAppend = endSector + 1 - this.filledSectorArray.size(); + for (int i = 0; i < sectorsToAppend; i++) { + this.filledSectorArray.add(Boolean.valueOf(false)); + } + for (int i = section.startSector; i < endSector; i++) { + if (filled && this.filledSectorArray.get(i)) { + RegionManager.logError("sector %d already filled, possible chunk overlap", i); + } + this.filledSectorArray.set(i, Boolean.valueOf(filled)); + } + } + + private boolean checkSectionOverlaps(Section section) { + // get end sector, limiting to length of the filled sector array as all sectors past the + // end of the file are assumed free. + int endSector = Math.min(section.startSector + section.length, this.filledSectorArray.size()); + boolean overlaps = false; + for (int i = section.startSector; i < endSector; i++) { + if (this.filledSectorArray.get(i)) { + overlaps = true; + } + } + return overlaps; + } + + private Section getFreeSection(int requiredLength) { + int start = 0; + int length = 0; + int closestStart = 0; + int closestLength = Integer.MAX_VALUE; + // start at 2 to skip headers + int i; + for (i = 2; i < this.filledSectorArray.size(); i++) { + if (this.filledSectorArray.get(i)) { + // sector filled + // if the length of the empty block we found is greater than or + // equal to the required length, and is closer to the required + // length than the previous found length, then set this as the + // new closest length. + // the idea is to use an empty block of exactly the required + // length, rather than one that is larger. + if ((length >= requiredLength) && (length < closestLength)) { + closestLength = length; + closestStart = start; + // if we find an empty block of exactly the correct length + // then exit the loop. + if (closestLength == requiredLength) { + break; + } + } + length = 0; + } else { + // sector empty + if (length == 0) { + start = i; + } + length++; + } + } + + if (closestStart <= 0) { + // append to end of file + closestStart = i; + } + + return new Section(closestStart, requiredLength); + } + + public void printInfo() { + int freeCount = 0; + int filledCount = 0; + // start at 2 to skip headers + for (int i = 2; i < this.filledSectorArray.size(); i++) { + if (this.filledSectorArray.get(i)) { + filledCount++; + } else { + freeCount++; + } + } + RegionManager.logInfo("Region File %s: filled sectors = %d, free sectors = %d", this, filledCount, freeCount); + + String s = ""; + int i; + for (i = 0; i < this.filledSectorArray.size(); i++) { + if ((i & 31) == 0) { + s = String.format("%04x:", i); + } + s += this.filledSectorArray.get(i) ? '1' : '0'; + if ((i & 31) == 31) { + RegionManager.logInfo("%s", s); + } + } + if ((i & 31) != 31) { + RegionManager.logInfo("%s", s); + } + } + + private Section getChunkSection(int x, int z) { + return this.chunkSectionsArray[((z & 31) << 5) | (x & 31)]; + } + + private void updateChunkSection(int x, int z, Section newSection) throws IOException { + int chunkIndex = ((z & 31) << 5) | (x & 31); + this.fin.seek(chunkIndex * 4); + if ((newSection != null) && (newSection.length > 0)) { + this.fin.writeInt(newSection.getSectorAndSize()); + } else { + this.fin.writeInt(0); + } + + this.chunkSectionsArray[chunkIndex] = newSection; + } + + public boolean open() { + File dir = this.file.getParentFile(); + if (dir.exists()) { + if (!dir.isDirectory()) { + RegionManager.logError("path %s exists and is not a directory", dir); + return true; + } + } else { + if (!dir.mkdirs()) { + RegionManager.logError("could not create directory %s", dir); + return true; + } + } + try { + this.fin = new RandomAccessFile(this.file, "rw"); + + // seek to start + this.fin.seek(0); + + this.lengthInSectors = (int) ((this.fin.length() + 4095L) / 4096L); + + this.filledSectorArray = new ArrayList(); + + Arrays.fill(this.chunkSectionsArray, null); + Arrays.fill(this.timestampArray, 0); + + if (this.lengthInSectors < 3) { + // no chunk data + // fill chunk and timestamp tables with 0's + for (int i = 0; i < 2048; i++) { + this.fin.writeInt(0); + } + } else { + // add a section for each chunk + for (int i = 0; i < 1024; i++) { + Section section = new Section(this.fin.readInt()); + if (section.length > 0) { + // make sure chunk does not overlap another + if (!checkSectionOverlaps(section)) { + this.chunkSectionsArray[i] = section; + this.setFilledSectorArray(section, true); + } else { + RegionManager.logError("chunk %d overlaps another chunk, file may be corrupt", i); + } + } + } + for (int i = 0; i < 1024; i++) { + this.timestampArray[i] = this.fin.readInt(); + } + } + + //this.printInfo(); + + } catch (Exception e) { + this.fin = null; + RegionManager.logError("exception when opening region file '%s': %s", this.file, e); + + } + + return this.fin == null; + } + + public void close() { + if (this.fin != null) { + try { this.fin.close(); } + catch (IOException e) {} + } + } + + public DataInputStream getChunkDataInputStream(int x, int z) { + DataInputStream dis = null; + if (this.fin != null) { + Section section = getChunkSection(x, z); + if ((section != null) && (section.length > 0)) { + int offset = section.startSector * 4096; + try { + // read length of following data (includes version byte) and compressed data version byte + this.fin.seek(offset); + int length = this.fin.readInt(); + byte version = this.fin.readByte(); + // version 1 = gzip compressed, version 2 = zlib/inflater compressed + if ((length > 1) && ((length + 4) < (section.length * 4096)) && (version == 2)) { + // read the compressed data + byte[] compressedChunkData = new byte[length - 1]; + this.fin.read(compressedChunkData); + // create a buffered inflater stream on the compressed data + dis = new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(compressedChunkData)))); + } else { + RegionManager.logError("data length (%d) or version (%d) invalid for chunk (%d, %d)", length, version, x, z); + } + } catch (Exception e) { + RegionManager.logError("exception while reading chunk (%d, %d): %s", x, z, e); + dis = null; + } + } + } + return dis; + } + + // basically an in memory byte array that writes its contents + // to a file when it is closed. + private class RegionFileChunkBuffer extends ByteArrayOutputStream { + private final int x; + private final int z; + private final RegionFile regionFile; + + public RegionFileChunkBuffer(RegionFile regionFile, int x, int z) { + super(8096); + this.regionFile = regionFile; + this.x = x; + this.z = z; + } + + public void close() { + this.regionFile.writeCompressedChunk(this.x, this.z, this.buf, this.count); + } + } + + public DataOutputStream getChunkDataOutputStream(int x, int z) { + return new DataOutputStream(new DeflaterOutputStream(new RegionFileChunkBuffer(this, x, z))); + } + + /*private int padToSectorSize() throws IOException { + // pad with 0 so that the file length is a multiple of 4096 bytes + long paddedLength = (this.length + 4095L) & (-4096L); + this.fin.seek(this.length); + for (long i = this.length; i < paddedLength; i++) { + this.fin.writeByte(0); + } + this.length = paddedLength; + return (int) (paddedLength / 4096); + }*/ + + private void writeChunkDataToSection(Section section, byte[] compressedChunkData, int length) throws IOException { + this.fin.seek(((long) section.startSector) * 4096L); + // write version and length + this.fin.writeInt(length + 1); + this.fin.writeByte(2); + // write compressed data + this.fin.write(compressedChunkData, 0, length); + + int endSector = section.startSector + section.length; + if ((endSector + 1) > this.lengthInSectors) { + this.lengthInSectors = endSector + 1; + } + } + + private boolean writeCompressedChunk(int x, int z, byte[] compressedChunkData, int length) { + // if larger than the existing chunk data or chunk does not exist then need to find the + // first possible file position to write to. This will either be a contiguous strip of + // free sectors longer than the length of the chunk data, or the end of the file (append). + + if (length <= 0) { + RegionManager.logWarning("not writing chunk (%d, %d) with length %d", x, z, length); + return true; + } + + // free the section this chunk currently occupies + Section currentSection = this.getChunkSection(x, z); + if (currentSection != null) { + this.setFilledSectorArray(currentSection, false); + } + + int requiredSectors = (length + 5 + 4095) / 4096; + Section newSection; + + if ((currentSection != null) && (requiredSectors <= currentSection.length)) { + // if the chunk still fits in it's current location don't move + //RegionManager.logInfo("chunk (%d, %d) fits in current location %d", x, z, currentSection.startSector); + newSection = new Section(currentSection.startSector, requiredSectors); + } else { + // otherwise find a free section large enough to hold the chunk data + newSection = getFreeSection(requiredSectors); + } + + // set the new section to filled + this.setFilledSectorArray(newSection, true); + + boolean error = true; + try { + //RegionManager.logInfo("writing %d bytes to sector %d for chunk (%d, %d)", length, newSection.startSector, x, z); + this.writeChunkDataToSection(newSection, compressedChunkData, length); + // update the header + this.updateChunkSection(x, z, newSection); + error = false; + } catch (IOException e) { + RegionManager.logError("could not write chunk (%d, %d) to region file: %s", x, z, e); + } + + return error; + } +} diff --git a/src/main/java/mapwriter/region/RegionFileCache.java b/src/main/java/mapwriter/region/RegionFileCache.java new file mode 100644 index 0000000..1b2cdd8 --- /dev/null +++ b/src/main/java/mapwriter/region/RegionFileCache.java @@ -0,0 +1,76 @@ +package mapwriter.region; + +import java.io.File; +import java.util.LinkedHashMap; +import java.util.Map; + +public class RegionFileCache { + + // simple Least Recently Used (LRU) cache implementation + class LruCache extends LinkedHashMap { + private static final long serialVersionUID = 1L; + static final int MAX_REGION_FILES_OPEN = 8; + + public LruCache() { + // initial capacity, loading factor, true for access time ordering + super(MAX_REGION_FILES_OPEN * 2, 0.5f, true); + } + + // called on every put and putAll call, the entry 'entry' is removed + // if this function returns true. + @Override + protected boolean removeEldestEntry(Map.Entry entry) { + boolean ret = false; + if (this.size() > MAX_REGION_FILES_OPEN) { + RegionFile regionFile = entry.getValue(); + regionFile.close(); + ret = true; + } + return ret; + } + } + + private LruCache regionFileCache = new LruCache(); + private File worldDir; + + public RegionFileCache(File worldDir) { + this.worldDir = worldDir; + } + + public void close() { + for (RegionFile regionFile : regionFileCache.values()) { + regionFile.close(); + } + this.regionFileCache.clear(); + } + + public File getRegionFilePath(int x, int z, int dimension) { + File dir = this.worldDir; + if (dimension != 0) { + dir = new File(dir, "DIM" + dimension); + } + dir = new File(dir, "region"); + + String filename = String.format("r.%d.%d.mca", + x >> Region.SHIFT, + z >> Region.SHIFT); + + return new File(dir, filename); + } + + public boolean regionFileExists(int x, int z, int dimension) { + File regionFilePath = getRegionFilePath(x, z, dimension); + return regionFilePath.isFile(); + } + + public RegionFile getRegionFile(int x, int z, int dimension) { + File regionFilePath = getRegionFilePath(x, z, dimension); + String key = regionFilePath.toString(); + RegionFile regionFile = this.regionFileCache.get(key); + if (regionFile == null) { + regionFile = new RegionFile(regionFilePath); + this.regionFileCache.put(key, regionFile); + } + return regionFile; + } +} diff --git a/src/main/java/mapwriter/region/RegionManager.java b/src/main/java/mapwriter/region/RegionManager.java new file mode 100644 index 0000000..7d9d7c6 --- /dev/null +++ b/src/main/java/mapwriter/region/RegionManager.java @@ -0,0 +1,157 @@ +package mapwriter.region; + +import java.io.File; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.logging.log4j.Logger; + +public class RegionManager { + + // simple Least Recently Used (LRU) cache implementation + class LruCache extends LinkedHashMap { + private final static long serialVersionUID = 1L; + private final static int MAX_LOADED_REGIONS = 64; + + public LruCache() { + // initial capacity, loading factor, true for access time ordering + super(MAX_LOADED_REGIONS * 2, 0.5f, true); + } + + // called on every put and putAll call, the entry 'entry' is removed + // if this function returns true. + @Override + protected boolean removeEldestEntry(Map.Entry entry) { + boolean ret = false; + if (this.size() > MAX_LOADED_REGIONS) { + Region region = entry.getValue(); + region.close(); + ret = true; + } + return ret; + } + } + + private final LruCache regionMap; + + public final File worldDir; + public final File imageDir; + public BlockColours blockColours; + public static Logger logger; + public final RegionFileCache regionFileCache; + + public int maxZoom; + public int minZoom; + + public static void logInfo(String s, Object...args) { + if (logger != null) { + logger.info(String.format(s, args)); + } + } + + public static void logWarning(String s, Object...args) { + if (logger != null) { + logger.warn(String.format(s, args)); + } + } + + public static void logError(String s, Object...args) { + if (logger != null) { + logger.error(String.format(s, args)); + } + } + + public RegionManager(File worldDir, File imageDir, BlockColours blockColours, int minZoom, int maxZoom) { + this.worldDir = worldDir; + this.imageDir = imageDir; + this.blockColours = blockColours; + this.regionMap = new LruCache(); + this.regionFileCache = new RegionFileCache(worldDir); + this.minZoom = minZoom; + this.maxZoom = maxZoom; + } + + public void close() { + for (Region region : this.regionMap.values()) { + if (region != null) { + region.close(); + } + } + this.regionMap.clear(); + this.regionFileCache.close(); + } + + private static int incrStatsCounter(Map h, String key) { + int n = 1; + if (h.containsKey(key)) { + n = h.get(key) + 1; + } + h.put(key, n); + return n; + } + + public void printLoadedRegionStats() { + logInfo("loaded region listing:"); + Map stats = new HashMap(); + for (Region region : this.regionMap.values()) { + logInfo(" %s", region); + incrStatsCounter(stats, String.format("dim%d", region.dimension)); + incrStatsCounter(stats, String.format("zoom%d", region.zoomLevel)); + incrStatsCounter(stats, "total"); + } + logInfo("loaded region stats:"); + for (Entry e : stats.entrySet()) { + logInfo(" %s: %d", e.getKey(), e.getValue()); + } + } + + // must not return null + public Region getRegion(int x, int z, int zoomLevel, int dimension) { + Region region = this.regionMap.get(Region.getKey(x, z, zoomLevel, dimension)); + if (region == null) { + // add region + region = new Region(this, x, z, zoomLevel, dimension); + this.regionMap.put(region.key, region); + } + return region; + } + + public void updateChunk(MwChunk chunk) { + Region region = this.getRegion(chunk.x << 4, chunk.z << 4, 0, chunk.dimension); + region.updateChunk(chunk); + } + + public void rebuildRegions(int xStart, int zStart, int w, int h, int dimension) { + // read all zoom level 0 regions + // then find all regions with a backing image at zoom level 0 + + xStart &= Region.MASK; + zStart &= Region.MASK; + w = (w + Region.SIZE) & Region.MASK; + h = (h + Region.SIZE) & Region.MASK; + + logInfo("rebuilding regions from (%d, %d) to (%d, %d)", xStart, zStart, xStart + w, zStart + h); + + for (int rX = xStart; rX < (xStart + w); rX += Region.SIZE) { + for (int rZ = zStart; rZ < (zStart + h); rZ += Region.SIZE) { + Region region = this.getRegion(rX, rZ, 0, dimension); + if (this.regionFileCache.regionFileExists(rX, rZ, dimension)) { + region.clear(); + for (int cz = 0; cz < 32; cz++) { + for (int cx = 0; cx < 32; cx++) { + // load chunk from anvil file + MwChunk chunk = MwChunk.read( + (region.x >> 4) + cx, (region.z >> 4) + cz, + region.dimension, this.regionFileCache + ); + region.updateChunk(chunk); + } + } + } + region.updateZoomLevels(); + } + } + } +} diff --git a/src/main/java/mapwriter/region/SurfacePixels.java b/src/main/java/mapwriter/region/SurfacePixels.java new file mode 100644 index 0000000..4755434 --- /dev/null +++ b/src/main/java/mapwriter/region/SurfacePixels.java @@ -0,0 +1,159 @@ +package mapwriter.region; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.Arrays; + +import javax.imageio.ImageIO; + +public class SurfacePixels { + + protected Region region; + protected File filename; + protected int[] pixels = null; + protected boolean cannotLoad = false; + protected int updateCount = 0; + + public SurfacePixels(Region region, File filename) { + this.region = region; + this.filename = filename; + } + + public void clear() { + if (this.pixels != null) { + Arrays.fill(this.pixels, 0); + } + } + + public void close() { + if (this.updateCount > 0) { + this.save(); + } + this.pixels = null; + } + + private void save() { + if (this.pixels != null) { + saveImage(this.filename, this.pixels, Region.SIZE, Region.SIZE); + this.cannotLoad = false; + } + this.updateCount = 0; + } + + private void load() { + if (!this.cannotLoad) { + this.pixels = loadImage(this.filename, Region.SIZE, Region.SIZE); + if (this.pixels != null) { + // set opaque black pixels to transparent so that + // background texture shows + for (int i = 0; i < this.pixels.length; i++) { + int colour = this.pixels[i]; + if (colour == 0xff000000) { + this.pixels[i] = 0; + } + } + } else { + this.cannotLoad = true; + } + this.updateCount = 0; + } + } + + public int[] getPixels() { + if (this.pixels == null) { + this.load(); + } + return this.pixels; + } + + public int[] getOrAllocatePixels() { + this.getPixels(); + if (this.pixels == null) { + this.pixels = new int[Region.SIZE * Region.SIZE]; + this.clear(); + } + return this.pixels; + } + + public void updateChunk(MwChunk chunk) { + int x = (chunk.x << 4); + int z = (chunk.z << 4); + int offset = this.region.getPixelOffset(x, z); + int[] pixels = this.getOrAllocatePixels(); + // TODO: refactor so that blockColours can be accessed + // more directly + ChunkRender.renderSurface( + this.region.regionManager.blockColours, + chunk, pixels, offset, Region.SIZE, + (chunk.dimension == -1) // use ceiling algorithm for nether + ); + this.region.updateZoomLevels(x, z, MwChunk.SIZE, MwChunk.SIZE); + this.updateCount++; + } + + // get the averaged colour of a 2x2 pixel area in the given pixels + public static int getAverageOfPixelQuad(int[] pixels, int offset, int scanSize) { + int p00 = pixels[offset]; + int p01 = pixels[offset + 1]; + int p10 = pixels[offset + scanSize]; + int p11 = pixels[offset + scanSize + 1]; + + // ignore alpha channel + int r = ((p00 >> 16) & 0xff) + ((p01 >> 16) & 0xff) + ((p10 >> 16) & 0xff) + ((p11 >> 16) & 0xff); + r >>= 2; + int g = ((p00 >> 8) & 0xff) + ((p01 >> 8) & 0xff) + ((p10 >> 8) & 0xff) + ((p11 >> 8) & 0xff); + g >>= 2; + int b = (p00 & 0xff) + (p01 & 0xff) + (p10 & 0xff) + (p11 & 0xff); + b >>= 2; + return 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); + } + + // update an area of pixels in this region from an area of pixels in srcPixels, + // scaling the pixels by 50%. + public void updateScaled(int[] srcPixels, int srcX, int srcZ, int dstX, int dstZ, int dstW, int dstH) { + int[] dstPixels = this.getOrAllocatePixels(); + for (int j = 0; j < dstH; j++) { + for (int i = 0; i < dstW; i++) { + int srcOffset = ((srcZ + (j * 2)) << Region.SHIFT) + (srcX + (i * 2)); + int dstPixel = getAverageOfPixelQuad(srcPixels, srcOffset, Region.SIZE); + dstPixels[((dstZ + j) << Region.SHIFT) + (dstX + i)] = dstPixel; + } + } + this.updateCount++; + } + + public static void saveImage(File filename, int[] pixels, int w, int h) { + BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); + img.setRGB(0, 0, w, h, pixels, 0, w); + + try { + //MwUtil.log("writing region %s to %s", this, this.imageFile); + ImageIO.write(img, "png", filename); + } catch (IOException e) { + RegionManager.logError("saveImage: error: could not write image to %s", filename); + } + } + + public static int[] loadImage(File filename, int w, int h) { + BufferedImage img = null; + try { + img = ImageIO.read(filename); + } catch (IOException e) { + img = null; + } + int[] pixels = null; + if (img != null) { + if ((img.getWidth() == w) && (img.getHeight() == h)) { + pixels = new int[w * h]; + img.getRGB(0, 0, w, h, pixels, 0, w); + } else { + RegionManager.logWarning( + "loadImage: image '%s' does not match expected dimensions (got %dx%d expected %dx%d)", + filename, img.getWidth(), img.getHeight(), w, h + ); + } + } + return pixels; + } +} diff --git a/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java b/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java new file mode 100644 index 0000000..6880844 --- /dev/null +++ b/src/main/java/mapwriter/tasks/CloseRegionManagerTask.java @@ -0,0 +1,21 @@ +package mapwriter.tasks; + +import mapwriter.region.RegionManager; + +public class CloseRegionManagerTask extends Task { + + private final RegionManager regionManager; + + public CloseRegionManagerTask(RegionManager regionManager) { + this.regionManager = regionManager; + } + + @Override + public void run() { + this.regionManager.close(); + } + + @Override + public void onComplete() { + } +} diff --git a/src/main/java/mapwriter/tasks/MergeTask.java b/src/main/java/mapwriter/tasks/MergeTask.java new file mode 100644 index 0000000..7f23cc3 --- /dev/null +++ b/src/main/java/mapwriter/tasks/MergeTask.java @@ -0,0 +1,43 @@ +package mapwriter.tasks; + +import java.io.File; + +import mapwriter.MwUtil; +import mapwriter.region.MergeToImage; +import mapwriter.region.RegionManager; + +public class MergeTask extends Task { + + final RegionManager regionManager; + final File outputDir; + final String basename; + final int x, z, w, h, dimension; + String msg = ""; + + public MergeTask(RegionManager regionManager, int x, int z, int w, int h, int dimension, File outputDir, String basename) { + this.regionManager = regionManager; + this.x = x; + this.z = z; + this.w = w; + this.h = h; + this.dimension = dimension; + this.outputDir = outputDir; + this.basename = basename; + } + + @Override + public void run() { + int count = MergeToImage.merge(this.regionManager, this.x, this.z, this.w, this.h, this.dimension, this.outputDir, this.basename); + if (count > 0) { + this.msg = String.format("successfully wrote merged images to directory %s", this.outputDir); + } else { + this.msg = String.format("merge error: could not write images to directory %s", this.outputDir); + } + } + + @Override + public void onComplete() { + MwUtil.printBoth(this.msg); + } + +} diff --git a/src/main/java/mapwriter/tasks/RebuildRegionsTask.java b/src/main/java/mapwriter/tasks/RebuildRegionsTask.java new file mode 100644 index 0000000..9e8823f --- /dev/null +++ b/src/main/java/mapwriter/tasks/RebuildRegionsTask.java @@ -0,0 +1,36 @@ +package mapwriter.tasks; + +import mapwriter.Mw; +import mapwriter.MwUtil; +import mapwriter.region.BlockColours; +import mapwriter.region.RegionManager; + +public class RebuildRegionsTask extends Task { + + final RegionManager regionManager; + final BlockColours blockColours; + final int x, z, w, h, dimension; + String msg = ""; + + public RebuildRegionsTask(Mw mw, int x, int z, int w, int h, int dimension) { + this.regionManager = mw.regionManager; + this.blockColours = mw.blockColours; + this.x = x; + this.z = z; + this.w = w; + this.h = h; + this.dimension = dimension; + } + + @Override + public void run() { + this.regionManager.blockColours = blockColours; + this.regionManager.rebuildRegions(this.x, this.z, this.w, this.h, this.dimension); + } + + @Override + public void onComplete() { + MwUtil.printBoth("rebuild task complete"); + } + +} diff --git a/src/main/java/mapwriter/tasks/SaveChunkTask.java b/src/main/java/mapwriter/tasks/SaveChunkTask.java new file mode 100644 index 0000000..b90fbc3 --- /dev/null +++ b/src/main/java/mapwriter/tasks/SaveChunkTask.java @@ -0,0 +1,23 @@ +package mapwriter.tasks; + +import mapwriter.region.MwChunk; +import mapwriter.region.RegionManager; + +public class SaveChunkTask extends Task { + private final MwChunk chunk; + private final RegionManager regionManager; + + public SaveChunkTask(MwChunk chunk, RegionManager regionManager) { + this.chunk = chunk; + this.regionManager = regionManager; + } + + @Override + public void run() { + this.chunk.write(this.regionManager.regionFileCache); + } + + @Override + public void onComplete() { + } +} diff --git a/src/main/java/mapwriter/tasks/Task.java b/src/main/java/mapwriter/tasks/Task.java new file mode 100644 index 0000000..d2eff63 --- /dev/null +++ b/src/main/java/mapwriter/tasks/Task.java @@ -0,0 +1,43 @@ +package mapwriter.tasks; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +public abstract class Task implements Runnable { + + // the task stores its own future + private Future future = null; + + // called by processTaskQueue after the thread completes + public abstract void onComplete(); + + // the method that runs in a separate thread + // must not access future in run() + public abstract void run(); + + // methods to access the tasks Future variable + public final Future getFuture() { + return this.future; + } + + public final void setFuture(Future future) { + this.future = future; + } + + public final boolean isDone() { + return (this.future != null) ? this.future.isDone() : false; + } + + public final void printException() { + if (this.future != null) { + try { + this.future.get(); + } catch (ExecutionException e) { + Throwable rootException = e.getCause(); + rootException.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } +} diff --git a/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java new file mode 100644 index 0000000..b71c00d --- /dev/null +++ b/src/main/java/mapwriter/tasks/UpdateSurfaceChunksTask.java @@ -0,0 +1,38 @@ +package mapwriter.tasks; + +import mapwriter.Mw; +import mapwriter.map.MapTexture; +import mapwriter.region.MwChunk; +import mapwriter.region.RegionManager; + +public class UpdateSurfaceChunksTask extends Task { + MwChunk[] chunkArray; + RegionManager regionManager; + MapTexture mapTexture; + + public UpdateSurfaceChunksTask(Mw mw, MwChunk[] chunkArray) { + this.mapTexture = mw.mapTexture; + this.regionManager = mw.regionManager; + this.chunkArray = chunkArray; + } + + @Override + public void run() { + for (MwChunk chunk : this.chunkArray) { + if (chunk != null) { + // update the chunk in the region pixels + this.regionManager.updateChunk(chunk); + // copy updated region pixels to maptexture + this.mapTexture.updateArea( + this.regionManager, + chunk.x << 4, chunk.z << 4, + MwChunk.SIZE, MwChunk.SIZE, chunk.dimension + ); + } + } + } + + @Override + public void onComplete() { + } +} diff --git a/src/main/java/mcp/mobius/mobiuscore/profiler/DummyProfiler.java b/src/main/java/mcp/mobius/mobiuscore/profiler/DummyProfiler.java deleted file mode 100644 index 3c737b0..0000000 --- a/src/main/java/mcp/mobius/mobiuscore/profiler/DummyProfiler.java +++ /dev/null @@ -1,38 +0,0 @@ -package mcp.mobius.mobiuscore.profiler; - -import net.minecraft.world.World; - -public class DummyProfiler implements IProfilerBase{ - @Override - public void reset() {} - - @Override - public void start() {} - - @Override - public void stop() {} - - @Override - public void start(Object key) {} - - @Override - public void stop(Object key) {} - - @Override - public void start(Object key1, Object key2) {} - - @Override - public void stop(Object key1, Object key2) {} - - @Override - public void start(Object key1, Object key2, Object key3) {} - - @Override - public void stop(Object key1, Object key2, Object key3) {} - - @Override - public void start(Object key1, Object key2, Object key3, Object key4) {} - - @Override - public void stop(Object key1, Object key2, Object key3, Object key4) {} -} diff --git a/src/main/java/mcp/mobius/mobiuscore/profiler/IProfilerBase.java b/src/main/java/mcp/mobius/mobiuscore/profiler/IProfilerBase.java deleted file mode 100644 index c263eb3..0000000 --- a/src/main/java/mcp/mobius/mobiuscore/profiler/IProfilerBase.java +++ /dev/null @@ -1,24 +0,0 @@ -package mcp.mobius.mobiuscore.profiler; - -import net.minecraft.world.World; - -public interface IProfilerBase { - - public void reset(); - - public void start(); - public void stop(); - - public void start(Object key); - public void stop(Object key); - - public void start(Object key1, Object key2); - public void stop(Object key1, Object key2); - - public void start(Object key1, Object key2, Object key3); - public void stop(Object key1, Object key2, Object key3); - - public void start(Object key1, Object key2, Object key3, Object key4); - public void stop(Object key1, Object key2, Object key3, Object key4); - -} diff --git a/src/main/java/mcp/mobius/mobiuscore/profiler/ProfilerSection.java b/src/main/java/mcp/mobius/mobiuscore/profiler/ProfilerSection.java deleted file mode 100644 index 20214a6..0000000 --- a/src/main/java/mcp/mobius/mobiuscore/profiler/ProfilerSection.java +++ /dev/null @@ -1,129 +0,0 @@ -package mcp.mobius.mobiuscore.profiler; - -import java.util.EnumSet; - -import cpw.mods.fml.relauncher.Side; -import net.minecraft.world.World; - -public enum ProfilerSection implements IProfilerBase{ - DIMENSION_TICK (RunType.REALTIME, Side.SERVER), //Global section around the ticks for each dim (Blocks & ents). - DIMENSION_BLOCKTICK(RunType.ONREQUEST, Side.SERVER), //Subsection for dimension block tick. - ENTITY_UPDATETIME (RunType.ONREQUEST, Side.SERVER), //Profiling of the entity tick time, per entity. - TICK (RunType.REALTIME, Side.SERVER), //Tick timing profiling - TILEENT_UPDATETIME (RunType.ONREQUEST, Side.SERVER), //Profiling of the TileEntity tick time, per TE. - //HANDLER_TICKSTART (RunType.ONREQUEST, EnumSet.of(Side.CLIENT, Side.SERVER)), //Server handler for ServerTick start. - //HANDLER_TICKSTOP (RunType.ONREQUEST, EnumSet.of(Side.CLIENT, Side.SERVER)), //Server handler for ServerTick stop. - PACKET_INBOUND (RunType.REALTIME, Side.SERVER), //Outbound packet analysis - PACKET_OUTBOUND (RunType.REALTIME, Side.SERVER), //Inbound packet analysis - //PACKETFML_INBOUND (RunType.REALTIME, Side.SERVER), //Outbound packet analysis - //PACKETFML_OUTBOUND (RunType.REALTIME, Side.SERVER), //Inbound packet analysis - - - NETWORK_TICK (RunType.ONREQUEST, Side.SERVER), //The time it takes for the server to handle the packets during a tick. - EVENT_INVOKE (RunType.ONREQUEST, EnumSet.of(Side.CLIENT, Side.SERVER)), //Timing of the event invokation - - RENDER_TILEENTITY (RunType.ONREQUEST, Side.CLIENT), //Profiler for TileEnt rendering - RENDER_ENTITY (RunType.ONREQUEST, Side.CLIENT), //Profiler for Entity rendering - RENDER_BLOCK (RunType.ONREQUEST, Side.CLIENT); //Profiler for Block rendering - - public enum RunType{ - REALTIME, - ONREQUEST; - } - - private EnumSet sides; - private RunType runType; - private IProfilerBase profiler = new DummyProfiler();; - private IProfilerBase profilerSuspended = new DummyProfiler();; - - public static long timeStampLastRun; - - private ProfilerSection(RunType runType, Side side){ - this.runType = runType; - this.profiler = new DummyProfiler(); - this.sides = EnumSet.of(side); - } - - private ProfilerSection(RunType runType, EnumSet sides){ - this.runType = runType; - this.profiler = new DummyProfiler(); - this.sides = sides; - } - - public RunType getRunType(){ - return this.runType; - } - - public EnumSet getSide(){ - return this.sides; - } - - public IProfilerBase getProfiler(){ - return this.profilerSuspended; - } - - public void setProfiler(IProfilerBase profiler){ - this.profilerSuspended = profiler; - if (this.runType == RunType.REALTIME) - this.profiler = profiler; - } - - public void activate(){ - this.profiler = profilerSuspended; - this.timeStampLastRun = System.currentTimeMillis(); - } - - public void desactivate(){ - if (this.runType == RunType.ONREQUEST) - this.profiler = new DummyProfiler(); - } - - public static void activateAll(Side trgside){ - for (ProfilerSection section : ProfilerSection.values()) - if (section.sides.contains(trgside)) - section.activate(); - } - - public static void desactivateAll(Side trgside){ - for (ProfilerSection section : ProfilerSection.values()) - if (section.sides.contains(trgside)) - section.desactivate(); - } - - public static void resetAll(Side trgside){ - for (ProfilerSection section : ProfilerSection.values()) - if (section.sides.contains(trgside)) - section.reset(); - } - - public static String getClassName(){ - return ProfilerSection.class.getCanonicalName().replace(".", "/"); - } - - public static String getTypeName(){ - return "L" + ProfilerSection.getClassName() + ";"; - } - - @Override - public void reset() { this.profiler.reset(); this.profilerSuspended.reset(); } - @Override - public void start() { this.profiler.start(); } - @Override - public void stop() { this.profiler.stop(); } - @Override - public void start(Object key) { this.profiler.start(key); } - @Override - public void stop(Object key) { this.profiler.stop(key); } - @Override - public void start(Object key1, Object key2) { this.profiler.start(key1, key2); } - @Override - public void stop(Object key1, Object key2) { this.profiler.stop(key1, key2); } - @Override - public void start(Object key1, Object key2, Object key3) { this.profiler.start(key1, key2, key3);} - @Override - public void stop(Object key1, Object key2, Object key3) { this.profiler.stop(key1, key2, key3); } - @Override - public void start(Object key1, Object key2, Object key3, Object key4) { this.profiler.start(key1, key2, key3, key4);} - @Override - public void stop(Object key1, Object key2, Object key3, Object key4) { this.profiler.stop(key1, key2, key3, key4); } -} diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerEvent.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerEvent.java index 101bb00..50fad5b 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerEvent.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerEvent.java @@ -7,6 +7,8 @@ import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import com.google.common.collect.HashBasedTable; import com.google.common.collect.HashMultimap; +import cpw.mods.fml.common.ModContainer; + public class ProfilerEvent extends ProfilerAbstract { private IClock clock = Clock.getNewClock(); @@ -39,7 +41,7 @@ public class ProfilerEvent extends ProfilerAbstract { } catch (Exception e) { String name = (String)pkg + "|" + handler.getClass().getSimpleName(); dataTick.put(event.getClass(), name, new DescriptiveStatistics(250)); - dataModTick.put(event.getClass(), name, (String)mod); + dataModTick.put(event.getClass(), name, ((ModContainer)mod).getName()); dataTick.get(event.getClass(), name).addValue((double)clock.getDelta()); } @@ -51,7 +53,7 @@ public class ProfilerEvent extends ProfilerAbstract { } catch (Exception e) { String name = (String)pkg + "|" + handler.getClass().getSimpleName(); data.put(event.getClass(), name, new DescriptiveStatistics(250)); - dataMod.put(event.getClass(), name, (String)mod); + dataMod.put(event.getClass(), name, ((ModContainer)mod).getName()); data.get(event.getClass(), name).addValue((double)clock.getDelta()); } diff --git a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderEntity.java b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderEntity.java index 5932c5a..b081c4b 100644 --- a/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderEntity.java +++ b/src/main/java/mcp/mobius/opis/data/profilers/ProfilerRenderEntity.java @@ -31,7 +31,8 @@ public class ProfilerRenderEntity extends ProfilerAbstract { public void stop(Object key){ clock.stop(); try{ - data.get((Entity)key).addValue((double)clock.getDelta()); + //data.get((Entity)key).addValue((double)clock.getDelta()); + data.get(key).addValue((double)clock.getDelta()); } catch (Exception e) { modOpis.log.warning(String.format("Error while profiling entity %s\n", key)); } diff --git a/src/main/java/mcp/mobius/opis/modOpis.java b/src/main/java/mcp/mobius/opis/modOpis.java index 8f03002..1407361 100644 --- a/src/main/java/mcp/mobius/opis/modOpis.java +++ b/src/main/java/mcp/mobius/opis/modOpis.java @@ -2,18 +2,16 @@ package mcp.mobius.opis; import java.util.logging.Logger; +import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; + import net.minecraft.block.Block; import net.minecraft.block.material.Material; -import net.minecraft.server.MinecraftServer; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import mcp.mobius.opis.commands.client.CommandClientShowRenderTick; -import mcp.mobius.opis.commands.client.CommandClientStart; import mcp.mobius.opis.commands.client.CommandOpis; import mcp.mobius.opis.commands.server.CommandAddPrivileged; import mcp.mobius.opis.commands.server.CommandAmountEntities; -import mcp.mobius.opis.commands.server.CommandChunkDump; import mcp.mobius.opis.commands.server.CommandChunkList; import mcp.mobius.opis.commands.server.CommandEntityCreate; import mcp.mobius.opis.commands.server.CommandFrequency; @@ -28,7 +26,6 @@ import mcp.mobius.opis.commands.server.CommandTicks; import mcp.mobius.opis.commands.server.CommandTimingEntities; import mcp.mobius.opis.commands.server.CommandTimingTileEntities; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; -import mcp.mobius.opis.data.profilers.DeadManSwitch; import mcp.mobius.opis.data.profilers.ProfilerDimBlockTick; import mcp.mobius.opis.data.profilers.ProfilerDimTick; import mcp.mobius.opis.data.profilers.ProfilerEntityUpdate; @@ -64,8 +61,6 @@ import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.registry.GameRegistry; -import cpw.mods.fml.common.registry.LanguageRegistry; -import cpw.mods.fml.relauncher.Side; @Mod(modid="Opis", name="Opis", version="1.2.2") //@NetworkMod(channels={"Opis", "Opis_Chunk"},clientSideRequired=false, serverSideRequired=false, connectionHandler=OpisConnectionHandler.class, packetHandler=OpisPacketHandler.class) @@ -199,5 +194,10 @@ public class modOpis { //GameRegistry.registerPlayerTracker(PlayerTracker.instance()); //DeadManSwitch.startDeadManSwitch(MinecraftServer.getServer()); + /* + for (ProfilerSection sec : ProfilerSection.values()){ + System.out.printf("%s : %s\n", sec, sec.getProfiler().getClass().getSimpleName()); + } + */ } } diff --git a/src/main/java/mcp/mobius/opis/swing/SwingUI.java b/src/main/java/mcp/mobius/opis/swing/SwingUI.java index a4ab065..b6fa1c4 100644 --- a/src/main/java/mcp/mobius/opis/swing/SwingUI.java +++ b/src/main/java/mcp/mobius/opis/swing/SwingUI.java @@ -8,8 +8,6 @@ import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.ToolTipManager; -import javax.swing.UIManager; -import javax.swing.UnsupportedLookAndFeelException; import javax.swing.WindowConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; @@ -26,20 +24,12 @@ import net.minecraft.client.gui.GuiChat; import mcp.mobius.opis.modOpis; import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.api.ITabPanel; -import mcp.mobius.opis.api.TabPanelRegistrar; import mcp.mobius.opis.data.holders.basetypes.SerialInt; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.AccessLevel; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; -import mcp.mobius.opis.swing.panels.PanelSummary; -import mcp.mobius.opis.swing.panels.timingserver.PanelTimingChunks; -import mcp.mobius.opis.swing.panels.timingserver.PanelTimingEntities; -import mcp.mobius.opis.swing.panels.timingserver.PanelTimingHandlers; -import mcp.mobius.opis.swing.panels.timingserver.PanelTimingTileEnts; -import mcp.mobius.opis.swing.panels.tracking.PanelAmountEntities; -import mcp.mobius.opis.swing.panels.tracking.PanelPlayers; import mcp.mobius.opis.swing.widgets.JButtonAccess; public class SwingUI extends JFrame implements WindowListener, ChangeListener, IMessageHandler{ diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountEntities.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountEntities.java index 1fb9554..1dea16c 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountEntities.java @@ -9,19 +9,12 @@ import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.SelectedTab; -import mcp.mobius.opis.swing.SwingUI; import mcp.mobius.opis.swing.panels.tracking.PanelAmountEntities; import mcp.mobius.opis.swing.widgets.JTableStats; -import javax.swing.JButton; - import mcp.mobius.opis.api.TabPanelRegistrar; import mcp.mobius.opis.data.holders.basetypes.AmountHolder; -import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.basetypes.SerialString; -import mcp.mobius.opis.data.holders.stats.StatAbstract; -import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; -import mcp.mobius.opis.swing.widgets.JTableStats; public class ActionAmountEntities implements ActionListener, ItemListener { diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountTileEnts.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountTileEnts.java index b81543c..3234bbc 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountTileEnts.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionAmountTileEnts.java @@ -2,28 +2,12 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; - import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.SelectedTab; -import mcp.mobius.opis.swing.SwingUI; -import mcp.mobius.opis.swing.panels.tracking.PanelAmountEntities; import mcp.mobius.opis.swing.panels.tracking.PanelAmountTileEnts; -import mcp.mobius.opis.swing.widgets.JTableStats; - -import javax.swing.JButton; - import mcp.mobius.opis.api.TabPanelRegistrar; -import mcp.mobius.opis.data.holders.basetypes.AmountHolder; -import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; -import mcp.mobius.opis.data.holders.basetypes.SerialString; -import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntityPerClass; -import mcp.mobius.opis.data.holders.stats.StatAbstract; -import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; -import mcp.mobius.opis.swing.widgets.JTableStats; public class ActionAmountTileEnts implements ActionListener{ diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionOrphanTileEntities.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionOrphanTileEntities.java index 7954983..bd2d4f9 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionOrphanTileEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionOrphanTileEntities.java @@ -9,7 +9,6 @@ import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.panels.debug.PanelOrphanTileEntities; -import mcp.mobius.opis.swing.widgets.JTableStats; public class ActionOrphanTileEntities implements ActionListener { diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionPlayers.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionPlayers.java index 97d3d28..c339e80 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionPlayers.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionPlayers.java @@ -2,9 +2,6 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; - import mapwriter.Mw; import mapwriter.api.MwAPI; import mapwriter.gui.MwGui; @@ -12,20 +9,14 @@ import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.SelectedTab; -import mcp.mobius.opis.swing.SwingUI; import mcp.mobius.opis.swing.panels.tracking.PanelPlayers; import mcp.mobius.opis.swing.widgets.JTableStats; -import javax.swing.JButton; - import mcp.mobius.opis.api.TabPanelRegistrar; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.basetypes.TargetEntity; import mcp.mobius.opis.data.holders.newtypes.DataEntity; -import mcp.mobius.opis.data.holders.stats.StatAbstract; import mcp.mobius.opis.gui.overlay.entperchunk.OverlayEntityPerChunk; -import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; -import mcp.mobius.opis.swing.widgets.JTableStats; import net.minecraft.client.Minecraft; public class ActionPlayers implements ActionListener { diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingChunks.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingChunks.java index afd6029..0c88a59 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingChunks.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingChunks.java @@ -2,9 +2,6 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; - import mapwriter.Mw; import mapwriter.api.MwAPI; import mapwriter.gui.MwGui; @@ -12,19 +9,12 @@ import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.SelectedTab; -import mcp.mobius.opis.swing.SwingUI; import mcp.mobius.opis.swing.panels.timingserver.PanelTimingChunks; import mcp.mobius.opis.swing.widgets.JTableStats; -import javax.swing.JButton; - import mcp.mobius.opis.api.TabPanelRegistrar; -import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; -import mcp.mobius.opis.data.holders.stats.StatAbstract; import mcp.mobius.opis.data.holders.stats.StatsChunk; import mcp.mobius.opis.gui.overlay.OverlayMeanTime; -import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; -import mcp.mobius.opis.swing.widgets.JTableStats; import net.minecraft.client.Minecraft; public class ActionTimingChunks implements ActionListener { diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingEntities.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingEntities.java index 20b442c..8f53b85 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingEntities.java @@ -2,9 +2,6 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; - import mapwriter.Mw; import mapwriter.api.MwAPI; import mapwriter.gui.MwGui; @@ -12,20 +9,14 @@ import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.SelectedTab; -import mcp.mobius.opis.swing.SwingUI; import mcp.mobius.opis.swing.panels.timingserver.PanelTimingEntities; import mcp.mobius.opis.swing.widgets.JTableStats; -import javax.swing.JButton; - import mcp.mobius.opis.api.TabPanelRegistrar; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.basetypes.TargetEntity; import mcp.mobius.opis.data.holders.newtypes.DataEntity; -import mcp.mobius.opis.data.holders.stats.StatAbstract; import mcp.mobius.opis.gui.overlay.entperchunk.OverlayEntityPerChunk; -import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; -import mcp.mobius.opis.swing.widgets.JTableStats; import net.minecraft.client.Minecraft; public class ActionTimingEntities implements ActionListener { diff --git a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingTileEnts.java b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingTileEnts.java index 16d2653..ba6b363 100644 --- a/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingTileEnts.java +++ b/src/main/java/mcp/mobius/opis/swing/actions/ActionTimingTileEnts.java @@ -2,9 +2,6 @@ package mcp.mobius.opis.swing.actions; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; - import mapwriter.Mw; import mapwriter.api.MwAPI; import mapwriter.gui.MwGui; @@ -13,18 +10,13 @@ import mcp.mobius.opis.network.PacketManager; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.network.packets.client.PacketReqData; import mcp.mobius.opis.swing.SelectedTab; -import mcp.mobius.opis.swing.SwingUI; import mcp.mobius.opis.swing.panels.timingserver.PanelTimingTileEnts; import mcp.mobius.opis.swing.widgets.JTableStats; -import javax.swing.JButton; - import mcp.mobius.opis.api.TabPanelRegistrar; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntity; import mcp.mobius.opis.gui.overlay.OverlayMeanTime; -import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; -import mcp.mobius.opis.swing.widgets.JTableStats; import net.minecraft.client.Minecraft; public class ActionTimingTileEnts implements ActionListener { diff --git a/src/main/java/mcp/mobius/opis/swing/panels/PanelSummary.java b/src/main/java/mcp/mobius/opis/swing/panels/PanelSummary.java index 1434661..a542f89 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/PanelSummary.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/PanelSummary.java @@ -1,8 +1,6 @@ package mcp.mobius.opis.swing.panels; import java.awt.Color; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; @@ -12,12 +10,9 @@ import javax.swing.JPanel; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.client.DataCache; import mcp.mobius.opis.data.holders.ISerializable; -import mcp.mobius.opis.data.holders.basetypes.SerialDouble; import mcp.mobius.opis.data.holders.basetypes.SerialInt; import mcp.mobius.opis.data.holders.basetypes.SerialLong; import mcp.mobius.opis.data.holders.newtypes.DataBlockTick; -import mcp.mobius.opis.data.holders.newtypes.DataNetworkTick; -import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntity; import mcp.mobius.opis.data.holders.newtypes.DataTiming; import mcp.mobius.opis.data.holders.newtypes.DataTimingMillisecond; import mcp.mobius.opis.network.PacketBase; @@ -446,7 +441,7 @@ public class PanelSummary extends JPanelMsgHandler implements ITabPanel{ } case STATUS_PING:{ - this.pingData.addValue((double)(System.nanoTime() - ((SerialLong)rawdata.value).value)); + this.pingData.addValue(System.nanoTime() - ((SerialLong)rawdata.value).value); this.nPings += 1; //if (this.nPings % 2 == 0){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelOrphanTileEntities.java b/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelOrphanTileEntities.java index 25ab342..12d86c4 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelOrphanTileEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelOrphanTileEntities.java @@ -15,7 +15,6 @@ import net.miginfocom.swing.MigLayout; import javax.swing.JButton; import javax.swing.JScrollPane; -import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableModel; @@ -47,8 +46,8 @@ public class PanelOrphanTileEntities extends JPanelMsgHandler implements ITabPan switch(msg){ case LIST_ORPHAN_TILEENTS:{ - ((JTableStats)this.getTable()).addTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)this.getTable().getModel(); + this.getTable().addTableData(rawdata.array); + DefaultTableModel model = this.getTable().getModel(); //int row = this.updateData(table, model, DataTileEntity.class); for (Object o : rawdata.array){ @@ -68,8 +67,8 @@ public class PanelOrphanTileEntities extends JPanelMsgHandler implements ITabPan } case LIST_ORPHAN_TILEENTS_CLEAR:{ - ((JTableStats)this.getTable()).clearTableData(); - DefaultTableModel model = (DefaultTableModel)this.getTable().getModel(); + this.getTable().clearTableData(); + DefaultTableModel model = this.getTable().getModel(); row = this.getTable().clearTable(DataTileEntity.class); } diff --git a/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelThreads.java b/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelThreads.java index d25a43e..cd69c64 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelThreads.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/debug/PanelThreads.java @@ -3,18 +3,14 @@ package mcp.mobius.opis.swing.panels.debug; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataThread; -import mcp.mobius.opis.data.holders.newtypes.DataTileEntity; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.swing.SelectedTab; -import mcp.mobius.opis.swing.actions.ActionOrphanTileEntities; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JButton; import javax.swing.JScrollPane; -import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableModel; @@ -39,9 +35,9 @@ public class PanelThreads extends JPanelMsgHandler implements ITabPanel { switch(msg){ case LIST_THREADS:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)this.getTable().getModel(); + DefaultTableModel model = this.getTable().getModel(); int row = this.getTable().clearTable(DataThread.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound.java b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound.java index d2e1827..f9cd565 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound.java @@ -1,7 +1,6 @@ package mcp.mobius.opis.swing.panels.network; import javax.swing.JScrollPane; -import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import net.miginfocom.swing.MigLayout; @@ -16,8 +15,6 @@ import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class PanelInbound extends JPanelMsgHandler implements ITabPanel { @@ -41,9 +38,9 @@ public class PanelInbound extends JPanelMsgHandler implements ITabPanel { switch(msg){ case LIST_PACKETS_INBOUND:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)this.getTable().getModel(); + DefaultTableModel model = this.getTable().getModel(); int row = this.getTable().clearTable(DataPacket.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound250.java b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound250.java index a0e6b53..533a256 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound250.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelInbound250.java @@ -1,7 +1,6 @@ package mcp.mobius.opis.swing.panels.network; import javax.swing.JScrollPane; -import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import net.miginfocom.swing.MigLayout; @@ -10,7 +9,6 @@ import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataAmountRate; import mcp.mobius.opis.data.holders.newtypes.DataByteRate; import mcp.mobius.opis.data.holders.newtypes.DataByteSize; -import mcp.mobius.opis.data.holders.newtypes.DataPacket; import mcp.mobius.opis.data.holders.newtypes.DataPacket250; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.Message; @@ -18,8 +16,6 @@ import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class PanelInbound250 extends JPanelMsgHandler implements ITabPanel { @@ -43,9 +39,9 @@ public class PanelInbound250 extends JPanelMsgHandler implements ITabPanel { switch(msg){ case LIST_PACKETS_INBOUND_250:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)this.getTable().getModel(); + DefaultTableModel model = this.getTable().getModel(); int row = this.getTable().clearTable(DataPacket250.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound.java b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound.java index 4dc4f0c..6e5ba0a 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound.java @@ -1,7 +1,6 @@ package mcp.mobius.opis.swing.panels.network; import javax.swing.JScrollPane; -import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import net.miginfocom.swing.MigLayout; @@ -16,8 +15,6 @@ import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class PanelOutbound extends JPanelMsgHandler implements ITabPanel { @@ -42,9 +39,9 @@ public class PanelOutbound extends JPanelMsgHandler implements ITabPanel { switch(msg){ case LIST_PACKETS_OUTBOUND:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)this.getTable().getModel(); + DefaultTableModel model = this.getTable().getModel(); int row = this.getTable().clearTable(DataPacket.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound250.java b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound250.java index 15dee03..0107fb8 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound250.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/network/PanelOutbound250.java @@ -1,7 +1,6 @@ package mcp.mobius.opis.swing.panels.network; import javax.swing.JScrollPane; -import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import net.miginfocom.swing.MigLayout; @@ -17,8 +16,6 @@ import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class PanelOutbound250 extends JPanelMsgHandler implements ITabPanel { @@ -43,9 +40,9 @@ public class PanelOutbound250 extends JPanelMsgHandler implements ITabPanel { switch(msg){ case LIST_PACKETS_OUTBOUND_250:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)this.getTable().getModel(); + DefaultTableModel model = this.getTable().getModel(); int row = this.getTable().clearTable(DataPacket250.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelEventClient.java b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelEventClient.java index 805d06a..969d705 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelEventClient.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelEventClient.java @@ -7,16 +7,13 @@ import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; -import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import net.miginfocom.swing.MigLayout; import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.CachedString; -import mcp.mobius.opis.data.holders.newtypes.DataEntityRender; import mcp.mobius.opis.data.holders.newtypes.DataEvent; import mcp.mobius.opis.data.holders.newtypes.DataTiming; import mcp.mobius.opis.network.PacketBase; @@ -25,8 +22,6 @@ import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.actions.ActionRunOpisClient; import mcp.mobius.opis.swing.widgets.JTableStats; -import javax.swing.JLabel; - public class PanelEventClient extends JPanel implements ITabPanel, IMessageHandler{ private JTableStats table; private JButton btnRunRender; @@ -55,7 +50,7 @@ public class PanelEventClient extends JPanel implements ITabPanel, IMessageHandl public void setTable(ArrayList data){ - DefaultTableModel model = (DefaultTableModel)table.getModel(); + DefaultTableModel model = table.getModel(); int row = this.updateData(table, model, DataEvent.class); for (DataEvent o : data){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderEntities.java b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderEntities.java index 0e8b319..31ca110 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderEntities.java @@ -6,8 +6,6 @@ import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import net.miginfocom.swing.MigLayout; @@ -54,7 +52,7 @@ public class PanelRenderEntities extends JPanel implements ITabPanel, IMessageHa public void setTable(ArrayList data){ - DefaultTableModel model = (DefaultTableModel)table.getModel(); + DefaultTableModel model = table.getModel(); int row = this.updateData(table, model, DataEntityRender.class); for (DataEntityRender o : data){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderHandlers.java b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderHandlers.java index 0f0a2f0..00c5c1f 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderHandlers.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderHandlers.java @@ -6,16 +6,12 @@ import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import net.miginfocom.swing.MigLayout; import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.CachedString; -import mcp.mobius.opis.data.holders.newtypes.DataEntityRender; import mcp.mobius.opis.data.holders.newtypes.DataEvent; import mcp.mobius.opis.data.holders.newtypes.DataTiming; import mcp.mobius.opis.network.PacketBase; @@ -24,8 +20,6 @@ import mcp.mobius.opis.swing.SelectedTab; import mcp.mobius.opis.swing.actions.ActionRunOpisClient; import mcp.mobius.opis.swing.widgets.JTableStats; -import javax.swing.JLabel; - public class PanelRenderHandlers extends JPanel implements ITabPanel, IMessageHandler{ private JTableStats table; private JButton btnRunRender; @@ -52,7 +46,7 @@ public class PanelRenderHandlers extends JPanel implements ITabPanel, IMessageHa public void setTable(ArrayList data){ - DefaultTableModel model = (DefaultTableModel)table.getModel(); + DefaultTableModel model = table.getModel(); int row = this.updateData(table, model, DataEvent.class); for (DataEvent o : data){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderTileEnts.java b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderTileEnts.java index e442101..fc3928d 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderTileEnts.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingclient/PanelRenderTileEnts.java @@ -20,8 +20,6 @@ import net.minecraft.item.ItemStack; import javax.swing.JButton; import javax.swing.JScrollPane; import javax.swing.JTable; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.JLabel; @@ -55,7 +53,7 @@ public class PanelRenderTileEnts extends JPanel implements ITabPanel, IMessageHa public void setTable(ArrayList data){ - DefaultTableModel model = (DefaultTableModel)table.getModel(); + DefaultTableModel model = table.getModel(); int row = this.updateData(table, model, DataTileEntityRender.class); for (DataTileEntityRender o : data){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingChunks.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingChunks.java index a5a50b6..4f93a02 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingChunks.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingChunks.java @@ -1,12 +1,8 @@ package mcp.mobius.opis.swing.panels.timingserver; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.stats.StatAbstract; import mcp.mobius.opis.data.holders.stats.StatsChunk; -import mcp.mobius.opis.gui.overlay.OverlayMeanTime; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.AccessLevel; import mcp.mobius.opis.network.enums.Message; @@ -19,12 +15,7 @@ import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; import javax.swing.JButton; -import javax.swing.JLabel; import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class PanelTimingChunks extends JPanelMsgHandler implements ITabPanel{ @@ -69,9 +60,9 @@ public class PanelTimingChunks extends JPanelMsgHandler implements ITabPanel{ switch(msg){ case LIST_TIMING_CHUNK:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)table.getModel(); + DefaultTableModel model = table.getModel(); int row = this.getTable().clearTable(StatsChunk.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntities.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntities.java index ab04eeb..3fa21be 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntities.java @@ -1,14 +1,8 @@ package mcp.mobius.opis.swing.panels.timingserver; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - import mcp.mobius.opis.api.ITabPanel; -import mcp.mobius.opis.data.holders.basetypes.SerialDouble; import mcp.mobius.opis.data.holders.newtypes.DataEntity; import mcp.mobius.opis.data.holders.newtypes.DataTiming; -import mcp.mobius.opis.data.holders.stats.StatAbstract; -import mcp.mobius.opis.gui.overlay.entperchunk.OverlayEntityPerChunk; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.AccessLevel; import mcp.mobius.opis.network.enums.Message; @@ -23,10 +17,6 @@ import net.miginfocom.swing.MigLayout; import javax.swing.JButton; import javax.swing.JScrollPane; import javax.swing.JLabel; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class PanelTimingEntities extends JPanelMsgHandler implements ITabPanel{ @@ -82,9 +72,9 @@ public class PanelTimingEntities extends JPanelMsgHandler implements ITabPanel{ switch(msg){ case LIST_TIMING_ENTITIES:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)table.getModel(); + DefaultTableModel model = table.getModel(); int row = this.getTable().clearTable(DataEntity.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntitiesPerClass.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntitiesPerClass.java index 05ca76d..546fae1 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntitiesPerClass.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEntitiesPerClass.java @@ -46,9 +46,9 @@ public class PanelTimingEntitiesPerClass extends JPanelMsgHandler implements ITa case LIST_TIMING_ENTITIES_PER_CLASS:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)table.getModel(); + DefaultTableModel model = table.getModel(); int row = this.getTable().clearTable(DataEntityPerClass.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEvents.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEvents.java index 8f95c54..ed25e9c 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEvents.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingEvents.java @@ -1,7 +1,5 @@ package mcp.mobius.opis.swing.panels.timingserver; -import javax.swing.JPanel; - import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataEvent; @@ -18,7 +16,6 @@ import net.miginfocom.swing.MigLayout; import javax.swing.JButton; import javax.swing.JScrollPane; -import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableModel; @@ -49,9 +46,9 @@ public class PanelTimingEvents extends JPanelMsgHandler implements ITabPanel { case LIST_TIMING_EVENTS:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)table.getModel(); + DefaultTableModel model = table.getModel(); int row = this.getTable().clearTable(DataEvent.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingHandlers.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingHandlers.java index cbf99f0..4e71e60 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingHandlers.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingHandlers.java @@ -1,14 +1,9 @@ package mcp.mobius.opis.swing.panels.timingserver; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - import mcp.mobius.opis.api.ITabPanel; -import mcp.mobius.opis.data.holders.basetypes.SerialDouble; import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataEvent; import mcp.mobius.opis.data.holders.newtypes.DataTiming; -import mcp.mobius.opis.data.holders.stats.StatAbstract; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.AccessLevel; import mcp.mobius.opis.network.enums.Message; @@ -22,10 +17,6 @@ import net.miginfocom.swing.MigLayout; import javax.swing.JButton; import javax.swing.JScrollPane; import javax.swing.JLabel; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; @@ -65,9 +56,9 @@ public class PanelTimingHandlers extends JPanelMsgHandler implements ITabPanel{ switch(msg){ case LIST_TIMING_HANDLERS:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)table.getModel(); + DefaultTableModel model = table.getModel(); int row = this.getTable().clearTable(DataEvent.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEnts.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEnts.java index eda3a9e..0395af5 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEnts.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEnts.java @@ -1,16 +1,10 @@ package mcp.mobius.opis.swing.panels.timingserver; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - import mcp.mobius.opis.modOpis; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.basetypes.CoordinatesBlock; -import mcp.mobius.opis.data.holders.basetypes.SerialDouble; import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntity; import mcp.mobius.opis.data.holders.newtypes.DataTiming; -import mcp.mobius.opis.data.holders.stats.StatAbstract; -import mcp.mobius.opis.gui.overlay.OverlayMeanTime; import mcp.mobius.opis.helpers.ModIdentification; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.AccessLevel; @@ -22,15 +16,9 @@ import mcp.mobius.opis.swing.widgets.JButtonAccess; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import net.minecraft.item.ItemStack; - import javax.swing.JButton; import javax.swing.JScrollPane; import javax.swing.JLabel; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class PanelTimingTileEnts extends JPanelMsgHandler implements ITabPanel{ @@ -87,9 +75,9 @@ public class PanelTimingTileEnts extends JPanelMsgHandler implements ITabPanel{ switch(msg){ case LIST_TIMING_TILEENTS:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)table.getModel(); + DefaultTableModel model = table.getModel(); int row = this.getTable().clearTable(DataBlockTileEntity.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEntsPerClass.java b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEntsPerClass.java index dc4af59..120315a 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEntsPerClass.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/timingserver/PanelTimingTileEntsPerClass.java @@ -9,7 +9,6 @@ import javax.swing.table.DefaultTableModel; import net.miginfocom.swing.MigLayout; import mcp.mobius.opis.api.ITabPanel; -import mcp.mobius.opis.data.holders.newtypes.CachedString; import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntityPerClass; import mcp.mobius.opis.data.holders.newtypes.DataTiming; import mcp.mobius.opis.helpers.ModIdentification; @@ -49,9 +48,9 @@ public class PanelTimingTileEntsPerClass extends JPanelMsgHandler implements ITa case LIST_TIMING_TILEENTS_PER_CLASS:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)table.getModel(); + DefaultTableModel model = table.getModel(); int row = this.getTable().clearTable(DataBlockTileEntityPerClass.class); HashMap cumData = new HashMap(); diff --git a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountEntities.java b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountEntities.java index 9aa8ed7..90dcf0d 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountEntities.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountEntities.java @@ -1,10 +1,5 @@ package mcp.mobius.opis.swing.panels.tracking; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; - import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.basetypes.AmountHolder; import mcp.mobius.opis.network.PacketBase; @@ -21,10 +16,6 @@ import javax.swing.JCheckBox; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class PanelAmountEntities extends JPanelMsgHandler implements ITabPanel{ @@ -73,9 +64,9 @@ public class PanelAmountEntities extends JPanelMsgHandler implements ITabPanel{ public boolean handleMessage(Message msg, PacketBase rawdata) { switch(msg){ case LIST_AMOUNT_ENTITIES:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)this.getTable().getModel(); + DefaultTableModel model = this.getTable().getModel(); int row = this.getTable().clearTable(AmountHolder.class); int totalEntities = 0; diff --git a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountTileEnts.java b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountTileEnts.java index a13c787..5c98a4d 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountTileEnts.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelAmountTileEnts.java @@ -1,34 +1,23 @@ package mcp.mobius.opis.swing.panels.tracking; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; import java.util.HashMap; import mcp.mobius.opis.api.ITabPanel; -import mcp.mobius.opis.data.holders.basetypes.AmountHolder; import mcp.mobius.opis.data.holders.newtypes.DataBlockTileEntityPerClass; import mcp.mobius.opis.helpers.ModIdentification; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.AccessLevel; import mcp.mobius.opis.network.enums.Message; import mcp.mobius.opis.swing.SelectedTab; -import mcp.mobius.opis.swing.actions.ActionAmountEntities; import mcp.mobius.opis.swing.actions.ActionAmountTileEnts; import mcp.mobius.opis.swing.widgets.JButtonAccess; import mcp.mobius.opis.swing.widgets.JPanelMsgHandler; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JCheckBox; import javax.swing.JButton; -import javax.swing.JLabel; import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class PanelAmountTileEnts extends JPanelMsgHandler implements ITabPanel{ @@ -63,9 +52,9 @@ public class PanelAmountTileEnts extends JPanelMsgHandler implements ITabPanel{ switch(msg){ case LIST_AMOUNT_TILEENTS:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)table.getModel(); + DefaultTableModel model = table.getModel(); int row = this.getTable().clearTable(DataBlockTileEntityPerClass.class); HashMap cumData = new HashMap(); diff --git a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelDimensions.java b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelDimensions.java index a356d7d..8cedd57 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelDimensions.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelDimensions.java @@ -1,11 +1,8 @@ package mcp.mobius.opis.swing.panels.tracking; -import javax.swing.JPanel; - import mcp.mobius.opis.api.IMessageHandler; import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.DataDimension; -import mcp.mobius.opis.data.holders.newtypes.DataTiming; import mcp.mobius.opis.data.holders.newtypes.DataTimingMillisecond; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.AccessLevel; @@ -18,11 +15,7 @@ import mcp.mobius.opis.swing.widgets.JTableButton; import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; -import javax.swing.JTable; import javax.swing.JScrollPane; -import javax.swing.SwingConstants; -import javax.swing.UIManager; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.JButton; @@ -56,9 +49,9 @@ public class PanelDimensions extends JPanelMsgHandler implements IMessageHandler public boolean handleMessage(Message msg, PacketBase rawdata) { switch(msg){ case LIST_DIMENSION_DATA:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)this.getTable().getModel(); + DefaultTableModel model = this.getTable().getModel(); int row = this.getTable().clearTable(DataDimension.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelPlayers.java b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelPlayers.java index bbae456..ddff17c 100644 --- a/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelPlayers.java +++ b/src/main/java/mcp/mobius/opis/swing/panels/tracking/PanelPlayers.java @@ -1,11 +1,7 @@ package mcp.mobius.opis.swing.panels.tracking; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - import mcp.mobius.opis.api.ITabPanel; import mcp.mobius.opis.data.holders.newtypes.DataEntity; -import mcp.mobius.opis.gui.overlay.entperchunk.OverlayEntityPerChunk; import mcp.mobius.opis.network.PacketBase; import mcp.mobius.opis.network.enums.AccessLevel; import mcp.mobius.opis.network.enums.Message; @@ -17,11 +13,7 @@ import mcp.mobius.opis.swing.widgets.JTableStats; import net.miginfocom.swing.MigLayout; import javax.swing.JButton; -import javax.swing.JLabel; import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.SwingConstants; -import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class PanelPlayers extends JPanelMsgHandler implements ITabPanel{ @@ -74,9 +66,9 @@ public class PanelPlayers extends JPanelMsgHandler implements ITabPanel{ switch(msg){ case LIST_PLAYERS:{ - ((JTableStats)this.getTable()).setTableData(rawdata.array); + this.getTable().setTableData(rawdata.array); - DefaultTableModel model = (DefaultTableModel)this.getTable().getModel(); + DefaultTableModel model = this.getTable().getModel(); int row = this.getTable().clearTable(DataEntity.class); for (Object o : rawdata.array){ diff --git a/src/main/java/mcp/mobius/opis/swing/widgets/JPanelMsgHandler.java b/src/main/java/mcp/mobius/opis/swing/widgets/JPanelMsgHandler.java index 5dab0ea..b97550b 100644 --- a/src/main/java/mcp/mobius/opis/swing/widgets/JPanelMsgHandler.java +++ b/src/main/java/mcp/mobius/opis/swing/widgets/JPanelMsgHandler.java @@ -1,12 +1,7 @@ package mcp.mobius.opis.swing.widgets; import javax.swing.JPanel; -import javax.swing.JTable; -import javax.swing.table.DefaultTableModel; - -import mapwriter.api.IMwDataProvider; import mcp.mobius.opis.api.IMessageHandler; -import mcp.mobius.opis.data.holders.stats.StatAbstract; public abstract class JPanelMsgHandler extends JPanel implements IMessageHandler { diff --git a/src/main/java/mcp/mobius/opis/swing/widgets/JTableButton.java b/src/main/java/mcp/mobius/opis/swing/widgets/JTableButton.java index 08b7aed..ba5ce5d 100644 --- a/src/main/java/mcp/mobius/opis/swing/widgets/JTableButton.java +++ b/src/main/java/mcp/mobius/opis/swing/widgets/JTableButton.java @@ -140,6 +140,7 @@ public class JTableButton extends AbstractCellEditor // // Implement TableCellRenderer interface // + @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { @@ -189,6 +190,7 @@ public class JTableButton extends AbstractCellEditor /* * The button has been pressed. Stop editing and invoke the custom Action */ + @Override public void actionPerformed(ActionEvent e) { int row = table.convertRowIndexToModel( table.getEditingRow() ); @@ -205,14 +207,16 @@ public class JTableButton extends AbstractCellEditor * the mouse to another cell before releasing it, the editor is still * active. Make sure editing is stopped when the mouse is released. */ - public void mousePressed(MouseEvent e) + @Override + public void mousePressed(MouseEvent e) { if (table.isEditing() && table.getCellEditor() == this) isButtonColumnEditor = true; } - public void mouseReleased(MouseEvent e) + @Override + public void mouseReleased(MouseEvent e) { if (isButtonColumnEditor && table.isEditing()) @@ -221,7 +225,10 @@ public class JTableButton extends AbstractCellEditor isButtonColumnEditor = false; } - public void mouseClicked(MouseEvent e) {} + @Override + public void mouseClicked(MouseEvent e) {} + @Override public void mouseEntered(MouseEvent e) {} - public void mouseExited(MouseEvent e) {} + @Override + public void mouseExited(MouseEvent e) {} } \ No newline at end of file diff --git a/src/main/java/mcp/mobius/opis/swing/widgets/JTableStats.java b/src/main/java/mcp/mobius/opis/swing/widgets/JTableStats.java index e10e8c0..655f5d6 100644 --- a/src/main/java/mcp/mobius/opis/swing/widgets/JTableStats.java +++ b/src/main/java/mcp/mobius/opis/swing/widgets/JTableStats.java @@ -10,7 +10,6 @@ import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import mcp.mobius.opis.data.holders.ISerializable; -import mcp.mobius.opis.data.holders.stats.StatAbstract; public class JTableStats extends JTable { @@ -102,6 +101,7 @@ public class JTableStats extends JTable { this.statistics.addAll(statistics); } + @Override public DefaultTableModel getModel(){ return (DefaultTableModel)super.getModel(); } diff --git a/src/main/java/mcp/mobius/opis/tools/BlockDebug.java b/src/main/java/mcp/mobius/opis/tools/BlockDebug.java index c893cb2..bc13c28 100644 --- a/src/main/java/mcp/mobius/opis/tools/BlockDebug.java +++ b/src/main/java/mcp/mobius/opis/tools/BlockDebug.java @@ -1,6 +1,5 @@ package mcp.mobius.opis.tools; -import mcp.mobius.opis.modOpis; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.tileentity.TileEntity; diff --git a/src/main/java/mcp/mobius/opis/tools/TileDebug.java b/src/main/java/mcp/mobius/opis/tools/TileDebug.java index 2add395..8aeff26 100644 --- a/src/main/java/mcp/mobius/opis/tools/TileDebug.java +++ b/src/main/java/mcp/mobius/opis/tools/TileDebug.java @@ -1,6 +1,5 @@ package mcp.mobius.opis.tools; -import cpw.mods.fml.common.FMLCommonHandler; import mcp.mobius.opis.modOpis; import net.minecraft.tileentity.TileEntity; @@ -19,6 +18,7 @@ public class TileDebug extends TileEntity { } + @Override public void updateEntity(){ } } diff --git a/src/main/java/mcp/mobius/opis/tools/TileLag.java b/src/main/java/mcp/mobius/opis/tools/TileLag.java index 0cb2a3b..54f5f9d 100644 --- a/src/main/java/mcp/mobius/opis/tools/TileLag.java +++ b/src/main/java/mcp/mobius/opis/tools/TileLag.java @@ -4,6 +4,7 @@ import net.minecraft.tileentity.TileEntity; public class TileLag extends TileEntity { + @Override public void updateEntity(){ if (this.worldObj.isRemote) return; diff --git a/src/main/java/net/minecraft/client/renderer/entity/RenderManager.java b/src/main/java/net/minecraft/client/renderer/entity/RenderManager.java deleted file mode 100644 index 36dbe45..0000000 --- a/src/main/java/net/minecraft/client/renderer/entity/RenderManager.java +++ /dev/null @@ -1,413 +0,0 @@ -package net.minecraft.client.renderer.entity; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import net.minecraft.block.Block; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.model.ModelChicken; -import net.minecraft.client.model.ModelCow; -import net.minecraft.client.model.ModelHorse; -import net.minecraft.client.model.ModelOcelot; -import net.minecraft.client.model.ModelPig; -import net.minecraft.client.model.ModelSheep1; -import net.minecraft.client.model.ModelSheep2; -import net.minecraft.client.model.ModelSlime; -import net.minecraft.client.model.ModelSquid; -import net.minecraft.client.model.ModelWolf; -import net.minecraft.client.model.ModelZombie; -import net.minecraft.client.renderer.ItemRenderer; -import net.minecraft.client.renderer.OpenGlHelper; -import net.minecraft.client.renderer.RenderGlobal; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.client.renderer.tileentity.RenderEnderCrystal; -import net.minecraft.client.renderer.tileentity.RenderItemFrame; -import net.minecraft.client.renderer.tileentity.RenderWitherSkull; -import net.minecraft.client.settings.GameSettings; -import net.minecraft.crash.CrashReport; -import net.minecraft.crash.CrashReportCategory; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLeashKnot; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.ai.EntityMinecartMobSpawner; -import net.minecraft.entity.boss.EntityDragon; -import net.minecraft.entity.boss.EntityWither; -import net.minecraft.entity.effect.EntityLightningBolt; -import net.minecraft.entity.item.EntityBoat; -import net.minecraft.entity.item.EntityEnderCrystal; -import net.minecraft.entity.item.EntityEnderEye; -import net.minecraft.entity.item.EntityEnderPearl; -import net.minecraft.entity.item.EntityExpBottle; -import net.minecraft.entity.item.EntityFallingBlock; -import net.minecraft.entity.item.EntityFireworkRocket; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.item.EntityItemFrame; -import net.minecraft.entity.item.EntityMinecart; -import net.minecraft.entity.item.EntityMinecartTNT; -import net.minecraft.entity.item.EntityPainting; -import net.minecraft.entity.item.EntityTNTPrimed; -import net.minecraft.entity.item.EntityXPOrb; -import net.minecraft.entity.monster.EntityBlaze; -import net.minecraft.entity.monster.EntityCaveSpider; -import net.minecraft.entity.monster.EntityCreeper; -import net.minecraft.entity.monster.EntityEnderman; -import net.minecraft.entity.monster.EntityGhast; -import net.minecraft.entity.monster.EntityGiantZombie; -import net.minecraft.entity.monster.EntityIronGolem; -import net.minecraft.entity.monster.EntityMagmaCube; -import net.minecraft.entity.monster.EntitySilverfish; -import net.minecraft.entity.monster.EntitySkeleton; -import net.minecraft.entity.monster.EntitySlime; -import net.minecraft.entity.monster.EntitySnowman; -import net.minecraft.entity.monster.EntitySpider; -import net.minecraft.entity.monster.EntityWitch; -import net.minecraft.entity.monster.EntityZombie; -import net.minecraft.entity.passive.EntityBat; -import net.minecraft.entity.passive.EntityChicken; -import net.minecraft.entity.passive.EntityCow; -import net.minecraft.entity.passive.EntityHorse; -import net.minecraft.entity.passive.EntityMooshroom; -import net.minecraft.entity.passive.EntityOcelot; -import net.minecraft.entity.passive.EntityPig; -import net.minecraft.entity.passive.EntitySheep; -import net.minecraft.entity.passive.EntitySquid; -import net.minecraft.entity.passive.EntityVillager; -import net.minecraft.entity.passive.EntityWolf; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.projectile.EntityArrow; -import net.minecraft.entity.projectile.EntityEgg; -import net.minecraft.entity.projectile.EntityFishHook; -import net.minecraft.entity.projectile.EntityLargeFireball; -import net.minecraft.entity.projectile.EntityPotion; -import net.minecraft.entity.projectile.EntitySmallFireball; -import net.minecraft.entity.projectile.EntitySnowball; -import net.minecraft.entity.projectile.EntityWitherSkull; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.MathHelper; -import net.minecraft.util.ReportedException; -import net.minecraft.world.World; - -import org.lwjgl.opengl.GL11; - -@SideOnly(Side.CLIENT) -public class RenderManager -{ - /** A map of entity classes and the associated renderer. */ - public Map entityRenderMap = new HashMap(); - /** The static instance of RenderManager. */ - public static RenderManager instance = new RenderManager(); - /** Renders fonts */ - private FontRenderer fontRenderer; - public static double renderPosX; - public static double renderPosY; - public static double renderPosZ; - public TextureManager renderEngine; - public ItemRenderer itemRenderer; - /** Reference to the World object. */ - public World worldObj; - /** Rendermanager's variable for the player */ - public EntityLivingBase livingPlayer; - public Entity field_147941_i; - public float playerViewY; - public float playerViewX; - /** Reference to the GameSettings object. */ - public GameSettings options; - public double viewerPosX; - public double viewerPosY; - public double viewerPosZ; - /** whether bounding box should be rendered or not */ - public static boolean debugBoundingBox; - private static final String __OBFID = "CL_00000991"; - - private RenderManager() - { - this.entityRenderMap.put(EntityCaveSpider.class, new RenderCaveSpider()); - this.entityRenderMap.put(EntitySpider.class, new RenderSpider()); - this.entityRenderMap.put(EntityPig.class, new RenderPig(new ModelPig(), new ModelPig(0.5F), 0.7F)); - this.entityRenderMap.put(EntitySheep.class, new RenderSheep(new ModelSheep2(), new ModelSheep1(), 0.7F)); - this.entityRenderMap.put(EntityCow.class, new RenderCow(new ModelCow(), 0.7F)); - this.entityRenderMap.put(EntityMooshroom.class, new RenderMooshroom(new ModelCow(), 0.7F)); - this.entityRenderMap.put(EntityWolf.class, new RenderWolf(new ModelWolf(), new ModelWolf(), 0.5F)); - this.entityRenderMap.put(EntityChicken.class, new RenderChicken(new ModelChicken(), 0.3F)); - this.entityRenderMap.put(EntityOcelot.class, new RenderOcelot(new ModelOcelot(), 0.4F)); - this.entityRenderMap.put(EntitySilverfish.class, new RenderSilverfish()); - this.entityRenderMap.put(EntityCreeper.class, new RenderCreeper()); - this.entityRenderMap.put(EntityEnderman.class, new RenderEnderman()); - this.entityRenderMap.put(EntitySnowman.class, new RenderSnowMan()); - this.entityRenderMap.put(EntitySkeleton.class, new RenderSkeleton()); - this.entityRenderMap.put(EntityWitch.class, new RenderWitch()); - this.entityRenderMap.put(EntityBlaze.class, new RenderBlaze()); - this.entityRenderMap.put(EntityZombie.class, new RenderZombie()); - this.entityRenderMap.put(EntitySlime.class, new RenderSlime(new ModelSlime(16), new ModelSlime(0), 0.25F)); - this.entityRenderMap.put(EntityMagmaCube.class, new RenderMagmaCube()); - this.entityRenderMap.put(EntityPlayer.class, new RenderPlayer()); - this.entityRenderMap.put(EntityGiantZombie.class, new RenderGiantZombie(new ModelZombie(), 0.5F, 6.0F)); - this.entityRenderMap.put(EntityGhast.class, new RenderGhast()); - this.entityRenderMap.put(EntitySquid.class, new RenderSquid(new ModelSquid(), 0.7F)); - this.entityRenderMap.put(EntityVillager.class, new RenderVillager()); - this.entityRenderMap.put(EntityIronGolem.class, new RenderIronGolem()); - this.entityRenderMap.put(EntityBat.class, new RenderBat()); - this.entityRenderMap.put(EntityDragon.class, new RenderDragon()); - this.entityRenderMap.put(EntityEnderCrystal.class, new RenderEnderCrystal()); - this.entityRenderMap.put(EntityWither.class, new RenderWither()); - this.entityRenderMap.put(Entity.class, new RenderEntity()); - this.entityRenderMap.put(EntityPainting.class, new RenderPainting()); - this.entityRenderMap.put(EntityItemFrame.class, new RenderItemFrame()); - this.entityRenderMap.put(EntityLeashKnot.class, new RenderLeashKnot()); - this.entityRenderMap.put(EntityArrow.class, new RenderArrow()); - this.entityRenderMap.put(EntitySnowball.class, new RenderSnowball(Items.snowball)); - this.entityRenderMap.put(EntityEnderPearl.class, new RenderSnowball(Items.ender_pearl)); - this.entityRenderMap.put(EntityEnderEye.class, new RenderSnowball(Items.ender_eye)); - this.entityRenderMap.put(EntityEgg.class, new RenderSnowball(Items.egg)); - this.entityRenderMap.put(EntityPotion.class, new RenderSnowball(Items.potionitem, 16384)); - this.entityRenderMap.put(EntityExpBottle.class, new RenderSnowball(Items.experience_bottle)); - this.entityRenderMap.put(EntityFireworkRocket.class, new RenderSnowball(Items.fireworks)); - this.entityRenderMap.put(EntityLargeFireball.class, new RenderFireball(2.0F)); - this.entityRenderMap.put(EntitySmallFireball.class, new RenderFireball(0.5F)); - this.entityRenderMap.put(EntityWitherSkull.class, new RenderWitherSkull()); - this.entityRenderMap.put(EntityItem.class, new RenderItem()); - this.entityRenderMap.put(EntityXPOrb.class, new RenderXPOrb()); - this.entityRenderMap.put(EntityTNTPrimed.class, new RenderTNTPrimed()); - this.entityRenderMap.put(EntityFallingBlock.class, new RenderFallingBlock()); - this.entityRenderMap.put(EntityMinecartTNT.class, new RenderTntMinecart()); - this.entityRenderMap.put(EntityMinecartMobSpawner.class, new RenderMinecartMobSpawner()); - this.entityRenderMap.put(EntityMinecart.class, new RenderMinecart()); - this.entityRenderMap.put(EntityBoat.class, new RenderBoat()); - this.entityRenderMap.put(EntityFishHook.class, new RenderFish()); - this.entityRenderMap.put(EntityHorse.class, new RenderHorse(new ModelHorse(), 0.75F)); - this.entityRenderMap.put(EntityLightningBolt.class, new RenderLightningBolt()); - Iterator iterator = this.entityRenderMap.values().iterator(); - - while (iterator.hasNext()) - { - Render render = (Render)iterator.next(); - render.setRenderManager(this); - } - } - - public Render getEntityClassRenderObject(Class par1Class) - { - Render render = (Render)this.entityRenderMap.get(par1Class); - - if (render == null && par1Class != Entity.class) - { - render = this.getEntityClassRenderObject(par1Class.getSuperclass()); - this.entityRenderMap.put(par1Class, render); - } - - return render; - } - - public Render getEntityRenderObject(Entity par1Entity) - { - return this.getEntityClassRenderObject(par1Entity.getClass()); - } - - public void cacheActiveRenderInfo(World p_147938_1_, TextureManager p_147938_2_, FontRenderer p_147938_3_, EntityLivingBase p_147938_4_, Entity p_147938_5_, GameSettings p_147938_6_, float p_147938_7_) - { - this.worldObj = p_147938_1_; - this.renderEngine = p_147938_2_; - this.options = p_147938_6_; - this.livingPlayer = p_147938_4_; - this.field_147941_i = p_147938_5_; - this.fontRenderer = p_147938_3_; - - if (p_147938_4_.isPlayerSleeping()) - { - Block block = p_147938_1_.getBlock(MathHelper.floor_double(p_147938_4_.posX), MathHelper.floor_double(p_147938_4_.posY), MathHelper.floor_double(p_147938_4_.posZ)); - int x = MathHelper.floor_double(p_147938_4_.posX); - int y = MathHelper.floor_double(p_147938_4_.posY); - int z = MathHelper.floor_double(p_147938_4_.posZ); - - if (block.isBed(p_147938_1_, x, y, z, p_147938_4_)) - { - int j = block.getBedDirection(p_147938_1_, x, y, z); - this.playerViewY = (float)(j * 90 + 180); - this.playerViewX = 0.0F; - } - } - else - { - this.playerViewY = p_147938_4_.prevRotationYaw + (p_147938_4_.rotationYaw - p_147938_4_.prevRotationYaw) * p_147938_7_; - this.playerViewX = p_147938_4_.prevRotationPitch + (p_147938_4_.rotationPitch - p_147938_4_.prevRotationPitch) * p_147938_7_; - } - - if (p_147938_6_.thirdPersonView == 2) - { - this.playerViewY += 180.0F; - } - - this.viewerPosX = p_147938_4_.lastTickPosX + (p_147938_4_.posX - p_147938_4_.lastTickPosX) * (double)p_147938_7_; - this.viewerPosY = p_147938_4_.lastTickPosY + (p_147938_4_.posY - p_147938_4_.lastTickPosY) * (double)p_147938_7_; - this.viewerPosZ = p_147938_4_.lastTickPosZ + (p_147938_4_.posZ - p_147938_4_.lastTickPosZ) * (double)p_147938_7_; - } - - public boolean renderEntitySimple(Entity p_147937_1_, float p_147937_2_) - { - return this.renderEntityStatic(p_147937_1_, p_147937_2_, false); - } - - public boolean renderEntityStatic(Entity p_147936_1_, float p_147936_2_, boolean p_147936_3_) - { - ProfilerSection.RENDER_ENTITY.start(p_147936_1_); - - if (p_147936_1_.ticksExisted == 0) - { - p_147936_1_.lastTickPosX = p_147936_1_.posX; - p_147936_1_.lastTickPosY = p_147936_1_.posY; - p_147936_1_.lastTickPosZ = p_147936_1_.posZ; - } - - double d0 = p_147936_1_.lastTickPosX + (p_147936_1_.posX - p_147936_1_.lastTickPosX) * (double)p_147936_2_; - double d1 = p_147936_1_.lastTickPosY + (p_147936_1_.posY - p_147936_1_.lastTickPosY) * (double)p_147936_2_; - double d2 = p_147936_1_.lastTickPosZ + (p_147936_1_.posZ - p_147936_1_.lastTickPosZ) * (double)p_147936_2_; - float f1 = p_147936_1_.prevRotationYaw + (p_147936_1_.rotationYaw - p_147936_1_.prevRotationYaw) * p_147936_2_; - int i = p_147936_1_.getBrightnessForRender(p_147936_2_); - - if (p_147936_1_.isBurning()) - { - i = 15728880; - } - - int j = i % 65536; - int k = i / 65536; - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float)j / 1.0F, (float)k / 1.0F); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - boolean retVal = this.func_147939_a(p_147936_1_, d0 - renderPosX, d1 - renderPosY, d2 - renderPosZ, f1, p_147936_2_, p_147936_3_); - - ProfilerSection.RENDER_ENTITY.stop(p_147936_1_); - return retVal; - } - - public boolean renderEntityWithPosYaw(Entity p_147940_1_, double p_147940_2_, double p_147940_4_, double p_147940_6_, float p_147940_8_, float p_147940_9_) - { - return this.func_147939_a(p_147940_1_, p_147940_2_, p_147940_4_, p_147940_6_, p_147940_8_, p_147940_9_, false); - } - - public boolean func_147939_a(Entity p_147939_1_, double p_147939_2_, double p_147939_4_, double p_147939_6_, float p_147939_8_, float p_147939_9_, boolean p_147939_10_) - { - Render render = null; - - try - { - render = this.getEntityRenderObject(p_147939_1_); - - if (render != null && this.renderEngine != null) - { - if (!render.isStaticEntity() || p_147939_10_) - { - try - { - render.doRender(p_147939_1_, p_147939_2_, p_147939_4_, p_147939_6_, p_147939_8_, p_147939_9_); - } - catch (Throwable throwable2) - { - throw new ReportedException(CrashReport.makeCrashReport(throwable2, "Rendering entity in world")); - } - - try - { - render.doRenderShadowAndFire(p_147939_1_, p_147939_2_, p_147939_4_, p_147939_6_, p_147939_8_, p_147939_9_); - } - catch (Throwable throwable1) - { - throw new ReportedException(CrashReport.makeCrashReport(throwable1, "Post-rendering entity in world")); - } - - if (debugBoundingBox && !p_147939_1_.isInvisible() && !p_147939_10_) - { - try - { - this.renderDebugBoundingBox(p_147939_1_, p_147939_2_, p_147939_4_, p_147939_6_, p_147939_8_, p_147939_9_); - } - catch (Throwable throwable) - { - throw new ReportedException(CrashReport.makeCrashReport(throwable, "Rendering entity hitbox in world")); - } - } - } - } - else if (this.renderEngine != null) - { - return false; - } - - return true; - } - catch (Throwable throwable3) - { - CrashReport crashreport = CrashReport.makeCrashReport(throwable3, "Rendering entity in world"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Entity being rendered"); - p_147939_1_.addEntityCrashInfo(crashreportcategory); - CrashReportCategory crashreportcategory1 = crashreport.makeCategory("Renderer details"); - crashreportcategory1.addCrashSection("Assigned renderer", render); - crashreportcategory1.addCrashSection("Location", CrashReportCategory.func_85074_a(p_147939_2_, p_147939_4_, p_147939_6_)); - crashreportcategory1.addCrashSection("Rotation", Float.valueOf(p_147939_8_)); - crashreportcategory1.addCrashSection("Delta", Float.valueOf(p_147939_9_)); - throw new ReportedException(crashreport); - } - } - - /** - * Renders the bounding box around an entity when F3+B is pressed - */ - private void renderDebugBoundingBox(Entity par1Entity, double par2, double par4, double par6, float par8, float par9) - { - GL11.glDepthMask(false); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_CULL_FACE); - GL11.glDisable(GL11.GL_BLEND); - float f2 = par1Entity.width / 2.0F; - AxisAlignedBB axisalignedbb = AxisAlignedBB.getAABBPool().getAABB(par2 - (double)f2, par4, par6 - (double)f2, par2 + (double)f2, par4 + (double)par1Entity.height, par6 + (double)f2); - RenderGlobal.drawOutlinedBoundingBox(axisalignedbb, 16777215); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_CULL_FACE); - GL11.glDisable(GL11.GL_BLEND); - GL11.glDepthMask(true); - } - - /** - * World sets this RenderManager's worldObj to the world provided - */ - public void set(World par1World) - { - this.worldObj = par1World; - } - - public double getDistanceToCamera(double par1, double par3, double par5) - { - double d3 = par1 - this.viewerPosX; - double d4 = par3 - this.viewerPosY; - double d5 = par5 - this.viewerPosZ; - return d3 * d3 + d4 * d4 + d5 * d5; - } - - /** - * Returns the font renderer - */ - public FontRenderer getFontRenderer() - { - return this.fontRenderer; - } - - public void updateIcons(IIconRegister par1IconRegister) - { - Iterator iterator = this.entityRenderMap.values().iterator(); - - while (iterator.hasNext()) - { - Render render = (Render)iterator.next(); - render.updateIcons(par1IconRegister); - } - } -} \ No newline at end of file diff --git a/src/main/java/net/minecraft/client/renderer/tileentity/TileEntityRendererDispatcher.java b/src/main/java/net/minecraft/client/renderer/tileentity/TileEntityRendererDispatcher.java deleted file mode 100644 index e9b82aa..0000000 --- a/src/main/java/net/minecraft/client/renderer/tileentity/TileEntityRendererDispatcher.java +++ /dev/null @@ -1,181 +0,0 @@ -package net.minecraft.client.renderer.tileentity; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.OpenGlHelper; -import net.minecraft.client.renderer.entity.RenderEnchantmentTable; -import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.crash.CrashReport; -import net.minecraft.crash.CrashReportCategory; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.tileentity.TileEntityBeacon; -import net.minecraft.tileentity.TileEntityChest; -import net.minecraft.tileentity.TileEntityEnchantmentTable; -import net.minecraft.tileentity.TileEntityEndPortal; -import net.minecraft.tileentity.TileEntityEnderChest; -import net.minecraft.tileentity.TileEntityMobSpawner; -import net.minecraft.tileentity.TileEntityPiston; -import net.minecraft.tileentity.TileEntitySign; -import net.minecraft.tileentity.TileEntitySkull; -import net.minecraft.util.ReportedException; -import net.minecraft.world.World; - -import org.lwjgl.opengl.GL11; - -@SideOnly(Side.CLIENT) -public class TileEntityRendererDispatcher -{ - public Map mapSpecialRenderers = new HashMap(); - public static TileEntityRendererDispatcher instance = new TileEntityRendererDispatcher(); - private FontRenderer field_147557_n; - /** The player's current X position (same as playerX) */ - public static double staticPlayerX; - /** The player's current Y position (same as playerY) */ - public static double staticPlayerY; - /** The player's current Z position (same as playerZ) */ - public static double staticPlayerZ; - public TextureManager field_147553_e; - public World field_147550_f; - public EntityLivingBase field_147551_g; - public float field_147562_h; - public float field_147563_i; - public double field_147560_j; - public double field_147561_k; - public double field_147558_l; - private static final String __OBFID = "CL_00000963"; - - private TileEntityRendererDispatcher() - { - this.mapSpecialRenderers.put(TileEntitySign.class, new TileEntitySignRenderer()); - this.mapSpecialRenderers.put(TileEntityMobSpawner.class, new TileEntityMobSpawnerRenderer()); - this.mapSpecialRenderers.put(TileEntityPiston.class, new TileEntityRendererPiston()); - this.mapSpecialRenderers.put(TileEntityChest.class, new TileEntityChestRenderer()); - this.mapSpecialRenderers.put(TileEntityEnderChest.class, new TileEntityEnderChestRenderer()); - this.mapSpecialRenderers.put(TileEntityEnchantmentTable.class, new RenderEnchantmentTable()); - this.mapSpecialRenderers.put(TileEntityEndPortal.class, new RenderEndPortal()); - this.mapSpecialRenderers.put(TileEntityBeacon.class, new TileEntityBeaconRenderer()); - this.mapSpecialRenderers.put(TileEntitySkull.class, new TileEntitySkullRenderer()); - Iterator iterator = this.mapSpecialRenderers.values().iterator(); - - while (iterator.hasNext()) - { - TileEntitySpecialRenderer tileentityspecialrenderer = (TileEntitySpecialRenderer)iterator.next(); - tileentityspecialrenderer.func_147497_a(this); - } - } - - public TileEntitySpecialRenderer getSpecialRendererByClass(Class p_147546_1_) - { - TileEntitySpecialRenderer tileentityspecialrenderer = (TileEntitySpecialRenderer)this.mapSpecialRenderers.get(p_147546_1_); - - if (tileentityspecialrenderer == null && p_147546_1_ != TileEntity.class) - { - tileentityspecialrenderer = this.getSpecialRendererByClass(p_147546_1_.getSuperclass()); - this.mapSpecialRenderers.put(p_147546_1_, tileentityspecialrenderer); - } - - return tileentityspecialrenderer; - } - - /** - * Returns true if this TileEntity instance has a TileEntitySpecialRenderer associated with it, false otherwise. - */ - public boolean hasSpecialRenderer(TileEntity p_147545_1_) - { - return this.getSpecialRenderer(p_147545_1_) != null; - } - - public TileEntitySpecialRenderer getSpecialRenderer(TileEntity p_147547_1_) - { - return p_147547_1_ == null ? null : this.getSpecialRendererByClass(p_147547_1_.getClass()); - } - - public void cacheActiveRenderInfo(World p_147542_1_, TextureManager p_147542_2_, FontRenderer p_147542_3_, EntityLivingBase p_147542_4_, float p_147542_5_) - { - if (this.field_147550_f != p_147542_1_) - { - this.func_147543_a(p_147542_1_); - } - - this.field_147553_e = p_147542_2_; - this.field_147551_g = p_147542_4_; - this.field_147557_n = p_147542_3_; - this.field_147562_h = p_147542_4_.prevRotationYaw + (p_147542_4_.rotationYaw - p_147542_4_.prevRotationYaw) * p_147542_5_; - this.field_147563_i = p_147542_4_.prevRotationPitch + (p_147542_4_.rotationPitch - p_147542_4_.prevRotationPitch) * p_147542_5_; - this.field_147560_j = p_147542_4_.lastTickPosX + (p_147542_4_.posX - p_147542_4_.lastTickPosX) * (double)p_147542_5_; - this.field_147561_k = p_147542_4_.lastTickPosY + (p_147542_4_.posY - p_147542_4_.lastTickPosY) * (double)p_147542_5_; - this.field_147558_l = p_147542_4_.lastTickPosZ + (p_147542_4_.posZ - p_147542_4_.lastTickPosZ) * (double)p_147542_5_; - } - - /** - * Render this TileEntity at its current position from the player - */ - public void renderTileEntity(TileEntity p_147544_1_, float p_147544_2_) - { - if (p_147544_1_.getDistanceFrom(this.field_147560_j, this.field_147561_k, this.field_147558_l) < p_147544_1_.getMaxRenderDistanceSquared()) - { - int i = this.field_147550_f.getLightBrightnessForSkyBlocks(p_147544_1_.xCoord, p_147544_1_.yCoord, p_147544_1_.zCoord, 0); - int j = i % 65536; - int k = i / 65536; - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float)j / 1.0F, (float)k / 1.0F); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - this.renderTileEntityAt(p_147544_1_, (double)p_147544_1_.xCoord - staticPlayerX, (double)p_147544_1_.yCoord - staticPlayerY, (double)p_147544_1_.zCoord - staticPlayerZ, p_147544_2_); - } - } - - /** - * Render this TileEntity at a given set of coordinates - */ - public void renderTileEntityAt(TileEntity p_147549_1_, double p_147549_2_, double p_147549_4_, double p_147549_6_, float p_147549_8_) - { - ProfilerSection.RENDER_TILEENTITY.start(p_147549_1_); - - TileEntitySpecialRenderer tileentityspecialrenderer = this.getSpecialRenderer(p_147549_1_); - - if (tileentityspecialrenderer != null) - { - try - { - tileentityspecialrenderer.renderTileEntityAt(p_147549_1_, p_147549_2_, p_147549_4_, p_147549_6_, p_147549_8_); - } - catch (Throwable throwable) - { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Rendering Block Entity"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Block Entity Details"); - p_147549_1_.func_145828_a(crashreportcategory); - throw new ReportedException(crashreport); - } - } - - ProfilerSection.RENDER_TILEENTITY.stop(p_147549_1_); - } - - public void func_147543_a(World p_147543_1_) - { - this.field_147550_f = p_147543_1_; - Iterator iterator = this.mapSpecialRenderers.values().iterator(); - - while (iterator.hasNext()) - { - TileEntitySpecialRenderer tileentityspecialrenderer = (TileEntitySpecialRenderer)iterator.next(); - - if (tileentityspecialrenderer != null) - { - tileentityspecialrenderer.func_147496_a(p_147543_1_); - } - } - } - - public FontRenderer getFontRenderer() - { - return this.field_147557_n; - } -} \ No newline at end of file diff --git a/src/main/java/net/minecraft/network/NetworkManager.java b/src/main/java/net/minecraft/network/NetworkManager.java deleted file mode 100644 index f590f1a..0000000 --- a/src/main/java/net/minecraft/network/NetworkManager.java +++ /dev/null @@ -1,395 +0,0 @@ -package net.minecraft.network; - -import com.google.common.collect.Queues; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import cpw.mods.fml.common.network.internal.FMLProxyPacket; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelException; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.channel.local.LocalChannel; -import io.netty.channel.local.LocalServerChannel; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.timeout.ReadTimeoutHandler; -import io.netty.util.AttributeKey; -import io.netty.util.concurrent.GenericFutureListener; - -import java.net.InetAddress; -import java.net.SocketAddress; -import java.util.Queue; - -import javax.crypto.SecretKey; - -import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import net.minecraft.util.ChatComponentTranslation; -import net.minecraft.util.CryptManager; -import net.minecraft.util.IChatComponent; -import net.minecraft.util.MessageDeserializer; -import net.minecraft.util.MessageDeserializer2; -import net.minecraft.util.MessageSerializer; -import net.minecraft.util.MessageSerializer2; - -import org.apache.commons.lang3.Validate; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; - -public class NetworkManager extends SimpleChannelInboundHandler -{ - private static final Logger logger = LogManager.getLogger(); - public static final Marker logMarkerNetwork = MarkerManager.getMarker("NETWORK"); - public static final Marker logMarkerPackets = MarkerManager.getMarker("NETWORK_PACKETS", logMarkerNetwork); - public static final AttributeKey attrKeyConnectionState = new AttributeKey("protocol"); - public static final AttributeKey attrKeyReceivable = new AttributeKey("receivable_packets"); - public static final AttributeKey attrKeySendable = new AttributeKey("sendable_packets"); - public static final NioEventLoopGroup eventLoops = new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Client IO #%d").setDaemon(true).build()); - /** - * Whether this NetworkManager deals with the client or server side of the connection - */ - private final boolean isClientSide; - /** - * The queue for received, unprioritized packets that will be processed at the earliest opportunity - */ - private final Queue receivedPacketsQueue = Queues.newConcurrentLinkedQueue(); - /** The queue for packets that require transmission */ - private final Queue outboundPacketsQueue = Queues.newConcurrentLinkedQueue(); - /** The active channel used to send data */ - private Channel channel; - /** The address of the remote party */ - private SocketAddress socketAddress; - /** The INetHandler instance responsible for processing received packets */ - private INetHandler netHandler; - /** - * The current connection state, being one of: HANDSHAKING, PLAY, STATUS, LOGIN - */ - private EnumConnectionState connectionState; - /** A String indicating why the network has shutdown. */ - private IChatComponent terminationReason; - private static final String __OBFID = "CL_00001240"; - - public NetworkManager(boolean p_i45147_1_) - { - this.isClientSide = p_i45147_1_; - } - - public void channelActive(ChannelHandlerContext p_channelActive_1_) throws Exception - { - super.channelActive(p_channelActive_1_); - this.channel = p_channelActive_1_.channel(); - this.socketAddress = this.channel.remoteAddress(); - this.setConnectionState(EnumConnectionState.HANDSHAKING); - } - - /** - * Sets the new connection state and registers which packets this channel may send and receive - */ - public void setConnectionState(EnumConnectionState p_150723_1_) - { - this.connectionState = (EnumConnectionState)this.channel.attr(attrKeyConnectionState).getAndSet(p_150723_1_); - this.channel.attr(attrKeyReceivable).set(p_150723_1_.func_150757_a(this.isClientSide)); - this.channel.attr(attrKeySendable).set(p_150723_1_.func_150754_b(this.isClientSide)); - this.channel.config().setAutoRead(true); - logger.debug("Enabled auto read"); - } - - public void channelInactive(ChannelHandlerContext p_channelInactive_1_) - { - this.closeChannel(new ChatComponentTranslation("disconnect.endOfStream", new Object[0])); - } - - public void exceptionCaught(ChannelHandlerContext p_exceptionCaught_1_, Throwable p_exceptionCaught_2_) - { - this.closeChannel(new ChatComponentTranslation("disconnect.genericReason", new Object[] {"Internal Exception: " + p_exceptionCaught_2_})); - } - - protected void channelRead0(ChannelHandlerContext p_150728_1_, Packet p_150728_2_) - { - if (this.channel.isOpen()) - { - if (p_150728_2_.hasPriority()) - { - p_150728_2_.processPacket(this.netHandler); - } - else - { - this.receivedPacketsQueue.add(p_150728_2_); - } - } - } - - /** - * Sets the NetHandler for this NetworkManager, no checks are made if this handler is suitable for the particular - * connection state (protocol) - */ - public void setNetHandler(INetHandler p_150719_1_) - { - Validate.notNull(p_150719_1_, "packetListener", new Object[0]); - logger.debug("Set listener of {} to {}", new Object[] {this, p_150719_1_}); - this.netHandler = p_150719_1_; - } - - /** - * Will flush the outbound queue and dispatch the supplied Packet if the channel is ready, otherwise it adds the - * packet to the outbound queue and registers the GenericFutureListener to fire after transmission - */ - public void scheduleOutboundPacket(Packet p_150725_1_, GenericFutureListener ... p_150725_2_) - { - if (this.channel != null && this.channel.isOpen()) - { - this.flushOutboundQueue(); - this.dispatchPacket(p_150725_1_, p_150725_2_); - } - else - { - this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(p_150725_1_, p_150725_2_)); - } - } - - /** - * Will commit the packet to the channel. If the current thread 'owns' the channel it will write and flush the - * packet, otherwise it will add a task for the channel eventloop thread to do that. - */ - private void dispatchPacket(final Packet p_150732_1_, final GenericFutureListener[] p_150732_2_) - { - final EnumConnectionState enumconnectionstate = EnumConnectionState.func_150752_a(p_150732_1_); - final EnumConnectionState enumconnectionstate1 = (EnumConnectionState)this.channel.attr(attrKeyConnectionState).get(); - - if (enumconnectionstate1 != enumconnectionstate && !( p_150732_1_ instanceof FMLProxyPacket)) - { - logger.debug("Disabled auto read"); - this.channel.config().setAutoRead(false); - } - - if (this.channel.eventLoop().inEventLoop()) - { - if (enumconnectionstate != enumconnectionstate1 && !( p_150732_1_ instanceof FMLProxyPacket)) - { - this.setConnectionState(enumconnectionstate); - } - - this.channel.writeAndFlush(p_150732_1_).addListeners(p_150732_2_).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); - } - else - { - this.channel.eventLoop().execute(new Runnable() - { - private static final String __OBFID = "CL_00001241"; - public void run() - { - if (enumconnectionstate != enumconnectionstate1 && !( p_150732_1_ instanceof FMLProxyPacket)) - { - NetworkManager.this.setConnectionState(enumconnectionstate); - } - - NetworkManager.this.channel.writeAndFlush(p_150732_1_).addListeners(p_150732_2_).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); - } - }); - } - } - - /** - * Will iterate through the outboundPacketQueue and dispatch all Packets - */ - private void flushOutboundQueue() - { - if (this.channel != null && this.channel.isOpen()) - { - while (!this.outboundPacketsQueue.isEmpty()) - { - NetworkManager.InboundHandlerTuplePacketListener inboundhandlertuplepacketlistener = (NetworkManager.InboundHandlerTuplePacketListener)this.outboundPacketsQueue.poll(); - this.dispatchPacket(inboundhandlertuplepacketlistener.field_150774_a, inboundhandlertuplepacketlistener.field_150773_b); - } - } - } - - /** - * Checks timeouts and processes all packets received - */ - public void processReceivedPackets() - { - this.flushOutboundQueue(); - EnumConnectionState enumconnectionstate = (EnumConnectionState)this.channel.attr(attrKeyConnectionState).get(); - - if (this.connectionState != enumconnectionstate) - { - if (this.connectionState != null) - { - this.netHandler.onConnectionStateTransition(this.connectionState, enumconnectionstate); - } - - this.connectionState = enumconnectionstate; - } - - if (this.netHandler != null) - { - for (int i = 1000; !this.receivedPacketsQueue.isEmpty() && i >= 0; --i) - { - Packet packet = (Packet)this.receivedPacketsQueue.poll(); - packet.processPacket(this.netHandler); - } - - this.netHandler.onNetworkTick(); - } - - this.channel.flush(); - } - - /** - * Return the InetSocketAddress of the remote endpoint - */ - public SocketAddress getSocketAddress() - { - return this.socketAddress; - } - - /** - * Closes the channel, the parameter can be used for an exit message (not certain how it gets sent) - */ - public void closeChannel(IChatComponent p_150718_1_) - { - if (this.channel.isOpen()) - { - this.channel.close(); - this.terminationReason = p_150718_1_; - } - } - - /** - * True if this NetworkManager uses a memory connection (single player game). False may imply both an active TCP - * connection or simply no active connection at all - */ - public boolean isLocalChannel() - { - return this.channel instanceof LocalChannel || this.channel instanceof LocalServerChannel; - } - - /** - * Prepares a clientside NetworkManager: establishes a connection to the address and port supplied and configures - * the channel pipeline. Returns the newly created instance. - */ - @SideOnly(Side.CLIENT) - public static NetworkManager provideLanClient(InetAddress p_150726_0_, int p_150726_1_) - { - final NetworkManager networkmanager = new NetworkManager(true); - ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group(eventLoops)).handler(new ChannelInitializer() - { - private static final String __OBFID = "CL_00001242"; - protected void initChannel(Channel p_initChannel_1_) - { - try - { - p_initChannel_1_.config().setOption(ChannelOption.IP_TOS, Integer.valueOf(24)); - } - catch (ChannelException channelexception1) - { - ; - } - - try - { - p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(false)); - } - catch (ChannelException channelexception) - { - ; - } - - p_initChannel_1_.pipeline().addLast("timeout", new ReadTimeoutHandler(20)).addLast("splitter", new MessageDeserializer2()).addLast("decoder", new MessageDeserializer()).addLast("prepender", new MessageSerializer2()).addLast("encoder", new MessageSerializer()).addLast("packet_handler", networkmanager); - } - })).channel(NioSocketChannel.class)).connect(p_150726_0_, p_150726_1_).syncUninterruptibly(); - return networkmanager; - } - - /** - * Prepares a clientside NetworkManager: establishes a connection to the socket supplied and configures the channel - * pipeline. Returns the newly created instance. - */ - @SideOnly(Side.CLIENT) - public static NetworkManager provideLocalClient(SocketAddress p_150722_0_) - { - final NetworkManager networkmanager = new NetworkManager(true); - ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group(eventLoops)).handler(new ChannelInitializer() - { - private static final String __OBFID = "CL_00001243"; - protected void initChannel(Channel p_initChannel_1_) - { - p_initChannel_1_.pipeline().addLast("packet_handler", networkmanager); - } - })).channel(LocalChannel.class)).connect(p_150722_0_).syncUninterruptibly(); - return networkmanager; - } - - /** - * Adds an encoder+decoder to the channel pipeline. The parameter is the secret key used for encrypted communication - */ - public void enableEncryption(SecretKey p_150727_1_) - { - this.channel.pipeline().addBefore("splitter", "decrypt", new NettyEncryptingDecoder(CryptManager.func_151229_a(2, p_150727_1_))); - this.channel.pipeline().addBefore("prepender", "encrypt", new NettyEncryptingEncoder(CryptManager.func_151229_a(1, p_150727_1_))); - } - - /** - * Returns true if this NetworkManager has an active channel, false otherwise - */ - public boolean isChannelOpen() - { - return this.channel != null && this.channel.isOpen(); - } - - /** - * Gets the current handler for processing packets - */ - public INetHandler getNetHandler() - { - return this.netHandler; - } - - /** - * If this channel is closed, returns the exit message, null otherwise. - */ - public IChatComponent getExitMessage() - { - return this.terminationReason; - } - - /** - * Switches the channel to manual reading modus - */ - public void disableAutoRead() - { - this.channel.config().setAutoRead(false); - } - - protected void channelRead0(ChannelHandlerContext p_channelRead0_1_, Object p_channelRead0_2_) - { - this.channelRead0(p_channelRead0_1_, (Packet)p_channelRead0_2_); - } - - public Channel channel() - { - /** The active channel used to send data */ - return channel; - } - - static class InboundHandlerTuplePacketListener - { - private final Packet field_150774_a; - private final GenericFutureListener[] field_150773_b; - private static final String __OBFID = "CL_00001244"; - - public InboundHandlerTuplePacketListener(Packet p_i45146_1_, GenericFutureListener ... p_i45146_2_) - { - this.field_150774_a = p_i45146_1_; - this.field_150773_b = p_i45146_2_; - } - } -} \ No newline at end of file diff --git a/src/main/java/net/minecraft/util/MessageDeserializer.java b/src/main/java/net/minecraft/util/MessageDeserializer.java deleted file mode 100644 index 52874be..0000000 --- a/src/main/java/net/minecraft/util/MessageDeserializer.java +++ /dev/null @@ -1,62 +0,0 @@ -package net.minecraft.util; - -import com.google.common.collect.BiMap; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; - -import java.io.IOException; -import java.util.List; - -import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -import net.minecraft.network.PacketBuffer; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; - -public class MessageDeserializer extends ByteToMessageDecoder -{ - private static final Logger logger = LogManager.getLogger(); - private static final Marker field_150799_b = MarkerManager.getMarker("PACKET_RECEIVED", NetworkManager.logMarkerPackets); - private static final String __OBFID = "CL_00001252"; - - protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List p_decode_3_) throws IOException - { - if (p_decode_2_.readableBytes() != 0) - { - PacketBuffer packetbuffer = new PacketBuffer(p_decode_2_); - int i = packetbuffer.readVarIntFromBuffer(); - Packet packet = Packet.generatePacket((BiMap)p_decode_1_.channel().attr(NetworkManager.attrKeyReceivable).get(), i); - - ProfilerSection.PACKET_INBOUND.start(packet, packetbuffer.capacity()); - - if (packet == null) - { - throw new IOException("Bad packet id " + i); - } - else - { - packet.readPacketData(packetbuffer); - - if (packetbuffer.readableBytes() > 0) - { - throw new IOException("Packet was larger than I expected, found " + packetbuffer.readableBytes() + " bytes extra whilst reading packet " + i); - } - else - { - p_decode_3_.add(packet); - - if (logger.isDebugEnabled()) - { - logger.debug(field_150799_b, " IN: [{}:{}] {}[{}]", new Object[] {p_decode_1_.channel().attr(NetworkManager.attrKeyConnectionState).get(), Integer.valueOf(i), packet.getClass().getName(), packet.serialize()}); - } - } - } - } - } -} \ No newline at end of file diff --git a/src/main/java/net/minecraft/util/MessageSerializer.java b/src/main/java/net/minecraft/util/MessageSerializer.java deleted file mode 100644 index 140dc3d..0000000 --- a/src/main/java/net/minecraft/util/MessageSerializer.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.minecraft.util; - -import com.google.common.collect.BiMap; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; - -import java.io.IOException; - -import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -import net.minecraft.network.PacketBuffer; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; - -public class MessageSerializer extends MessageToByteEncoder -{ - private static final Logger logger = LogManager.getLogger(); - private static final Marker field_150797_b = MarkerManager.getMarker("PACKET_SENT", NetworkManager.logMarkerPackets); - private static final String __OBFID = "CL_00001253"; - - protected void encode(ChannelHandlerContext p_150796_1_, Packet p_150796_2_, ByteBuf p_150796_3_) throws IOException - { - Integer integer = (Integer)((BiMap)p_150796_1_.channel().attr(NetworkManager.attrKeySendable).get()).inverse().get(p_150796_2_.getClass()); - - if (logger.isDebugEnabled()) - { - logger.debug(field_150797_b, "OUT: [{}:{}] {}[{}]", new Object[] {p_150796_1_.channel().attr(NetworkManager.attrKeyConnectionState).get(), integer, p_150796_2_.getClass().getName(), p_150796_2_.serialize()}); - } - - if (integer == null) - { - throw new IOException("Can\'t serialize unregistered packet"); - } - else - { - PacketBuffer packetbuffer = new PacketBuffer(p_150796_3_); - packetbuffer.writeVarIntToBuffer(integer.intValue()); - p_150796_2_.writePacketData(packetbuffer); - - ProfilerSection.PACKET_OUTBOUND.start(p_150796_2_, packetbuffer.readableBytes()); - } - } - - protected void encode(ChannelHandlerContext p_encode_1_, Object p_encode_2_, ByteBuf p_encode_3_) throws IOException - { - this.encode(p_encode_1_, (Packet)p_encode_2_, p_encode_3_); - } -} \ No newline at end of file diff --git a/src/main/java/net/minecraft/world/World.java b/src/main/java/net/minecraft/world/World.java deleted file mode 100644 index 489c8bd..0000000 --- a/src/main/java/net/minecraft/world/World.java +++ /dev/null @@ -1,4448 +0,0 @@ -package net.minecraft.world; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.Set; -import java.util.concurrent.Callable; - -import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import net.minecraft.block.Block; -import net.minecraft.block.BlockHopper; -import net.minecraft.block.BlockLiquid; -import net.minecraft.block.BlockSlab; -import net.minecraft.block.BlockSnow; -import net.minecraft.block.BlockStairs; -import net.minecraft.block.material.Material; -import net.minecraft.command.IEntitySelector; -import net.minecraft.crash.CrashReport; -import net.minecraft.crash.CrashReportCategory; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLiving; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.pathfinding.PathEntity; -import net.minecraft.pathfinding.PathFinder; -import net.minecraft.profiler.Profiler; -import net.minecraft.scoreboard.Scoreboard; -import net.minecraft.server.MinecraftServer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.Direction; -import net.minecraft.util.Facing; -import net.minecraft.util.MathHelper; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.util.ReportedException; -import net.minecraft.util.Vec3; -import net.minecraft.util.Vec3Pool; -import net.minecraft.village.VillageCollection; -import net.minecraft.village.VillageSiege; -import net.minecraft.world.biome.BiomeGenBase; -import net.minecraft.world.biome.WorldChunkManager; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.storage.ISaveHandler; -import net.minecraft.world.storage.MapStorage; -import net.minecraft.world.storage.WorldInfo; -import cpw.mods.fml.common.FMLLog; - -import com.google.common.collect.ImmutableSetMultimap; - -import net.minecraftforge.client.ForgeHooksClient; -import net.minecraftforge.common.ForgeChunkManager; -import net.minecraftforge.common.ForgeChunkManager.Ticket; -import net.minecraftforge.common.ForgeModContainer; -import net.minecraftforge.common.ForgeHooks; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.common.WorldSpecificSaveHandler; -import net.minecraftforge.event.entity.EntityEvent; -import net.minecraftforge.event.entity.EntityJoinWorldEvent; -import net.minecraftforge.event.world.WorldEvent; -import net.minecraftforge.event.entity.PlaySoundAtEntityEvent; -import net.minecraft.entity.EnumCreatureType; - -public abstract class World implements IBlockAccess -{ - /** - * Used in the getEntitiesWithinAABB functions to expand the search area for entities. - * Modders should change this variable to a higher value if it is less then the radius - * of one of there entities. - */ - public static double MAX_ENTITY_RADIUS = 2.0D; - - public final MapStorage perWorldStorage; - - /** - * boolean; if true updates scheduled by scheduleBlockUpdate happen immediately - */ - public boolean scheduledUpdatesAreImmediate; - /** A list of all Entities in all currently-loaded chunks */ - public List loadedEntityList = new ArrayList(); - protected List unloadedEntityList = new ArrayList(); - /** A list of the loaded tile entities in the world */ - public List loadedTileEntityList = new ArrayList(); - private List addedTileEntityList = new ArrayList(); - private List field_147483_b = new ArrayList(); - /** Array list of players in the world. */ - public List playerEntities = new ArrayList(); - /** a list of all the lightning entities */ - public List weatherEffects = new ArrayList(); - private long cloudColour = 16777215L; - /** How much light is subtracted from full daylight */ - public int skylightSubtracted; - /** - * Contains the current Linear Congruential Generator seed for block updates. Used with an A value of 3 and a C - * value of 0x3c6ef35f, producing a highly planar series of values ill-suited for choosing random blocks in a - * 16x128x16 field. - */ - protected int updateLCG = (new Random()).nextInt(); - /** - * magic number used to generate fast random numbers for 3d distribution within a chunk - */ - protected final int DIST_HASH_MAGIC = 1013904223; - public float prevRainingStrength; - public float rainingStrength; - public float prevThunderingStrength; - public float thunderingStrength; - /** - * Set to 2 whenever a lightning bolt is generated in SSP. Decrements if > 0 in updateWeather(). Value appears to be - * unused. - */ - public int lastLightningBolt; - /** Option > Difficulty setting (0 - 3) */ - public EnumDifficulty difficultySetting; - /** RNG for World. */ - public Random rand = new Random(); - /** The WorldProvider instance that World uses. */ - public final WorldProvider provider; - protected List worldAccesses = new ArrayList(); - /** Handles chunk operations and caching */ - protected IChunkProvider chunkProvider; - protected final ISaveHandler saveHandler; - /** - * holds information about a world (size on disk, time, spawn point, seed, ...) - */ - protected WorldInfo worldInfo; - /** Boolean that is set to true when trying to find a spawn point */ - public boolean findingSpawnPoint; - public MapStorage mapStorage; - public VillageCollection villageCollectionObj; - protected final VillageSiege villageSiegeObj = new VillageSiege(this); - public final Profiler theProfiler; - /** The world-local pool of vectors */ - private final Vec3Pool vecPool = new Vec3Pool(300, 2000); - private final Calendar theCalendar = Calendar.getInstance(); - protected Scoreboard worldScoreboard = new Scoreboard(); - /** This is set to true for client worlds, and false for server worlds. */ - public boolean isRemote; - /** Positions to update */ - public Set activeChunkSet = new HashSet(); - /** number of ticks until the next random ambients play */ - private int ambientTickCountdown; - /** indicates if enemies are spawned or not */ - protected boolean spawnHostileMobs; - /** A flag indicating whether we should spawn peaceful mobs. */ - protected boolean spawnPeacefulMobs; - private ArrayList collidingBoundingBoxes; - private boolean field_147481_N; - /** - * is a temporary list of blocks and light values used when updating light levels. Holds up to 32x32x32 blocks (the - * maximum influence of a light source.) Every element is a packed bit value: 0000000000LLLLzzzzzzyyyyyyxxxxxx. The - * 4-bit L is a light level used when darkening blocks. 6-bit numbers x, y and z represent the block's offset from - * the original block, plus 32 (i.e. value of 31 would mean a -1 offset - */ - int[] lightUpdateBlockList; - private static final String __OBFID = "CL_00000140"; - - /** - * Gets the biome for a given set of x/z coordinates - */ - public BiomeGenBase getBiomeGenForCoords(final int par1, final int par2) - { - return provider.getBiomeGenForCoords(par1, par2); - } - - public BiomeGenBase getBiomeGenForCoordsBody(final int par1, final int par2) - { - if (this.blockExists(par1, 0, par2)) - { - Chunk chunk = this.getChunkFromBlockCoords(par1, par2); - - try - { - return chunk.getBiomeGenForWorldCoords(par1 & 15, par2 & 15, this.provider.worldChunkMgr); - } - catch (Throwable throwable) - { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Getting biome"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Coordinates of biome request"); - crashreportcategory.addCrashSectionCallable("Location", new Callable() - { - private static final String __OBFID = "CL_00000141"; - public String call() - { - return CrashReportCategory.getLocationInfo(par1, 0, par2); - } - }); - throw new ReportedException(crashreport); - } - } - else - { - return this.provider.worldChunkMgr.getBiomeGenAt(par1, par2); - } - } - - public WorldChunkManager getWorldChunkManager() - { - return this.provider.worldChunkMgr; - } - - @SideOnly(Side.CLIENT) - public World(ISaveHandler p_i45368_1_, String p_i45368_2_, WorldProvider p_i45368_3_, WorldSettings p_i45368_4_, Profiler p_i45368_5_) - { - this.ambientTickCountdown = this.rand.nextInt(12000); - this.spawnHostileMobs = true; - this.spawnPeacefulMobs = true; - this.collidingBoundingBoxes = new ArrayList(); - this.lightUpdateBlockList = new int[32768]; - this.saveHandler = p_i45368_1_; - this.theProfiler = p_i45368_5_; - this.worldInfo = new WorldInfo(p_i45368_4_, p_i45368_2_); - this.provider = p_i45368_3_; - perWorldStorage = new MapStorage((ISaveHandler)null); - } - - // Broken up so that the WorldClient gets the chance to set the mapstorage object before the dimension initializes - @SideOnly(Side.CLIENT) - protected void finishSetup() - { - VillageCollection villagecollection = (VillageCollection)this.mapStorage.loadData(VillageCollection.class, "villages"); - - if (villagecollection == null) - { - this.villageCollectionObj = new VillageCollection(this); - this.mapStorage.setData("villages", this.villageCollectionObj); - } - else - { - this.villageCollectionObj = villagecollection; - this.villageCollectionObj.func_82566_a(this); - } - - // Guarantee the dimension ID was not reset by the provider - int providerDim = this.provider.dimensionId; - this.provider.registerWorld(this); - this.provider.dimensionId = providerDim; - this.chunkProvider = this.createChunkProvider(); - this.calculateInitialSkylight(); - this.calculateInitialWeather(); - } - - public World(ISaveHandler p_i45369_1_, String p_i45369_2_, WorldSettings p_i45369_3_, WorldProvider p_i45369_4_, Profiler p_i45369_5_) - { - this.ambientTickCountdown = this.rand.nextInt(12000); - this.spawnHostileMobs = true; - this.spawnPeacefulMobs = true; - this.collidingBoundingBoxes = new ArrayList(); - this.lightUpdateBlockList = new int[32768]; - this.saveHandler = p_i45369_1_; - this.theProfiler = p_i45369_5_; - this.mapStorage = getMapStorage(p_i45369_1_); - this.worldInfo = p_i45369_1_.loadWorldInfo(); - - if (p_i45369_4_ != null) - { - this.provider = p_i45369_4_; - } - else if (this.worldInfo != null && this.worldInfo.getVanillaDimension() != 0) - { - this.provider = WorldProvider.getProviderForDimension(this.worldInfo.getVanillaDimension()); - } - else - { - this.provider = WorldProvider.getProviderForDimension(0); - } - - if (this.worldInfo == null) - { - this.worldInfo = new WorldInfo(p_i45369_3_, p_i45369_2_); - } - else - { - this.worldInfo.setWorldName(p_i45369_2_); - } - - this.provider.registerWorld(this); - this.chunkProvider = this.createChunkProvider(); - - if (this instanceof WorldServer) - { - this.perWorldStorage = new MapStorage(new WorldSpecificSaveHandler((WorldServer)this, p_i45369_1_)); - } - else - { - this.perWorldStorage = new MapStorage((ISaveHandler)null); - } - - if (!this.worldInfo.isInitialized()) - { - try - { - this.initialize(p_i45369_3_); - } - catch (Throwable throwable1) - { - CrashReport crashreport = CrashReport.makeCrashReport(throwable1, "Exception initializing level"); - - try - { - this.addWorldInfoToCrashReport(crashreport); - } - catch (Throwable throwable) - { - ; - } - - throw new ReportedException(crashreport); - } - - this.worldInfo.setServerInitialized(true); - } - - VillageCollection villagecollection = (VillageCollection)this.perWorldStorage.loadData(VillageCollection.class, "villages"); - - if (villagecollection == null) - { - this.villageCollectionObj = new VillageCollection(this); - this.perWorldStorage.setData("villages", this.villageCollectionObj); - } - else - { - this.villageCollectionObj = villagecollection; - this.villageCollectionObj.func_82566_a(this); - } - - this.calculateInitialSkylight(); - this.calculateInitialWeather(); - } - - private static MapStorage s_mapStorage; - private static ISaveHandler s_savehandler; - //Provides a solution for different worlds getting different copies of the same data, potentially rewriting the data or causing race conditions/stale data - //Buildcraft has suffered from the issue this fixes. If you load the same data from two different worlds they can get two different copies of the same object, thus the last saved gets final say. - private MapStorage getMapStorage(ISaveHandler savehandler) - { - if (s_savehandler != savehandler || s_mapStorage == null) - { - s_mapStorage = new MapStorage(savehandler); - s_savehandler = savehandler; - } - return s_mapStorage; - } - - /** - * Creates the chunk provider for this world. Called in the constructor. Retrieves provider from worldProvider? - */ - protected abstract IChunkProvider createChunkProvider(); - - protected void initialize(WorldSettings par1WorldSettings) - { - this.worldInfo.setServerInitialized(true); - } - - /** - * Sets a new spawn location by finding an uncovered block at a random (x,z) location in the chunk. - */ - @SideOnly(Side.CLIENT) - public void setSpawnLocation() - { - this.setSpawnLocation(8, 64, 8); - } - - public Block getTopBlock(int p_147474_1_, int p_147474_2_) - { - int k; - - for (k = 63; !this.isAirBlock(p_147474_1_, k + 1, p_147474_2_); ++k) - { - ; - } - - return this.getBlock(p_147474_1_, k, p_147474_2_); - } - - public Block getBlock(int p_147439_1_, int p_147439_2_, int p_147439_3_) - { - if (p_147439_1_ >= -30000000 && p_147439_3_ >= -30000000 && p_147439_1_ < 30000000 && p_147439_3_ < 30000000 && p_147439_2_ >= 0 && p_147439_2_ < 256) - { - Chunk chunk = null; - - try - { - chunk = this.getChunkFromChunkCoords(p_147439_1_ >> 4, p_147439_3_ >> 4); - return chunk.getBlock(p_147439_1_ & 15, p_147439_2_, p_147439_3_ & 15); - } - catch (Throwable throwable) - { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception getting block type in world"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Requested block coordinates"); - crashreportcategory.addCrashSection("Found chunk", Boolean.valueOf(chunk == null)); - crashreportcategory.addCrashSection("Location", CrashReportCategory.getLocationInfo(p_147439_1_, p_147439_2_, p_147439_3_)); - throw new ReportedException(crashreport); - } - } - else - { - return Blocks.air; - } - } - - /** - * Returns true if the block at the specified coordinates is empty - */ - public boolean isAirBlock(int p_147437_1_, int p_147437_2_, int p_147437_3_) - { - Block block = this.getBlock(p_147437_1_, p_147437_2_, p_147437_3_); - return block.isAir(this, p_147437_1_, p_147437_2_, p_147437_3_); - } - - /** - * Returns whether a block exists at world coordinates x, y, z - */ - public boolean blockExists(int par1, int par2, int par3) - { - return par2 >= 0 && par2 < 256 ? this.chunkExists(par1 >> 4, par3 >> 4) : false; - } - - /** - * Checks if any of the chunks within distance (argument 4) blocks of the given block exist - */ - public boolean doChunksNearChunkExist(int par1, int par2, int par3, int par4) - { - return this.checkChunksExist(par1 - par4, par2 - par4, par3 - par4, par1 + par4, par2 + par4, par3 + par4); - } - - /** - * Checks between a min and max all the chunks inbetween actually exist. Args: minX, minY, minZ, maxX, maxY, maxZ - */ - public boolean checkChunksExist(int par1, int par2, int par3, int par4, int par5, int par6) - { - if (par5 >= 0 && par2 < 256) - { - par1 >>= 4; - par3 >>= 4; - par4 >>= 4; - par6 >>= 4; - - for (int k1 = par1; k1 <= par4; ++k1) - { - for (int l1 = par3; l1 <= par6; ++l1) - { - if (!this.chunkExists(k1, l1)) - { - return false; - } - } - } - - return true; - } - else - { - return false; - } - } - - /** - * Returns whether a chunk exists at chunk coordinates x, y - */ - protected boolean chunkExists(int par1, int par2) - { - return this.chunkProvider.chunkExists(par1, par2); - } - - /** - * Returns a chunk looked up by block coordinates. Args: x, z - */ - public Chunk getChunkFromBlockCoords(int par1, int par2) - { - return this.getChunkFromChunkCoords(par1 >> 4, par2 >> 4); - } - - /** - * Returns back a chunk looked up by chunk coordinates Args: x, y - */ - public Chunk getChunkFromChunkCoords(int par1, int par2) - { - return this.chunkProvider.provideChunk(par1, par2); - } - - /** - * Sets the block ID and metadata at a given location. Args: X, Y, Z, new block ID, new metadata, flags. Flag 1 will - * cause a block update. Flag 2 will send the change to clients (you almost always want this). Flag 4 prevents the - * block from being re-rendered, if this is a client world. Flags can be added together. - */ - public boolean setBlock(int p_147465_1_, int p_147465_2_, int p_147465_3_, Block p_147465_4_, int p_147465_5_, int p_147465_6_) - { - if (p_147465_1_ >= -30000000 && p_147465_3_ >= -30000000 && p_147465_1_ < 30000000 && p_147465_3_ < 30000000) - { - if (p_147465_2_ < 0) - { - return false; - } - else if (p_147465_2_ >= 256) - { - return false; - } - else - { - Chunk chunk = this.getChunkFromChunkCoords(p_147465_1_ >> 4, p_147465_3_ >> 4); - Block block1 = null; - - if ((p_147465_6_ & 1) != 0) - { - block1 = chunk.getBlock(p_147465_1_ & 15, p_147465_2_, p_147465_3_ & 15); - } - - boolean flag = chunk.func_150807_a(p_147465_1_ & 15, p_147465_2_, p_147465_3_ & 15, p_147465_4_, p_147465_5_); - this.theProfiler.startSection("checkLight"); - this.func_147451_t(p_147465_1_, p_147465_2_, p_147465_3_); - this.theProfiler.endSection(); - - if (flag) - { - if ((p_147465_6_ & 2) != 0 && (!this.isRemote || (p_147465_6_ & 4) == 0) && chunk.func_150802_k()) - { - this.markBlockForUpdate(p_147465_1_, p_147465_2_, p_147465_3_); - } - - if (!this.isRemote && (p_147465_6_ & 1) != 0) - { - this.notifyBlockChange(p_147465_1_, p_147465_2_, p_147465_3_, block1); - - if (p_147465_4_.hasComparatorInputOverride()) - { - this.func_147453_f(p_147465_1_, p_147465_2_, p_147465_3_, p_147465_4_); - } - } - } - - return flag; - } - } - else - { - return false; - } - } - - /** - * Returns the block metadata at coords x,y,z - */ - public int getBlockMetadata(int par1, int par2, int par3) - { - if (par1 >= -30000000 && par3 >= -30000000 && par1 < 30000000 && par3 < 30000000) - { - if (par2 < 0) - { - return 0; - } - else if (par2 >= 256) - { - return 0; - } - else - { - Chunk chunk = this.getChunkFromChunkCoords(par1 >> 4, par3 >> 4); - par1 &= 15; - par3 &= 15; - return chunk.getBlockMetadata(par1, par2, par3); - } - } - else - { - return 0; - } - } - - /** - * Sets the blocks metadata and if set will then notify blocks that this block changed, depending on the flag. Args: - * x, y, z, metadata, flag. See setBlock for flag description - */ - public boolean setBlockMetadataWithNotify(int par1, int par2, int par3, int par4, int par5) - { - if (par1 >= -30000000 && par3 >= -30000000 && par1 < 30000000 && par3 < 30000000) - { - if (par2 < 0) - { - return false; - } - else if (par2 >= 256) - { - return false; - } - else - { - Chunk chunk = this.getChunkFromChunkCoords(par1 >> 4, par3 >> 4); - int j1 = par1 & 15; - int k1 = par3 & 15; - boolean flag = chunk.setBlockMetadata(j1, par2, k1, par4); - - if (flag) - { - Block block = chunk.getBlock(j1, par2, k1); - - if ((par5 & 2) != 0 && (!this.isRemote || (par5 & 4) == 0) && chunk.func_150802_k()) - { - this.markBlockForUpdate(par1, par2, par3); - } - - if (!this.isRemote && (par5 & 1) != 0) - { - this.notifyBlockChange(par1, par2, par3, block); - - if (block.hasComparatorInputOverride()) - { - this.func_147453_f(par1, par2, par3, block); - } - } - } - - return flag; - } - } - else - { - return false; - } - } - - /** - * Sets a block to 0 and notifies relevant systems with the block change Args: x, y, z - */ - public boolean setBlockToAir(int p_147468_1_, int p_147468_2_, int p_147468_3_) - { - return this.setBlock(p_147468_1_, p_147468_2_, p_147468_3_, Blocks.air, 0, 3); - } - - public boolean func_147480_a(int p_147480_1_, int p_147480_2_, int p_147480_3_, boolean p_147480_4_) - { - Block block = this.getBlock(p_147480_1_, p_147480_2_, p_147480_3_); - - if (block.getMaterial() == Material.air) - { - return false; - } - else - { - int l = this.getBlockMetadata(p_147480_1_, p_147480_2_, p_147480_3_); - this.playAuxSFX(2001, p_147480_1_, p_147480_2_, p_147480_3_, Block.getIdFromBlock(block) + (l << 12)); - - if (p_147480_4_) - { - block.dropBlockAsItem(this, p_147480_1_, p_147480_2_, p_147480_3_, l, 0); - } - - return this.setBlock(p_147480_1_, p_147480_2_, p_147480_3_, Blocks.air, 0, 3); - } - } - - /** - * Sets a block by a coordinate - */ - public boolean setBlock(int p_147449_1_, int p_147449_2_, int p_147449_3_, Block p_147449_4_) - { - return this.setBlock(p_147449_1_, p_147449_2_, p_147449_3_, p_147449_4_, 0, 3); - } - - public void markBlockForUpdate(int p_147471_1_, int p_147471_2_, int p_147471_3_) - { - for (int l = 0; l < this.worldAccesses.size(); ++l) - { - ((IWorldAccess)this.worldAccesses.get(l)).markBlockForUpdate(p_147471_1_, p_147471_2_, p_147471_3_); - } - } - - /** - * The block type change and need to notify other systems Args: x, y, z, blockID - */ - public void notifyBlockChange(int p_147444_1_, int p_147444_2_, int p_147444_3_, Block p_147444_4_) - { - this.notifyBlocksOfNeighborChange(p_147444_1_, p_147444_2_, p_147444_3_, p_147444_4_); - } - - /** - * marks a vertical line of blocks as dirty - */ - public void markBlocksDirtyVertical(int par1, int par2, int par3, int par4) - { - int i1; - - if (par3 > par4) - { - i1 = par4; - par4 = par3; - par3 = i1; - } - - if (!this.provider.hasNoSky) - { - for (i1 = par3; i1 <= par4; ++i1) - { - this.updateLightByType(EnumSkyBlock.Sky, par1, i1, par2); - } - } - - this.markBlockRangeForRenderUpdate(par1, par3, par2, par1, par4, par2); - } - - public void markBlockRangeForRenderUpdate(int p_147458_1_, int p_147458_2_, int p_147458_3_, int p_147458_4_, int p_147458_5_, int p_147458_6_) - { - for (int k1 = 0; k1 < this.worldAccesses.size(); ++k1) - { - ((IWorldAccess)this.worldAccesses.get(k1)).markBlockRangeForRenderUpdate(p_147458_1_, p_147458_2_, p_147458_3_, p_147458_4_, p_147458_5_, p_147458_6_); - } - } - - public void notifyBlocksOfNeighborChange(int p_147459_1_, int p_147459_2_, int p_147459_3_, Block p_147459_4_) - { - this.notifyBlockOfNeighborChange(p_147459_1_ - 1, p_147459_2_, p_147459_3_, p_147459_4_); - this.notifyBlockOfNeighborChange(p_147459_1_ + 1, p_147459_2_, p_147459_3_, p_147459_4_); - this.notifyBlockOfNeighborChange(p_147459_1_, p_147459_2_ - 1, p_147459_3_, p_147459_4_); - this.notifyBlockOfNeighborChange(p_147459_1_, p_147459_2_ + 1, p_147459_3_, p_147459_4_); - this.notifyBlockOfNeighborChange(p_147459_1_, p_147459_2_, p_147459_3_ - 1, p_147459_4_); - this.notifyBlockOfNeighborChange(p_147459_1_, p_147459_2_, p_147459_3_ + 1, p_147459_4_); - } - - public void notifyBlocksOfNeighborChange(int p_147441_1_, int p_147441_2_, int p_147441_3_, Block p_147441_4_, int p_147441_5_) - { - if (p_147441_5_ != 4) - { - this.notifyBlockOfNeighborChange(p_147441_1_ - 1, p_147441_2_, p_147441_3_, p_147441_4_); - } - - if (p_147441_5_ != 5) - { - this.notifyBlockOfNeighborChange(p_147441_1_ + 1, p_147441_2_, p_147441_3_, p_147441_4_); - } - - if (p_147441_5_ != 0) - { - this.notifyBlockOfNeighborChange(p_147441_1_, p_147441_2_ - 1, p_147441_3_, p_147441_4_); - } - - if (p_147441_5_ != 1) - { - this.notifyBlockOfNeighborChange(p_147441_1_, p_147441_2_ + 1, p_147441_3_, p_147441_4_); - } - - if (p_147441_5_ != 2) - { - this.notifyBlockOfNeighborChange(p_147441_1_, p_147441_2_, p_147441_3_ - 1, p_147441_4_); - } - - if (p_147441_5_ != 3) - { - this.notifyBlockOfNeighborChange(p_147441_1_, p_147441_2_, p_147441_3_ + 1, p_147441_4_); - } - } - - /** - * Notifies a block that one of its neighbor change to the specified type Args: x, y, z, block - */ - public void notifyBlockOfNeighborChange(int p_147460_1_, int p_147460_2_, int p_147460_3_, final Block p_147460_4_) - { - if (!this.isRemote) - { - Block block = this.getBlock(p_147460_1_, p_147460_2_, p_147460_3_); - - try - { - block.onNeighborBlockChange(this, p_147460_1_, p_147460_2_, p_147460_3_, p_147460_4_); - } - catch (Throwable throwable1) - { - CrashReport crashreport = CrashReport.makeCrashReport(throwable1, "Exception while updating neighbours"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being updated"); - int l; - - try - { - l = this.getBlockMetadata(p_147460_1_, p_147460_2_, p_147460_3_); - } - catch (Throwable throwable) - { - l = -1; - } - - crashreportcategory.addCrashSectionCallable("Source block type", new Callable() - { - private static final String __OBFID = "CL_00000142"; - public String call() - { - try - { - return String.format("ID #%d (%s // %s)", new Object[] {Integer.valueOf(Block.getIdFromBlock(p_147460_4_)), p_147460_4_.getUnlocalizedName(), p_147460_4_.getClass().getCanonicalName()}); - } - catch (Throwable throwable2) - { - return "ID #" + Block.getIdFromBlock(p_147460_4_); - } - } - }); - CrashReportCategory.func_147153_a(crashreportcategory, p_147460_1_, p_147460_2_, p_147460_3_, block, l); - throw new ReportedException(crashreport); - } - } - } - - /** - * Returns true if the given block will receive a scheduled tick in this tick. Args: X, Y, Z, Block - */ - public boolean isBlockTickScheduledThisTick(int p_147477_1_, int p_147477_2_, int p_147477_3_, Block p_147477_4_) - { - return false; - } - - /** - * Checks if the specified block is able to see the sky - */ - public boolean canBlockSeeTheSky(int par1, int par2, int par3) - { - return this.getChunkFromChunkCoords(par1 >> 4, par3 >> 4).canBlockSeeTheSky(par1 & 15, par2, par3 & 15); - } - - /** - * Does the same as getBlockLightValue_do but without checking if its not a normal block - */ - public int getFullBlockLightValue(int par1, int par2, int par3) - { - if (par2 < 0) - { - return 0; - } - else - { - if (par2 >= 256) - { - par2 = 255; - } - - return this.getChunkFromChunkCoords(par1 >> 4, par3 >> 4).getBlockLightValue(par1 & 15, par2, par3 & 15, 0); - } - } - - /** - * Gets the light value of a block location - */ - public int getBlockLightValue(int par1, int par2, int par3) - { - return this.getBlockLightValue_do(par1, par2, par3, true); - } - - /** - * Gets the light value of a block location. This is the actual function that gets the value and has a bool flag - * that indicates if its a half step block to get the maximum light value of a direct neighboring block (left, - * right, forward, back, and up) - */ - public int getBlockLightValue_do(int par1, int par2, int par3, boolean par4) - { - if (par1 >= -30000000 && par3 >= -30000000 && par1 < 30000000 && par3 < 30000000) - { - if (par4 && this.getBlock(par1, par2, par3).getUseNeighborBrightness()) - { - int l1 = this.getBlockLightValue_do(par1, par2 + 1, par3, false); - int l = this.getBlockLightValue_do(par1 + 1, par2, par3, false); - int i1 = this.getBlockLightValue_do(par1 - 1, par2, par3, false); - int j1 = this.getBlockLightValue_do(par1, par2, par3 + 1, false); - int k1 = this.getBlockLightValue_do(par1, par2, par3 - 1, false); - - if (l > l1) - { - l1 = l; - } - - if (i1 > l1) - { - l1 = i1; - } - - if (j1 > l1) - { - l1 = j1; - } - - if (k1 > l1) - { - l1 = k1; - } - - return l1; - } - else if (par2 < 0) - { - return 0; - } - else - { - if (par2 >= 256) - { - par2 = 255; - } - - Chunk chunk = this.getChunkFromChunkCoords(par1 >> 4, par3 >> 4); - par1 &= 15; - par3 &= 15; - return chunk.getBlockLightValue(par1, par2, par3, this.skylightSubtracted); - } - } - else - { - return 15; - } - } - - /** - * Returns the y coordinate with a block in it at this x, z coordinate - */ - public int getHeightValue(int par1, int par2) - { - if (par1 >= -30000000 && par2 >= -30000000 && par1 < 30000000 && par2 < 30000000) - { - if (!this.chunkExists(par1 >> 4, par2 >> 4)) - { - return 0; - } - else - { - Chunk chunk = this.getChunkFromChunkCoords(par1 >> 4, par2 >> 4); - return chunk.getHeightValue(par1 & 15, par2 & 15); - } - } - else - { - return 64; - } - } - - /** - * Gets the heightMapMinimum field of the given chunk, or 0 if the chunk is not loaded. Coords are in blocks. Args: - * X, Z - */ - public int getChunkHeightMapMinimum(int par1, int par2) - { - if (par1 >= -30000000 && par2 >= -30000000 && par1 < 30000000 && par2 < 30000000) - { - if (!this.chunkExists(par1 >> 4, par2 >> 4)) - { - return 0; - } - else - { - Chunk chunk = this.getChunkFromChunkCoords(par1 >> 4, par2 >> 4); - return chunk.heightMapMinimum; - } - } - else - { - return 64; - } - } - - /** - * Brightness for SkyBlock.Sky is clear white and (through color computing it is assumed) DEPENDENT ON DAYTIME. - * Brightness for SkyBlock.Block is yellowish and independent. - */ - @SideOnly(Side.CLIENT) - public int getSkyBlockTypeBrightness(EnumSkyBlock par1EnumSkyBlock, int par2, int par3, int par4) - { - if (this.provider.hasNoSky && par1EnumSkyBlock == EnumSkyBlock.Sky) - { - return 0; - } - else - { - if (par3 < 0) - { - par3 = 0; - } - - if (par3 >= 256) - { - return par1EnumSkyBlock.defaultLightValue; - } - else if (par2 >= -30000000 && par4 >= -30000000 && par2 < 30000000 && par4 < 30000000) - { - int l = par2 >> 4; - int i1 = par4 >> 4; - - if (!this.chunkExists(l, i1)) - { - return par1EnumSkyBlock.defaultLightValue; - } - else if (this.getBlock(par2, par3, par4).getUseNeighborBrightness()) - { - int j2 = this.getSavedLightValue(par1EnumSkyBlock, par2, par3 + 1, par4); - int j1 = this.getSavedLightValue(par1EnumSkyBlock, par2 + 1, par3, par4); - int k1 = this.getSavedLightValue(par1EnumSkyBlock, par2 - 1, par3, par4); - int l1 = this.getSavedLightValue(par1EnumSkyBlock, par2, par3, par4 + 1); - int i2 = this.getSavedLightValue(par1EnumSkyBlock, par2, par3, par4 - 1); - - if (j1 > j2) - { - j2 = j1; - } - - if (k1 > j2) - { - j2 = k1; - } - - if (l1 > j2) - { - j2 = l1; - } - - if (i2 > j2) - { - j2 = i2; - } - - return j2; - } - else - { - Chunk chunk = this.getChunkFromChunkCoords(l, i1); - return chunk.getSavedLightValue(par1EnumSkyBlock, par2 & 15, par3, par4 & 15); - } - } - else - { - return par1EnumSkyBlock.defaultLightValue; - } - } - } - - /** - * Returns saved light value without taking into account the time of day. Either looks in the sky light map or - * block light map based on the enumSkyBlock arg. - */ - public int getSavedLightValue(EnumSkyBlock par1EnumSkyBlock, int par2, int par3, int par4) - { - if (par3 < 0) - { - par3 = 0; - } - - if (par3 >= 256) - { - par3 = 255; - } - - if (par2 >= -30000000 && par4 >= -30000000 && par2 < 30000000 && par4 < 30000000) - { - int l = par2 >> 4; - int i1 = par4 >> 4; - - if (!this.chunkExists(l, i1)) - { - return par1EnumSkyBlock.defaultLightValue; - } - else - { - Chunk chunk = this.getChunkFromChunkCoords(l, i1); - return chunk.getSavedLightValue(par1EnumSkyBlock, par2 & 15, par3, par4 & 15); - } - } - else - { - return par1EnumSkyBlock.defaultLightValue; - } - } - - /** - * Sets the light value either into the sky map or block map depending on if enumSkyBlock is set to sky or block. - * Args: enumSkyBlock, x, y, z, lightValue - */ - public void setLightValue(EnumSkyBlock par1EnumSkyBlock, int par2, int par3, int par4, int par5) - { - if (par2 >= -30000000 && par4 >= -30000000 && par2 < 30000000 && par4 < 30000000) - { - if (par3 >= 0) - { - if (par3 < 256) - { - if (this.chunkExists(par2 >> 4, par4 >> 4)) - { - Chunk chunk = this.getChunkFromChunkCoords(par2 >> 4, par4 >> 4); - chunk.setLightValue(par1EnumSkyBlock, par2 & 15, par3, par4 & 15, par5); - - for (int i1 = 0; i1 < this.worldAccesses.size(); ++i1) - { - ((IWorldAccess)this.worldAccesses.get(i1)).markBlockForRenderUpdate(par2, par3, par4); - } - } - } - } - } - } - - public void func_147479_m(int p_147479_1_, int p_147479_2_, int p_147479_3_) - { - for (int l = 0; l < this.worldAccesses.size(); ++l) - { - ((IWorldAccess)this.worldAccesses.get(l)).markBlockForRenderUpdate(p_147479_1_, p_147479_2_, p_147479_3_); - } - } - - /** - * Any Light rendered on a 1.8 Block goes through here - */ - @SideOnly(Side.CLIENT) - public int getLightBrightnessForSkyBlocks(int par1, int par2, int par3, int par4) - { - int i1 = this.getSkyBlockTypeBrightness(EnumSkyBlock.Sky, par1, par2, par3); - int j1 = this.getSkyBlockTypeBrightness(EnumSkyBlock.Block, par1, par2, par3); - - if (j1 < par4) - { - j1 = par4; - } - - return i1 << 20 | j1 << 4; - } - - /** - * Returns how bright the block is shown as which is the block's light value looked up in a lookup table (light - * values aren't linear for brightness). Args: x, y, z - */ - public float getLightBrightness(int par1, int par2, int par3) - { - return this.provider.lightBrightnessTable[this.getBlockLightValue(par1, par2, par3)]; - } - - /** - * Checks whether its daytime by seeing if the light subtracted from the skylight is less than 4 - */ - public boolean isDaytime() - { - return provider.isDaytime(); - } - - /** - * Performs a raycast against all blocks in the world except liquids. - */ - public MovingObjectPosition rayTraceBlocks(Vec3 par1Vec3, Vec3 par2Vec3) - { - return this.func_147447_a(par1Vec3, par2Vec3, false, false, false); - } - - /** - * Performs a raycast against all blocks in the world, and optionally liquids. - */ - public MovingObjectPosition rayTraceBlocks(Vec3 par1Vec3, Vec3 par2Vec3, boolean par3) - { - return this.func_147447_a(par1Vec3, par2Vec3, par3, false, false); - } - - public MovingObjectPosition func_147447_a(Vec3 p_147447_1_, Vec3 p_147447_2_, boolean p_147447_3_, boolean p_147447_4_, boolean p_147447_5_) - { - if (!Double.isNaN(p_147447_1_.xCoord) && !Double.isNaN(p_147447_1_.yCoord) && !Double.isNaN(p_147447_1_.zCoord)) - { - if (!Double.isNaN(p_147447_2_.xCoord) && !Double.isNaN(p_147447_2_.yCoord) && !Double.isNaN(p_147447_2_.zCoord)) - { - int i = MathHelper.floor_double(p_147447_2_.xCoord); - int j = MathHelper.floor_double(p_147447_2_.yCoord); - int k = MathHelper.floor_double(p_147447_2_.zCoord); - int l = MathHelper.floor_double(p_147447_1_.xCoord); - int i1 = MathHelper.floor_double(p_147447_1_.yCoord); - int j1 = MathHelper.floor_double(p_147447_1_.zCoord); - Block block = this.getBlock(l, i1, j1); - int k1 = this.getBlockMetadata(l, i1, j1); - - if ((!p_147447_4_ || block.getCollisionBoundingBoxFromPool(this, l, i1, j1) != null) && block.canCollideCheck(k1, p_147447_3_)) - { - MovingObjectPosition movingobjectposition = block.collisionRayTrace(this, l, i1, j1, p_147447_1_, p_147447_2_); - - if (movingobjectposition != null) - { - return movingobjectposition; - } - } - - MovingObjectPosition movingobjectposition2 = null; - k1 = 200; - - while (k1-- >= 0) - { - if (Double.isNaN(p_147447_1_.xCoord) || Double.isNaN(p_147447_1_.yCoord) || Double.isNaN(p_147447_1_.zCoord)) - { - return null; - } - - if (l == i && i1 == j && j1 == k) - { - return p_147447_5_ ? movingobjectposition2 : null; - } - - boolean flag6 = true; - boolean flag3 = true; - boolean flag4 = true; - double d0 = 999.0D; - double d1 = 999.0D; - double d2 = 999.0D; - - if (i > l) - { - d0 = (double)l + 1.0D; - } - else if (i < l) - { - d0 = (double)l + 0.0D; - } - else - { - flag6 = false; - } - - if (j > i1) - { - d1 = (double)i1 + 1.0D; - } - else if (j < i1) - { - d1 = (double)i1 + 0.0D; - } - else - { - flag3 = false; - } - - if (k > j1) - { - d2 = (double)j1 + 1.0D; - } - else if (k < j1) - { - d2 = (double)j1 + 0.0D; - } - else - { - flag4 = false; - } - - double d3 = 999.0D; - double d4 = 999.0D; - double d5 = 999.0D; - double d6 = p_147447_2_.xCoord - p_147447_1_.xCoord; - double d7 = p_147447_2_.yCoord - p_147447_1_.yCoord; - double d8 = p_147447_2_.zCoord - p_147447_1_.zCoord; - - if (flag6) - { - d3 = (d0 - p_147447_1_.xCoord) / d6; - } - - if (flag3) - { - d4 = (d1 - p_147447_1_.yCoord) / d7; - } - - if (flag4) - { - d5 = (d2 - p_147447_1_.zCoord) / d8; - } - - boolean flag5 = false; - byte b0; - - if (d3 < d4 && d3 < d5) - { - if (i > l) - { - b0 = 4; - } - else - { - b0 = 5; - } - - p_147447_1_.xCoord = d0; - p_147447_1_.yCoord += d7 * d3; - p_147447_1_.zCoord += d8 * d3; - } - else if (d4 < d5) - { - if (j > i1) - { - b0 = 0; - } - else - { - b0 = 1; - } - - p_147447_1_.xCoord += d6 * d4; - p_147447_1_.yCoord = d1; - p_147447_1_.zCoord += d8 * d4; - } - else - { - if (k > j1) - { - b0 = 2; - } - else - { - b0 = 3; - } - - p_147447_1_.xCoord += d6 * d5; - p_147447_1_.yCoord += d7 * d5; - p_147447_1_.zCoord = d2; - } - - Vec3 vec32 = this.getWorldVec3Pool().getVecFromPool(p_147447_1_.xCoord, p_147447_1_.yCoord, p_147447_1_.zCoord); - l = (int)(vec32.xCoord = (double)MathHelper.floor_double(p_147447_1_.xCoord)); - - if (b0 == 5) - { - --l; - ++vec32.xCoord; - } - - i1 = (int)(vec32.yCoord = (double)MathHelper.floor_double(p_147447_1_.yCoord)); - - if (b0 == 1) - { - --i1; - ++vec32.yCoord; - } - - j1 = (int)(vec32.zCoord = (double)MathHelper.floor_double(p_147447_1_.zCoord)); - - if (b0 == 3) - { - --j1; - ++vec32.zCoord; - } - - Block block1 = this.getBlock(l, i1, j1); - int l1 = this.getBlockMetadata(l, i1, j1); - - if (!p_147447_4_ || block1.getCollisionBoundingBoxFromPool(this, l, i1, j1) != null) - { - if (block1.canCollideCheck(l1, p_147447_3_)) - { - MovingObjectPosition movingobjectposition1 = block1.collisionRayTrace(this, l, i1, j1, p_147447_1_, p_147447_2_); - - if (movingobjectposition1 != null) - { - return movingobjectposition1; - } - } - else - { - movingobjectposition2 = new MovingObjectPosition(l, i1, j1, b0, p_147447_1_, false); - } - } - } - - return p_147447_5_ ? movingobjectposition2 : null; - } - else - { - return null; - } - } - else - { - return null; - } - } - - /** - * Plays a sound at the entity's position. Args: entity, sound, volume (relative to 1.0), and frequency (or pitch, - * also relative to 1.0). - */ - public void playSoundAtEntity(Entity par1Entity, String par2Str, float par3, float par4) - { - PlaySoundAtEntityEvent event = new PlaySoundAtEntityEvent(par1Entity, par2Str, par3, par4); - if (MinecraftForge.EVENT_BUS.post(event)) - { - return; - } - par2Str = event.name; - for (int i = 0; i < this.worldAccesses.size(); ++i) - { - ((IWorldAccess)this.worldAccesses.get(i)).playSound(par2Str, par1Entity.posX, par1Entity.posY - (double)par1Entity.yOffset, par1Entity.posZ, par3, par4); - } - } - - /** - * Plays sound to all near players except the player reference given - */ - public void playSoundToNearExcept(EntityPlayer par1EntityPlayer, String par2Str, float par3, float par4) - { - PlaySoundAtEntityEvent event = new PlaySoundAtEntityEvent(par1EntityPlayer, par2Str, par3, par4); - if (MinecraftForge.EVENT_BUS.post(event)) - { - return; - } - par2Str = event.name; - for (int i = 0; i < this.worldAccesses.size(); ++i) - { - ((IWorldAccess)this.worldAccesses.get(i)).playSoundToNearExcept(par1EntityPlayer, par2Str, par1EntityPlayer.posX, par1EntityPlayer.posY - (double)par1EntityPlayer.yOffset, par1EntityPlayer.posZ, par3, par4); - } - } - - /** - * Play a sound effect. Many many parameters for this function. Not sure what they do, but a classic call is : - * (double)i + 0.5D, (double)j + 0.5D, (double)k + 0.5D, 'random.door_open', 1.0F, world.rand.nextFloat() * 0.1F + - * 0.9F with i,j,k position of the block. - */ - public void playSoundEffect(double par1, double par3, double par5, String par7Str, float par8, float par9) - { - for (int i = 0; i < this.worldAccesses.size(); ++i) - { - ((IWorldAccess)this.worldAccesses.get(i)).playSound(par7Str, par1, par3, par5, par8, par9); - } - } - - /** - * par8 is loudness, all pars passed to minecraftInstance.sndManager.playSound - */ - public void playSound(double par1, double par3, double par5, String par7Str, float par8, float par9, boolean par10) {} - - /** - * Plays a record at the specified coordinates of the specified name. Args: recordName, x, y, z - */ - public void playRecord(String par1Str, int par2, int par3, int par4) - { - for (int l = 0; l < this.worldAccesses.size(); ++l) - { - ((IWorldAccess)this.worldAccesses.get(l)).playRecord(par1Str, par2, par3, par4); - } - } - - /** - * Spawns a particle. Args particleName, x, y, z, velX, velY, velZ - */ - public void spawnParticle(String par1Str, double par2, double par4, double par6, double par8, double par10, double par12) - { - for (int i = 0; i < this.worldAccesses.size(); ++i) - { - ((IWorldAccess)this.worldAccesses.get(i)).spawnParticle(par1Str, par2, par4, par6, par8, par10, par12); - } - } - - /** - * adds a lightning bolt to the list of lightning bolts in this world. - */ - public boolean addWeatherEffect(Entity par1Entity) - { - this.weatherEffects.add(par1Entity); - return true; - } - - /** - * Called to place all entities as part of a world - */ - public boolean spawnEntityInWorld(Entity par1Entity) - { - int i = MathHelper.floor_double(par1Entity.posX / 16.0D); - int j = MathHelper.floor_double(par1Entity.posZ / 16.0D); - boolean flag = par1Entity.forceSpawn; - - if (par1Entity instanceof EntityPlayer) - { - flag = true; - } - - if (!flag && !this.chunkExists(i, j)) - { - return false; - } - else - { - if (par1Entity instanceof EntityPlayer) - { - EntityPlayer entityplayer = (EntityPlayer)par1Entity; - this.playerEntities.add(entityplayer); - this.updateAllPlayersSleepingFlag(); - } - if (MinecraftForge.EVENT_BUS.post(new EntityJoinWorldEvent(par1Entity, this)) && !flag) return false; - - this.getChunkFromChunkCoords(i, j).addEntity(par1Entity); - this.loadedEntityList.add(par1Entity); - this.onEntityAdded(par1Entity); - return true; - } - } - - public void onEntityAdded(Entity par1Entity) - { - for (int i = 0; i < this.worldAccesses.size(); ++i) - { - ((IWorldAccess)this.worldAccesses.get(i)).onEntityCreate(par1Entity); - } - } - - public void onEntityRemoved(Entity par1Entity) - { - for (int i = 0; i < this.worldAccesses.size(); ++i) - { - ((IWorldAccess)this.worldAccesses.get(i)).onEntityDestroy(par1Entity); - } - } - - /** - * Schedule the entity for removal during the next tick. Marks the entity dead in anticipation. - */ - public void removeEntity(Entity par1Entity) - { - if (par1Entity.riddenByEntity != null) - { - par1Entity.riddenByEntity.mountEntity((Entity)null); - } - - if (par1Entity.ridingEntity != null) - { - par1Entity.mountEntity((Entity)null); - } - - par1Entity.setDead(); - - if (par1Entity instanceof EntityPlayer) - { - this.playerEntities.remove(par1Entity); - this.updateAllPlayersSleepingFlag(); - } - } - - /** - * Do NOT use this method to remove normal entities- use normal removeEntity - */ - public void removePlayerEntityDangerously(Entity par1Entity) - { - par1Entity.setDead(); - - if (par1Entity instanceof EntityPlayer) - { - this.playerEntities.remove(par1Entity); - this.updateAllPlayersSleepingFlag(); - } - - int i = par1Entity.chunkCoordX; - int j = par1Entity.chunkCoordZ; - - if (par1Entity.addedToChunk && this.chunkExists(i, j)) - { - this.getChunkFromChunkCoords(i, j).removeEntity(par1Entity); - } - - this.loadedEntityList.remove(par1Entity); - this.onEntityRemoved(par1Entity); - } - - /** - * Adds a IWorldAccess to the list of worldAccesses - */ - public void addWorldAccess(IWorldAccess par1IWorldAccess) - { - this.worldAccesses.add(par1IWorldAccess); - } - - /** - * Returns a list of bounding boxes that collide with aabb excluding the passed in entity's collision. Args: entity, - * aabb - */ - public List getCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) - { - this.collidingBoundingBoxes.clear(); - int i = MathHelper.floor_double(par2AxisAlignedBB.minX); - int j = MathHelper.floor_double(par2AxisAlignedBB.maxX + 1.0D); - int k = MathHelper.floor_double(par2AxisAlignedBB.minY); - int l = MathHelper.floor_double(par2AxisAlignedBB.maxY + 1.0D); - int i1 = MathHelper.floor_double(par2AxisAlignedBB.minZ); - int j1 = MathHelper.floor_double(par2AxisAlignedBB.maxZ + 1.0D); - - for (int k1 = i; k1 < j; ++k1) - { - for (int l1 = i1; l1 < j1; ++l1) - { - if (this.blockExists(k1, 64, l1)) - { - for (int i2 = k - 1; i2 < l; ++i2) - { - Block block; - - if (k1 >= -30000000 && k1 < 30000000 && l1 >= -30000000 && l1 < 30000000) - { - block = this.getBlock(k1, i2, l1); - } - else - { - block = Blocks.stone; - } - - block.addCollisionBoxesToList(this, k1, i2, l1, par2AxisAlignedBB, this.collidingBoundingBoxes, par1Entity); - } - } - } - } - - double d0 = 0.25D; - List list = this.getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB.expand(d0, d0, d0)); - - for (int j2 = 0; j2 < list.size(); ++j2) - { - AxisAlignedBB axisalignedbb1 = ((Entity)list.get(j2)).getBoundingBox(); - - if (axisalignedbb1 != null && axisalignedbb1.intersectsWith(par2AxisAlignedBB)) - { - this.collidingBoundingBoxes.add(axisalignedbb1); - } - - axisalignedbb1 = par1Entity.getCollisionBox((Entity)list.get(j2)); - - if (axisalignedbb1 != null && axisalignedbb1.intersectsWith(par2AxisAlignedBB)) - { - this.collidingBoundingBoxes.add(axisalignedbb1); - } - } - - return this.collidingBoundingBoxes; - } - - public List func_147461_a(AxisAlignedBB p_147461_1_) - { - this.collidingBoundingBoxes.clear(); - int i = MathHelper.floor_double(p_147461_1_.minX); - int j = MathHelper.floor_double(p_147461_1_.maxX + 1.0D); - int k = MathHelper.floor_double(p_147461_1_.minY); - int l = MathHelper.floor_double(p_147461_1_.maxY + 1.0D); - int i1 = MathHelper.floor_double(p_147461_1_.minZ); - int j1 = MathHelper.floor_double(p_147461_1_.maxZ + 1.0D); - - for (int k1 = i; k1 < j; ++k1) - { - for (int l1 = i1; l1 < j1; ++l1) - { - if (this.blockExists(k1, 64, l1)) - { - for (int i2 = k - 1; i2 < l; ++i2) - { - Block block; - - if (k1 >= -30000000 && k1 < 30000000 && l1 >= -30000000 && l1 < 30000000) - { - block = this.getBlock(k1, i2, l1); - } - else - { - block = Blocks.bedrock; - } - - block.addCollisionBoxesToList(this, k1, i2, l1, p_147461_1_, this.collidingBoundingBoxes, (Entity)null); - } - } - } - } - - return this.collidingBoundingBoxes; - } - - /** - * Returns the amount of skylight subtracted for the current time - */ - public int calculateSkylightSubtracted(float par1) - { - float f1 = this.getCelestialAngle(par1); - float f2 = 1.0F - (MathHelper.cos(f1 * (float)Math.PI * 2.0F) * 2.0F + 0.5F); - - if (f2 < 0.0F) - { - f2 = 0.0F; - } - - if (f2 > 1.0F) - { - f2 = 1.0F; - } - - f2 = 1.0F - f2; - f2 = (float)((double)f2 * (1.0D - (double)(this.getRainStrength(par1) * 5.0F) / 16.0D)); - f2 = (float)((double)f2 * (1.0D - (double)(this.getWeightedThunderStrength(par1) * 5.0F) / 16.0D)); - f2 = 1.0F - f2; - return (int)(f2 * 11.0F); - } - - /** - * Removes a worldAccess from the worldAccesses object - */ - public void removeWorldAccess(IWorldAccess par1IWorldAccess) - { - this.worldAccesses.remove(par1IWorldAccess); - } - - /** - * Returns the sun brightness - checks time of day, rain and thunder - */ - @SideOnly(Side.CLIENT) - public float getSunBrightness(float par1) - { - float f1 = this.getCelestialAngle(par1); - float f2 = 1.0F - (MathHelper.cos(f1 * (float)Math.PI * 2.0F) * 2.0F + 0.2F); - - if (f2 < 0.0F) - { - f2 = 0.0F; - } - - if (f2 > 1.0F) - { - f2 = 1.0F; - } - - f2 = 1.0F - f2; - f2 = (float)((double)f2 * (1.0D - (double)(this.getRainStrength(par1) * 5.0F) / 16.0D)); - f2 = (float)((double)f2 * (1.0D - (double)(this.getWeightedThunderStrength(par1) * 5.0F) / 16.0D)); - return f2 * 0.8F + 0.2F; - } - - /** - * Calculates the color for the skybox - */ - @SideOnly(Side.CLIENT) - public Vec3 getSkyColor(Entity par1Entity, float par2) - { - return provider.getSkyColor(par1Entity, par2); - } - - @SideOnly(Side.CLIENT) - public Vec3 getSkyColorBody(Entity par1Entity, float par2) - { - float f1 = this.getCelestialAngle(par2); - float f2 = MathHelper.cos(f1 * (float)Math.PI * 2.0F) * 2.0F + 0.5F; - - if (f2 < 0.0F) - { - f2 = 0.0F; - } - - if (f2 > 1.0F) - { - f2 = 1.0F; - } - - int i = MathHelper.floor_double(par1Entity.posX); - int j = MathHelper.floor_double(par1Entity.posY); - int k = MathHelper.floor_double(par1Entity.posZ); - int l = ForgeHooksClient.getSkyBlendColour(this, i, j, k); - float f4 = (float)(l >> 16 & 255) / 255.0F; - float f5 = (float)(l >> 8 & 255) / 255.0F; - float f6 = (float)(l & 255) / 255.0F; - f4 *= f2; - f5 *= f2; - f6 *= f2; - float f7 = this.getRainStrength(par2); - float f8; - float f9; - - if (f7 > 0.0F) - { - f8 = (f4 * 0.3F + f5 * 0.59F + f6 * 0.11F) * 0.6F; - f9 = 1.0F - f7 * 0.75F; - f4 = f4 * f9 + f8 * (1.0F - f9); - f5 = f5 * f9 + f8 * (1.0F - f9); - f6 = f6 * f9 + f8 * (1.0F - f9); - } - - f8 = this.getWeightedThunderStrength(par2); - - if (f8 > 0.0F) - { - f9 = (f4 * 0.3F + f5 * 0.59F + f6 * 0.11F) * 0.2F; - float f10 = 1.0F - f8 * 0.75F; - f4 = f4 * f10 + f9 * (1.0F - f10); - f5 = f5 * f10 + f9 * (1.0F - f10); - f6 = f6 * f10 + f9 * (1.0F - f10); - } - - if (this.lastLightningBolt > 0) - { - f9 = (float)this.lastLightningBolt - par2; - - if (f9 > 1.0F) - { - f9 = 1.0F; - } - - f9 *= 0.45F; - f4 = f4 * (1.0F - f9) + 0.8F * f9; - f5 = f5 * (1.0F - f9) + 0.8F * f9; - f6 = f6 * (1.0F - f9) + 1.0F * f9; - } - - return this.getWorldVec3Pool().getVecFromPool((double)f4, (double)f5, (double)f6); - } - - /** - * calls calculateCelestialAngle - */ - public float getCelestialAngle(float par1) - { - return this.provider.calculateCelestialAngle(this.worldInfo.getWorldTime(), par1); - } - - @SideOnly(Side.CLIENT) - public int getMoonPhase() - { - return this.provider.getMoonPhase(this.worldInfo.getWorldTime()); - } - - /** - * gets the current fullness of the moon expressed as a float between 1.0 and 0.0, in steps of .25 - */ - public float getCurrentMoonPhaseFactor() - { - return WorldProvider.moonPhaseFactors[this.provider.getMoonPhase(this.worldInfo.getWorldTime())]; - } - - /** - * Return getCelestialAngle()*2*PI - */ - public float getCelestialAngleRadians(float par1) - { - float f1 = this.getCelestialAngle(par1); - return f1 * (float)Math.PI * 2.0F; - } - - @SideOnly(Side.CLIENT) - public Vec3 getCloudColour(float par1) - { - return provider.drawClouds(par1); - } - - @SideOnly(Side.CLIENT) - public Vec3 drawCloudsBody(float par1) - { - float f1 = this.getCelestialAngle(par1); - float f2 = MathHelper.cos(f1 * (float)Math.PI * 2.0F) * 2.0F + 0.5F; - - if (f2 < 0.0F) - { - f2 = 0.0F; - } - - if (f2 > 1.0F) - { - f2 = 1.0F; - } - - float f3 = (float)(this.cloudColour >> 16 & 255L) / 255.0F; - float f4 = (float)(this.cloudColour >> 8 & 255L) / 255.0F; - float f5 = (float)(this.cloudColour & 255L) / 255.0F; - float f6 = this.getRainStrength(par1); - float f7; - float f8; - - if (f6 > 0.0F) - { - f7 = (f3 * 0.3F + f4 * 0.59F + f5 * 0.11F) * 0.6F; - f8 = 1.0F - f6 * 0.95F; - f3 = f3 * f8 + f7 * (1.0F - f8); - f4 = f4 * f8 + f7 * (1.0F - f8); - f5 = f5 * f8 + f7 * (1.0F - f8); - } - - f3 *= f2 * 0.9F + 0.1F; - f4 *= f2 * 0.9F + 0.1F; - f5 *= f2 * 0.85F + 0.15F; - f7 = this.getWeightedThunderStrength(par1); - - if (f7 > 0.0F) - { - f8 = (f3 * 0.3F + f4 * 0.59F + f5 * 0.11F) * 0.2F; - float f9 = 1.0F - f7 * 0.95F; - f3 = f3 * f9 + f8 * (1.0F - f9); - f4 = f4 * f9 + f8 * (1.0F - f9); - f5 = f5 * f9 + f8 * (1.0F - f9); - } - - return this.getWorldVec3Pool().getVecFromPool((double)f3, (double)f4, (double)f5); - } - - /** - * Returns vector(ish) with R/G/B for fog - */ - @SideOnly(Side.CLIENT) - public Vec3 getFogColor(float par1) - { - float f1 = this.getCelestialAngle(par1); - return this.provider.getFogColor(f1, par1); - } - - /** - * Gets the height to which rain/snow will fall. Calculates it if not already stored. - */ - public int getPrecipitationHeight(int par1, int par2) - { - return this.getChunkFromBlockCoords(par1, par2).getPrecipitationHeight(par1 & 15, par2 & 15); - } - - /** - * Finds the highest block on the x, z coordinate that is solid and returns its y coord. Args x, z - */ - public int getTopSolidOrLiquidBlock(int par1, int par2) - { - Chunk chunk = this.getChunkFromBlockCoords(par1, par2); - int x = par1; - int z = par2; - int k = chunk.getTopFilledSegment() + 15; - par1 &= 15; - - for (par2 &= 15; k > 0; --k) - { - Block block = chunk.getBlock(par1, k, par2); - - if (block.getMaterial().blocksMovement() && block.getMaterial() != Material.leaves && !block.isFoliage(this, x, k, z)) - { - return k + 1; - } - } - - return -1; - } - - /** - * How bright are stars in the sky - */ - @SideOnly(Side.CLIENT) - public float getStarBrightness(float par1) - { - return provider.getStarBrightness(par1); - } - - @SideOnly(Side.CLIENT) - public float getStarBrightnessBody(float par1) - { - float f1 = this.getCelestialAngle(par1); - float f2 = 1.0F - (MathHelper.cos(f1 * (float)Math.PI * 2.0F) * 2.0F + 0.25F); - - if (f2 < 0.0F) - { - f2 = 0.0F; - } - - if (f2 > 1.0F) - { - f2 = 1.0F; - } - - return f2 * f2 * 0.5F; - } - - /** - * Schedules a tick to a block with a delay (Most commonly the tick rate) - */ - public void scheduleBlockUpdate(int p_147464_1_, int p_147464_2_, int p_147464_3_, Block p_147464_4_, int p_147464_5_) {} - - public void scheduleBlockUpdateWithPriority(int p_147454_1_, int p_147454_2_, int p_147454_3_, Block p_147454_4_, int p_147454_5_, int p_147454_6_) {} - - public void func_147446_b(int p_147446_1_, int p_147446_2_, int p_147446_3_, Block p_147446_4_, int p_147446_5_, int p_147446_6_) {} - - /** - * Updates (and cleans up) entities and tile entities - */ - public void updateEntities() - { - this.theProfiler.startSection("entities"); - this.theProfiler.startSection("global"); - int i; - Entity entity; - CrashReport crashreport; - CrashReportCategory crashreportcategory; - - for (i = 0; i < this.weatherEffects.size(); ++i) - { - entity = (Entity)this.weatherEffects.get(i); - - try - { - ++entity.ticksExisted; - entity.onUpdate(); - } - catch (Throwable throwable2) - { - crashreport = CrashReport.makeCrashReport(throwable2, "Ticking entity"); - crashreportcategory = crashreport.makeCategory("Entity being ticked"); - - if (entity == null) - { - crashreportcategory.addCrashSection("Entity", "~~NULL~~"); - } - else - { - entity.addEntityCrashInfo(crashreportcategory); - } - - if (ForgeModContainer.removeErroringEntities) - { - FMLLog.severe(crashreport.getCompleteReport()); - removeEntity(entity); - } - else - { - throw new ReportedException(crashreport); - } - } - - if (entity.isDead) - { - this.weatherEffects.remove(i--); - } - } - - this.theProfiler.endStartSection("remove"); - this.loadedEntityList.removeAll(this.unloadedEntityList); - int j; - int l; - - for (i = 0; i < this.unloadedEntityList.size(); ++i) - { - entity = (Entity)this.unloadedEntityList.get(i); - j = entity.chunkCoordX; - l = entity.chunkCoordZ; - - if (entity.addedToChunk && this.chunkExists(j, l)) - { - this.getChunkFromChunkCoords(j, l).removeEntity(entity); - } - } - - for (i = 0; i < this.unloadedEntityList.size(); ++i) - { - this.onEntityRemoved((Entity)this.unloadedEntityList.get(i)); - } - - this.unloadedEntityList.clear(); - this.theProfiler.endStartSection("regular"); - - for (i = 0; i < this.loadedEntityList.size(); ++i) - { - entity = (Entity)this.loadedEntityList.get(i); - - if (entity.ridingEntity != null) - { - if (!entity.ridingEntity.isDead && entity.ridingEntity.riddenByEntity == entity) - { - continue; - } - - entity.ridingEntity.riddenByEntity = null; - entity.ridingEntity = null; - } - - this.theProfiler.startSection("tick"); - - if (!entity.isDead) - { - try - { - ProfilerSection.ENTITY_UPDATETIME.start(entity); - this.updateEntity(entity); - ProfilerSection.ENTITY_UPDATETIME.stop(entity); - } - catch (Throwable throwable1) - { - crashreport = CrashReport.makeCrashReport(throwable1, "Ticking entity"); - crashreportcategory = crashreport.makeCategory("Entity being ticked"); - entity.addEntityCrashInfo(crashreportcategory); - - if (ForgeModContainer.removeErroringEntities) - { - FMLLog.severe(crashreport.getCompleteReport()); - removeEntity(entity); - } - else - { - throw new ReportedException(crashreport); - } - } - } - - this.theProfiler.endSection(); - this.theProfiler.startSection("remove"); - - if (entity.isDead) - { - j = entity.chunkCoordX; - l = entity.chunkCoordZ; - - if (entity.addedToChunk && this.chunkExists(j, l)) - { - this.getChunkFromChunkCoords(j, l).removeEntity(entity); - } - - this.loadedEntityList.remove(i--); - this.onEntityRemoved(entity); - } - - this.theProfiler.endSection(); - } - - this.theProfiler.endStartSection("blockEntities"); - this.field_147481_N = true; - Iterator iterator = this.loadedTileEntityList.iterator(); - - while (iterator.hasNext()) - { - TileEntity tileentity = (TileEntity)iterator.next(); - - if (!tileentity.isInvalid() && tileentity.hasWorldObj() && this.blockExists(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord)) - { - try - { - ProfilerSection.TILEENT_UPDATETIME.start(tileentity); - tileentity.updateEntity(); - ProfilerSection.TILEENT_UPDATETIME.stop(tileentity); - } - catch (Throwable throwable) - { - crashreport = CrashReport.makeCrashReport(throwable, "Ticking block entity"); - crashreportcategory = crashreport.makeCategory("Block entity being ticked"); - tileentity.func_145828_a(crashreportcategory); - if (ForgeModContainer.removeErroringTileEntities) - { - FMLLog.severe(crashreport.getCompleteReport()); - tileentity.invalidate(); - setBlockToAir(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord); - } - else - { - throw new ReportedException(crashreport); - } - } - } - - if (tileentity.isInvalid()) - { - iterator.remove(); - - if (this.chunkExists(tileentity.xCoord >> 4, tileentity.zCoord >> 4)) - { - Chunk chunk = this.getChunkFromChunkCoords(tileentity.xCoord >> 4, tileentity.zCoord >> 4); - - if (chunk != null) - { - chunk.removeInvalidTileEntity(tileentity.xCoord & 15, tileentity.yCoord, tileentity.zCoord & 15); - } - } - } - } - - if (!this.field_147483_b.isEmpty()) - { - for (Object tile : field_147483_b) - { - ((TileEntity)tile).onChunkUnload(); - } - this.loadedTileEntityList.removeAll(this.field_147483_b); - this.field_147483_b.clear(); - } - - this.field_147481_N = false; - - this.theProfiler.endStartSection("pendingBlockEntities"); - - if (!this.addedTileEntityList.isEmpty()) - { - for (int k = 0; k < this.addedTileEntityList.size(); ++k) - { - TileEntity tileentity1 = (TileEntity)this.addedTileEntityList.get(k); - - if (!tileentity1.isInvalid()) - { - if (!this.loadedTileEntityList.contains(tileentity1)) - { - this.loadedTileEntityList.add(tileentity1); - } - } - else - { - if (this.chunkExists(tileentity1.xCoord >> 4, tileentity1.zCoord >> 4)) - { - Chunk chunk1 = this.getChunkFromChunkCoords(tileentity1.xCoord >> 4, tileentity1.zCoord >> 4); - - if (chunk1 != null) - { - chunk1.removeInvalidTileEntity(tileentity1.xCoord & 15, tileentity1.yCoord, tileentity1.zCoord & 15); - } - } - } - } - - this.addedTileEntityList.clear(); - } - - this.theProfiler.endSection(); - this.theProfiler.endSection(); - } - - public void func_147448_a(Collection p_147448_1_) - { - List dest = field_147481_N ? addedTileEntityList : loadedTileEntityList; - for(TileEntity entity : (Collection)p_147448_1_) - { - if(entity.canUpdate()) dest.add(entity); - } - } - - /** - * Will update the entity in the world if the chunk the entity is in is currently loaded. Args: entity - */ - public void updateEntity(Entity par1Entity) - { - this.updateEntityWithOptionalForce(par1Entity, true); - } - - /** - * Will update the entity in the world if the chunk the entity is in is currently loaded or its forced to update. - * Args: entity, forceUpdate - */ - public void updateEntityWithOptionalForce(Entity par1Entity, boolean par2) - { - int i = MathHelper.floor_double(par1Entity.posX); - int j = MathHelper.floor_double(par1Entity.posZ); - boolean isForced = getPersistentChunks().containsKey(new ChunkCoordIntPair(i >> 4, j >> 4)); - byte b0 = isForced ? (byte)0 : 32; - boolean canUpdate = !par2 || this.checkChunksExist(i - b0, 0, j - b0, i + b0, 0, j + b0); - - if (!canUpdate) - { - EntityEvent.CanUpdate event = new EntityEvent.CanUpdate(par1Entity); - MinecraftForge.EVENT_BUS.post(event); - canUpdate = event.canUpdate; - } - - if (canUpdate) - { - par1Entity.lastTickPosX = par1Entity.posX; - par1Entity.lastTickPosY = par1Entity.posY; - par1Entity.lastTickPosZ = par1Entity.posZ; - par1Entity.prevRotationYaw = par1Entity.rotationYaw; - par1Entity.prevRotationPitch = par1Entity.rotationPitch; - - if (par2 && par1Entity.addedToChunk) - { - ++par1Entity.ticksExisted; - - if (par1Entity.ridingEntity != null) - { - par1Entity.updateRidden(); - } - else - { - par1Entity.onUpdate(); - } - } - - this.theProfiler.startSection("chunkCheck"); - - if (Double.isNaN(par1Entity.posX) || Double.isInfinite(par1Entity.posX)) - { - par1Entity.posX = par1Entity.lastTickPosX; - } - - if (Double.isNaN(par1Entity.posY) || Double.isInfinite(par1Entity.posY)) - { - par1Entity.posY = par1Entity.lastTickPosY; - } - - if (Double.isNaN(par1Entity.posZ) || Double.isInfinite(par1Entity.posZ)) - { - par1Entity.posZ = par1Entity.lastTickPosZ; - } - - if (Double.isNaN((double)par1Entity.rotationPitch) || Double.isInfinite((double)par1Entity.rotationPitch)) - { - par1Entity.rotationPitch = par1Entity.prevRotationPitch; - } - - if (Double.isNaN((double)par1Entity.rotationYaw) || Double.isInfinite((double)par1Entity.rotationYaw)) - { - par1Entity.rotationYaw = par1Entity.prevRotationYaw; - } - - int k = MathHelper.floor_double(par1Entity.posX / 16.0D); - int l = MathHelper.floor_double(par1Entity.posY / 16.0D); - int i1 = MathHelper.floor_double(par1Entity.posZ / 16.0D); - - if (!par1Entity.addedToChunk || par1Entity.chunkCoordX != k || par1Entity.chunkCoordY != l || par1Entity.chunkCoordZ != i1) - { - if (par1Entity.addedToChunk && this.chunkExists(par1Entity.chunkCoordX, par1Entity.chunkCoordZ)) - { - this.getChunkFromChunkCoords(par1Entity.chunkCoordX, par1Entity.chunkCoordZ).removeEntityAtIndex(par1Entity, par1Entity.chunkCoordY); - } - - if (this.chunkExists(k, i1)) - { - par1Entity.addedToChunk = true; - this.getChunkFromChunkCoords(k, i1).addEntity(par1Entity); - } - else - { - par1Entity.addedToChunk = false; - } - } - - this.theProfiler.endSection(); - - if (par2 && par1Entity.addedToChunk && par1Entity.riddenByEntity != null) - { - if (!par1Entity.riddenByEntity.isDead && par1Entity.riddenByEntity.ridingEntity == par1Entity) - { - this.updateEntity(par1Entity.riddenByEntity); - } - else - { - par1Entity.riddenByEntity.ridingEntity = null; - par1Entity.riddenByEntity = null; - } - } - } - } - - /** - * Returns true if there are no solid, live entities in the specified AxisAlignedBB - */ - public boolean checkNoEntityCollision(AxisAlignedBB par1AxisAlignedBB) - { - return this.checkNoEntityCollision(par1AxisAlignedBB, (Entity)null); - } - - /** - * Returns true if there are no solid, live entities in the specified AxisAlignedBB, excluding the given entity - */ - public boolean checkNoEntityCollision(AxisAlignedBB par1AxisAlignedBB, Entity par2Entity) - { - List list = this.getEntitiesWithinAABBExcludingEntity((Entity)null, par1AxisAlignedBB); - - for (int i = 0; i < list.size(); ++i) - { - Entity entity1 = (Entity)list.get(i); - - if (!entity1.isDead && entity1.preventEntitySpawning && entity1 != par2Entity) - { - return false; - } - } - - return true; - } - - /** - * Returns true if there are any blocks in the region constrained by an AxisAlignedBB - */ - public boolean checkBlockCollision(AxisAlignedBB par1AxisAlignedBB) - { - int i = MathHelper.floor_double(par1AxisAlignedBB.minX); - int j = MathHelper.floor_double(par1AxisAlignedBB.maxX + 1.0D); - int k = MathHelper.floor_double(par1AxisAlignedBB.minY); - int l = MathHelper.floor_double(par1AxisAlignedBB.maxY + 1.0D); - int i1 = MathHelper.floor_double(par1AxisAlignedBB.minZ); - int j1 = MathHelper.floor_double(par1AxisAlignedBB.maxZ + 1.0D); - - if (par1AxisAlignedBB.minX < 0.0D) - { - --i; - } - - if (par1AxisAlignedBB.minY < 0.0D) - { - --k; - } - - if (par1AxisAlignedBB.minZ < 0.0D) - { - --i1; - } - - for (int k1 = i; k1 < j; ++k1) - { - for (int l1 = k; l1 < l; ++l1) - { - for (int i2 = i1; i2 < j1; ++i2) - { - Block block = this.getBlock(k1, l1, i2); - - if (block.getMaterial() != Material.air) - { - return true; - } - } - } - } - - return false; - } - - /** - * Returns if any of the blocks within the aabb are liquids. Args: aabb - */ - public boolean isAnyLiquid(AxisAlignedBB par1AxisAlignedBB) - { - int i = MathHelper.floor_double(par1AxisAlignedBB.minX); - int j = MathHelper.floor_double(par1AxisAlignedBB.maxX + 1.0D); - int k = MathHelper.floor_double(par1AxisAlignedBB.minY); - int l = MathHelper.floor_double(par1AxisAlignedBB.maxY + 1.0D); - int i1 = MathHelper.floor_double(par1AxisAlignedBB.minZ); - int j1 = MathHelper.floor_double(par1AxisAlignedBB.maxZ + 1.0D); - - if (par1AxisAlignedBB.minX < 0.0D) - { - --i; - } - - if (par1AxisAlignedBB.minY < 0.0D) - { - --k; - } - - if (par1AxisAlignedBB.minZ < 0.0D) - { - --i1; - } - - for (int k1 = i; k1 < j; ++k1) - { - for (int l1 = k; l1 < l; ++l1) - { - for (int i2 = i1; i2 < j1; ++i2) - { - Block block = this.getBlock(k1, l1, i2); - - if (block.getMaterial().isLiquid()) - { - return true; - } - } - } - } - - return false; - } - - public boolean func_147470_e(AxisAlignedBB p_147470_1_) - { - int i = MathHelper.floor_double(p_147470_1_.minX); - int j = MathHelper.floor_double(p_147470_1_.maxX + 1.0D); - int k = MathHelper.floor_double(p_147470_1_.minY); - int l = MathHelper.floor_double(p_147470_1_.maxY + 1.0D); - int i1 = MathHelper.floor_double(p_147470_1_.minZ); - int j1 = MathHelper.floor_double(p_147470_1_.maxZ + 1.0D); - - if (this.checkChunksExist(i, k, i1, j, l, j1)) - { - for (int k1 = i; k1 < j; ++k1) - { - for (int l1 = k; l1 < l; ++l1) - { - for (int i2 = i1; i2 < j1; ++i2) - { - Block block = this.getBlock(k1, l1, i2); - - if (block == Blocks.fire || block == Blocks.flowing_lava || block == Blocks.lava) - { - return true; - } - else - { - if (block.isBurning(this, k1, l1, i2)) return true; - } - } - } - } - } - - return false; - } - - /** - * handles the acceleration of an object whilst in water. Not sure if it is used elsewhere. - */ - public boolean handleMaterialAcceleration(AxisAlignedBB par1AxisAlignedBB, Material par2Material, Entity par3Entity) - { - int i = MathHelper.floor_double(par1AxisAlignedBB.minX); - int j = MathHelper.floor_double(par1AxisAlignedBB.maxX + 1.0D); - int k = MathHelper.floor_double(par1AxisAlignedBB.minY); - int l = MathHelper.floor_double(par1AxisAlignedBB.maxY + 1.0D); - int i1 = MathHelper.floor_double(par1AxisAlignedBB.minZ); - int j1 = MathHelper.floor_double(par1AxisAlignedBB.maxZ + 1.0D); - - if (!this.checkChunksExist(i, k, i1, j, l, j1)) - { - return false; - } - else - { - boolean flag = false; - Vec3 vec3 = this.getWorldVec3Pool().getVecFromPool(0.0D, 0.0D, 0.0D); - - for (int k1 = i; k1 < j; ++k1) - { - for (int l1 = k; l1 < l; ++l1) - { - for (int i2 = i1; i2 < j1; ++i2) - { - Block block = this.getBlock(k1, l1, i2); - - if (block.getMaterial() == par2Material) - { - double d0 = (double)((float)(l1 + 1) - BlockLiquid.getLiquidHeightPercent(this.getBlockMetadata(k1, l1, i2))); - - if ((double)l >= d0) - { - flag = true; - block.velocityToAddToEntity(this, k1, l1, i2, par3Entity, vec3); - } - } - } - } - } - - if (vec3.lengthVector() > 0.0D && par3Entity.isPushedByWater()) - { - vec3 = vec3.normalize(); - double d1 = 0.014D; - par3Entity.motionX += vec3.xCoord * d1; - par3Entity.motionY += vec3.yCoord * d1; - par3Entity.motionZ += vec3.zCoord * d1; - } - - return flag; - } - } - - /** - * Returns true if the given bounding box contains the given material - */ - public boolean isMaterialInBB(AxisAlignedBB par1AxisAlignedBB, Material par2Material) - { - int i = MathHelper.floor_double(par1AxisAlignedBB.minX); - int j = MathHelper.floor_double(par1AxisAlignedBB.maxX + 1.0D); - int k = MathHelper.floor_double(par1AxisAlignedBB.minY); - int l = MathHelper.floor_double(par1AxisAlignedBB.maxY + 1.0D); - int i1 = MathHelper.floor_double(par1AxisAlignedBB.minZ); - int j1 = MathHelper.floor_double(par1AxisAlignedBB.maxZ + 1.0D); - - for (int k1 = i; k1 < j; ++k1) - { - for (int l1 = k; l1 < l; ++l1) - { - for (int i2 = i1; i2 < j1; ++i2) - { - if (this.getBlock(k1, l1, i2).getMaterial() == par2Material) - { - return true; - } - } - } - } - - return false; - } - - /** - * checks if the given AABB is in the material given. Used while swimming. - */ - public boolean isAABBInMaterial(AxisAlignedBB par1AxisAlignedBB, Material par2Material) - { - int i = MathHelper.floor_double(par1AxisAlignedBB.minX); - int j = MathHelper.floor_double(par1AxisAlignedBB.maxX + 1.0D); - int k = MathHelper.floor_double(par1AxisAlignedBB.minY); - int l = MathHelper.floor_double(par1AxisAlignedBB.maxY + 1.0D); - int i1 = MathHelper.floor_double(par1AxisAlignedBB.minZ); - int j1 = MathHelper.floor_double(par1AxisAlignedBB.maxZ + 1.0D); - - for (int k1 = i; k1 < j; ++k1) - { - for (int l1 = k; l1 < l; ++l1) - { - for (int i2 = i1; i2 < j1; ++i2) - { - Block block = this.getBlock(k1, l1, i2); - - if (block.getMaterial() == par2Material) - { - int j2 = this.getBlockMetadata(k1, l1, i2); - double d0 = (double)(l1 + 1); - - if (j2 < 8) - { - d0 = (double)(l1 + 1) - (double)j2 / 8.0D; - } - - if (d0 >= par1AxisAlignedBB.minY) - { - return true; - } - } - } - } - } - - return false; - } - - /** - * Creates an explosion. Args: entity, x, y, z, strength - */ - public Explosion createExplosion(Entity par1Entity, double par2, double par4, double par6, float par8, boolean par9) - { - return this.newExplosion(par1Entity, par2, par4, par6, par8, false, par9); - } - - /** - * returns a new explosion. Does initiation (at time of writing Explosion is not finished) - */ - public Explosion newExplosion(Entity par1Entity, double par2, double par4, double par6, float par8, boolean par9, boolean par10) - { - Explosion explosion = new Explosion(this, par1Entity, par2, par4, par6, par8); - explosion.isFlaming = par9; - explosion.isSmoking = par10; - explosion.doExplosionA(); - explosion.doExplosionB(true); - return explosion; - } - - /** - * Gets the percentage of real blocks within within a bounding box, along a specified vector. - */ - public float getBlockDensity(Vec3 par1Vec3, AxisAlignedBB par2AxisAlignedBB) - { - double d0 = 1.0D / ((par2AxisAlignedBB.maxX - par2AxisAlignedBB.minX) * 2.0D + 1.0D); - double d1 = 1.0D / ((par2AxisAlignedBB.maxY - par2AxisAlignedBB.minY) * 2.0D + 1.0D); - double d2 = 1.0D / ((par2AxisAlignedBB.maxZ - par2AxisAlignedBB.minZ) * 2.0D + 1.0D); - int i = 0; - int j = 0; - - for (float f = 0.0F; f <= 1.0F; f = (float)((double)f + d0)) - { - for (float f1 = 0.0F; f1 <= 1.0F; f1 = (float)((double)f1 + d1)) - { - for (float f2 = 0.0F; f2 <= 1.0F; f2 = (float)((double)f2 + d2)) - { - double d3 = par2AxisAlignedBB.minX + (par2AxisAlignedBB.maxX - par2AxisAlignedBB.minX) * (double)f; - double d4 = par2AxisAlignedBB.minY + (par2AxisAlignedBB.maxY - par2AxisAlignedBB.minY) * (double)f1; - double d5 = par2AxisAlignedBB.minZ + (par2AxisAlignedBB.maxZ - par2AxisAlignedBB.minZ) * (double)f2; - - if (this.rayTraceBlocks(this.getWorldVec3Pool().getVecFromPool(d3, d4, d5), par1Vec3) == null) - { - ++i; - } - - ++j; - } - } - } - - return (float)i / (float)j; - } - - /** - * If the block in the given direction of the given coordinate is fire, extinguish it. Args: Player, X,Y,Z, - * blockDirection - */ - public boolean extinguishFire(EntityPlayer par1EntityPlayer, int par2, int par3, int par4, int par5) - { - if (par5 == 0) - { - --par3; - } - - if (par5 == 1) - { - ++par3; - } - - if (par5 == 2) - { - --par4; - } - - if (par5 == 3) - { - ++par4; - } - - if (par5 == 4) - { - --par2; - } - - if (par5 == 5) - { - ++par2; - } - - if (this.getBlock(par2, par3, par4) == Blocks.fire) - { - this.playAuxSFXAtEntity(par1EntityPlayer, 1004, par2, par3, par4, 0); - this.setBlockToAir(par2, par3, par4); - return true; - } - else - { - return false; - } - } - - /** - * This string is 'All: (number of loaded entities)' Viewable by press ing F3 - */ - @SideOnly(Side.CLIENT) - public String getDebugLoadedEntities() - { - return "All: " + this.loadedEntityList.size(); - } - - /** - * Returns the name of the current chunk provider, by calling chunkprovider.makeString() - */ - @SideOnly(Side.CLIENT) - public String getProviderName() - { - return this.chunkProvider.makeString(); - } - - public TileEntity getTileEntity(int p_147438_1_, int p_147438_2_, int p_147438_3_) - { - if (p_147438_2_ >= 0 && p_147438_2_ < 256) - { - TileEntity tileentity = null; - int l; - TileEntity tileentity1; - - if (this.field_147481_N) - { - for (l = 0; l < this.addedTileEntityList.size(); ++l) - { - tileentity1 = (TileEntity)this.addedTileEntityList.get(l); - - if (!tileentity1.isInvalid() && tileentity1.xCoord == p_147438_1_ && tileentity1.yCoord == p_147438_2_ && tileentity1.zCoord == p_147438_3_) - { - tileentity = tileentity1; - break; - } - } - } - - if (tileentity == null) - { - Chunk chunk = this.getChunkFromChunkCoords(p_147438_1_ >> 4, p_147438_3_ >> 4); - - if (chunk != null) - { - tileentity = chunk.func_150806_e(p_147438_1_ & 15, p_147438_2_, p_147438_3_ & 15); - } - } - - if (tileentity == null) - { - for (l = 0; l < this.addedTileEntityList.size(); ++l) - { - tileentity1 = (TileEntity)this.addedTileEntityList.get(l); - - if (!tileentity1.isInvalid() && tileentity1.xCoord == p_147438_1_ && tileentity1.yCoord == p_147438_2_ && tileentity1.zCoord == p_147438_3_) - { - tileentity = tileentity1; - break; - } - } - } - - return tileentity; - } - else - { - return null; - } - } - - public void setTileEntity(int p_147455_1_, int p_147455_2_, int p_147455_3_, TileEntity p_147455_4_) - { - if (p_147455_4_ == null || p_147455_4_.isInvalid()) - { - return; - } - - if (p_147455_4_.canUpdate()) - { - if (this.field_147481_N) - { - Iterator iterator = this.addedTileEntityList.iterator(); - - while (iterator.hasNext()) - { - TileEntity tileentity1 = (TileEntity)iterator.next(); - - if (tileentity1.xCoord == p_147455_1_ && tileentity1.yCoord == p_147455_2_ && tileentity1.zCoord == p_147455_3_) - { - tileentity1.invalidate(); - iterator.remove(); - } - } - - this.addedTileEntityList.add(p_147455_4_); - } - else - { - this.loadedTileEntityList.add(p_147455_4_); - } - } - Chunk chunk = this.getChunkFromChunkCoords(p_147455_1_ >> 4, p_147455_3_ >> 4); - if (chunk != null) - { - chunk.func_150812_a(p_147455_1_ & 15, p_147455_2_, p_147455_3_ & 15, p_147455_4_); - } - //notify tile changes - func_147453_f(p_147455_1_, p_147455_2_, p_147455_3_, getBlock(p_147455_1_, p_147455_2_, p_147455_3_)); - } - - public void removeTileEntity(int p_147475_1_, int p_147475_2_, int p_147475_3_) - { - Chunk chunk = getChunkFromChunkCoords(p_147475_1_ >> 4, p_147475_3_ >> 4); - if (chunk != null) chunk.removeTileEntity(p_147475_1_ & 15, p_147475_2_, p_147475_3_ & 15); - func_147453_f(p_147475_1_, p_147475_2_, p_147475_3_, getBlock(p_147475_1_, p_147475_2_, p_147475_3_)); - } - - public void func_147457_a(TileEntity p_147457_1_) - { - this.field_147483_b.add(p_147457_1_); - } - - public boolean func_147469_q(int p_147469_1_, int p_147469_2_, int p_147469_3_) - { - AxisAlignedBB axisalignedbb = this.getBlock(p_147469_1_, p_147469_2_, p_147469_3_).getCollisionBoundingBoxFromPool(this, p_147469_1_, p_147469_2_, p_147469_3_); - return axisalignedbb != null && axisalignedbb.getAverageEdgeLength() >= 1.0D; - } - - /** - * Returns true if the block at the given coordinate has a solid (buildable) top surface. - */ - public static boolean doesBlockHaveSolidTopSurface(IBlockAccess p_147466_0_, int p_147466_1_, int p_147466_2_, int p_147466_3_) - { - Block block = p_147466_0_.getBlock(p_147466_1_, p_147466_2_, p_147466_3_); - return block.isSideSolid(p_147466_0_, p_147466_1_, p_147466_2_, p_147466_3_, ForgeDirection.UP); - } - - /** - * Checks if the block is a solid, normal cube. If the chunk does not exist, or is not loaded, it returns the - * boolean parameter - */ - public boolean isBlockNormalCubeDefault(int p_147445_1_, int p_147445_2_, int p_147445_3_, boolean p_147445_4_) - { - if (p_147445_1_ >= -30000000 && p_147445_3_ >= -30000000 && p_147445_1_ < 30000000 && p_147445_3_ < 30000000) - { - Chunk chunk = this.chunkProvider.provideChunk(p_147445_1_ >> 4, p_147445_3_ >> 4); - - if (chunk != null && !chunk.isEmpty()) - { - Block block = this.getBlock(p_147445_1_, p_147445_2_, p_147445_3_); - return block.isNormalCube(this, p_147445_1_, p_147445_2_, p_147445_3_); - } - else - { - return p_147445_4_; - } - } - else - { - return p_147445_4_; - } - } - - /** - * Called on construction of the World class to setup the initial skylight values - */ - public void calculateInitialSkylight() - { - int i = this.calculateSkylightSubtracted(1.0F); - - if (i != this.skylightSubtracted) - { - this.skylightSubtracted = i; - } - } - - /** - * Set which types of mobs are allowed to spawn (peaceful vs hostile). - */ - public void setAllowedSpawnTypes(boolean par1, boolean par2) - { - provider.setAllowedSpawnTypes(par1, par2); - } - - /** - * Runs a single tick for the world - */ - public void tick() - { - this.updateWeather(); - } - - /** - * Called from World constructor to set rainingStrength and thunderingStrength - */ - private void calculateInitialWeather() - { - provider.calculateInitialWeather(); - } - - public void calculateInitialWeatherBody() - { - if (this.worldInfo.isRaining()) - { - this.rainingStrength = 1.0F; - - if (this.worldInfo.isThundering()) - { - this.thunderingStrength = 1.0F; - } - } - } - - /** - * Updates all weather states. - */ - protected void updateWeather() - { - provider.updateWeather(); - } - - public void updateWeatherBody() - { - if (!this.provider.hasNoSky) - { - if (!this.isRemote) - { - int i = this.worldInfo.getThunderTime(); - - if (i <= 0) - { - if (this.worldInfo.isThundering()) - { - this.worldInfo.setThunderTime(this.rand.nextInt(12000) + 3600); - } - else - { - this.worldInfo.setThunderTime(this.rand.nextInt(168000) + 12000); - } - } - else - { - --i; - this.worldInfo.setThunderTime(i); - - if (i <= 0) - { - this.worldInfo.setThundering(!this.worldInfo.isThundering()); - } - } - - this.prevThunderingStrength = this.thunderingStrength; - - if (this.worldInfo.isThundering()) - { - this.thunderingStrength = (float)((double)this.thunderingStrength + 0.01D); - } - else - { - this.thunderingStrength = (float)((double)this.thunderingStrength - 0.01D); - } - - this.thunderingStrength = MathHelper.clamp_float(this.thunderingStrength, 0.0F, 1.0F); - int j = this.worldInfo.getRainTime(); - - if (j <= 0) - { - if (this.worldInfo.isRaining()) - { - this.worldInfo.setRainTime(this.rand.nextInt(12000) + 12000); - } - else - { - this.worldInfo.setRainTime(this.rand.nextInt(168000) + 12000); - } - } - else - { - --j; - this.worldInfo.setRainTime(j); - - if (j <= 0) - { - this.worldInfo.setRaining(!this.worldInfo.isRaining()); - } - } - - this.prevRainingStrength = this.rainingStrength; - - if (this.worldInfo.isRaining()) - { - this.rainingStrength = (float)((double)this.rainingStrength + 0.01D); - } - else - { - this.rainingStrength = (float)((double)this.rainingStrength - 0.01D); - } - - this.rainingStrength = MathHelper.clamp_float(this.rainingStrength, 0.0F, 1.0F); - } - } - } - - protected void setActivePlayerChunksAndCheckLight() - { - this.activeChunkSet.clear(); - this.theProfiler.startSection("buildList"); - this.activeChunkSet.addAll(getPersistentChunks().keySet()); - int i; - EntityPlayer entityplayer; - int j; - int k; - - for (i = 0; i < this.playerEntities.size(); ++i) - { - entityplayer = (EntityPlayer)this.playerEntities.get(i); - j = MathHelper.floor_double(entityplayer.posX / 16.0D); - k = MathHelper.floor_double(entityplayer.posZ / 16.0D); - byte b0 = 7; - - for (int l = -b0; l <= b0; ++l) - { - for (int i1 = -b0; i1 <= b0; ++i1) - { - this.activeChunkSet.add(new ChunkCoordIntPair(l + j, i1 + k)); - } - } - } - - this.theProfiler.endSection(); - - if (this.ambientTickCountdown > 0) - { - --this.ambientTickCountdown; - } - - this.theProfiler.startSection("playerCheckLight"); - - if (!this.playerEntities.isEmpty()) - { - i = this.rand.nextInt(this.playerEntities.size()); - entityplayer = (EntityPlayer)this.playerEntities.get(i); - j = MathHelper.floor_double(entityplayer.posX) + this.rand.nextInt(11) - 5; - k = MathHelper.floor_double(entityplayer.posY) + this.rand.nextInt(11) - 5; - int j1 = MathHelper.floor_double(entityplayer.posZ) + this.rand.nextInt(11) - 5; - this.func_147451_t(j, k, j1); - } - - this.theProfiler.endSection(); - } - - protected void func_147467_a(int p_147467_1_, int p_147467_2_, Chunk p_147467_3_) - { - this.theProfiler.endStartSection("moodSound"); - - if (this.ambientTickCountdown == 0 && !this.isRemote) - { - this.updateLCG = this.updateLCG * 3 + 1013904223; - int k = this.updateLCG >> 2; - int l = k & 15; - int i1 = k >> 8 & 15; - int j1 = k >> 16 & 255; - Block block = p_147467_3_.getBlock(l, j1, i1); - l += p_147467_1_; - i1 += p_147467_2_; - - if (block.getMaterial() == Material.air && this.getFullBlockLightValue(l, j1, i1) <= this.rand.nextInt(8) && this.getSavedLightValue(EnumSkyBlock.Sky, l, j1, i1) <= 0) - { - EntityPlayer entityplayer = this.getClosestPlayer((double)l + 0.5D, (double)j1 + 0.5D, (double)i1 + 0.5D, 8.0D); - - if (entityplayer != null && entityplayer.getDistanceSq((double)l + 0.5D, (double)j1 + 0.5D, (double)i1 + 0.5D) > 4.0D) - { - this.playSoundEffect((double)l + 0.5D, (double)j1 + 0.5D, (double)i1 + 0.5D, "ambient.cave.cave", 0.7F, 0.8F + this.rand.nextFloat() * 0.2F); - this.ambientTickCountdown = this.rand.nextInt(12000) + 6000; - } - } - } - - this.theProfiler.endStartSection("checkLight"); - p_147467_3_.enqueueRelightChecks(); - } - - protected void func_147456_g() - { - this.setActivePlayerChunksAndCheckLight(); - } - - /** - * checks to see if a given block is both water and is cold enough to freeze - */ - public boolean isBlockFreezable(int par1, int par2, int par3) - { - return this.canBlockFreeze(par1, par2, par3, false); - } - - /** - * checks to see if a given block is both water and has at least one immediately adjacent non-water block - */ - public boolean isBlockFreezableNaturally(int par1, int par2, int par3) - { - return this.canBlockFreeze(par1, par2, par3, true); - } - - /** - * checks to see if a given block is both water, and cold enough to freeze - if the par4 boolean is set, this will - * only return true if there is a non-water block immediately adjacent to the specified block - */ - public boolean canBlockFreeze(int par1, int par2, int par3, boolean par4) - { - return provider.canBlockFreeze(par1, par2, par3, par4); - } - - public boolean canBlockFreezeBody(int par1, int par2, int par3, boolean par4) - { - BiomeGenBase biomegenbase = this.getBiomeGenForCoords(par1, par3); - float f = biomegenbase.getFloatTemperature(par1, par2, par3); - - if (f > 0.15F) - { - return false; - } - else - { - if (par2 >= 0 && par2 < 256 && this.getSavedLightValue(EnumSkyBlock.Block, par1, par2, par3) < 10) - { - Block block = this.getBlock(par1, par2, par3); - - if ((block == Blocks.water || block == Blocks.flowing_water) && this.getBlockMetadata(par1, par2, par3) == 0) - { - if (!par4) - { - return true; - } - - boolean flag1 = true; - - if (flag1 && this.getBlock(par1 - 1, par2, par3).getMaterial() != Material.water) - { - flag1 = false; - } - - if (flag1 && this.getBlock(par1 + 1, par2, par3).getMaterial() != Material.water) - { - flag1 = false; - } - - if (flag1 && this.getBlock(par1, par2, par3 - 1).getMaterial() != Material.water) - { - flag1 = false; - } - - if (flag1 && this.getBlock(par1, par2, par3 + 1).getMaterial() != Material.water) - { - flag1 = false; - } - - if (!flag1) - { - return true; - } - } - } - - return false; - } - } - - public boolean func_147478_e(int p_147478_1_, int p_147478_2_, int p_147478_3_, boolean p_147478_4_) - { - return provider.canSnowAt(p_147478_1_, p_147478_2_, p_147478_3_, p_147478_4_); - } - - public boolean canSnowAtBody(int p_147478_1_, int p_147478_2_, int p_147478_3_, boolean p_147478_4_) - { - BiomeGenBase biomegenbase = this.getBiomeGenForCoords(p_147478_1_, p_147478_3_); - float f = biomegenbase.getFloatTemperature(p_147478_1_, p_147478_2_, p_147478_3_); - - if (f > 0.15F) - { - return false; - } - else if (!p_147478_4_) - { - return true; - } - else - { - if (p_147478_2_ >= 0 && p_147478_2_ < 256 && this.getSavedLightValue(EnumSkyBlock.Block, p_147478_1_, p_147478_2_, p_147478_3_) < 10) - { - Block block = this.getBlock(p_147478_1_, p_147478_2_, p_147478_3_); - - if (block.getMaterial() == Material.air && Blocks.snow_layer.canPlaceBlockAt(this, p_147478_1_, p_147478_2_, p_147478_3_)) - { - return true; - } - } - - return false; - } - } - - public boolean func_147451_t(int p_147451_1_, int p_147451_2_, int p_147451_3_) - { - boolean flag = false; - - if (!this.provider.hasNoSky) - { - flag |= this.updateLightByType(EnumSkyBlock.Sky, p_147451_1_, p_147451_2_, p_147451_3_); - } - - flag |= this.updateLightByType(EnumSkyBlock.Block, p_147451_1_, p_147451_2_, p_147451_3_); - return flag; - } - - private int computeLightValue(int par1, int par2, int par3, EnumSkyBlock par4EnumSkyBlock) - { - if (par4EnumSkyBlock == EnumSkyBlock.Sky && this.canBlockSeeTheSky(par1, par2, par3)) - { - return 15; - } - else - { - Block block = this.getBlock(par1, par2, par3); - int blockLight = block.getLightValue(this, par1, par2, par3); - int l = par4EnumSkyBlock == EnumSkyBlock.Sky ? 0 : blockLight; - int i1 = block.getLightOpacity(this, par1, par2, par3); - - if (i1 >= 15 && blockLight > 0) - { - i1 = 1; - } - - if (i1 < 1) - { - i1 = 1; - } - - if (i1 >= 15) - { - return 0; - } - else if (l >= 14) - { - return l; - } - else - { - for (int j1 = 0; j1 < 6; ++j1) - { - int k1 = par1 + Facing.offsetsXForSide[j1]; - int l1 = par2 + Facing.offsetsYForSide[j1]; - int i2 = par3 + Facing.offsetsZForSide[j1]; - int j2 = this.getSavedLightValue(par4EnumSkyBlock, k1, l1, i2) - i1; - - if (j2 > l) - { - l = j2; - } - - if (l >= 14) - { - return l; - } - } - - return l; - } - } - } - - public boolean updateLightByType(EnumSkyBlock p_147463_1_, int p_147463_2_, int p_147463_3_, int p_147463_4_) - { - if (!this.doChunksNearChunkExist(p_147463_2_, p_147463_3_, p_147463_4_, 17)) - { - return false; - } - else - { - int l = 0; - int i1 = 0; - this.theProfiler.startSection("getBrightness"); - int j1 = this.getSavedLightValue(p_147463_1_, p_147463_2_, p_147463_3_, p_147463_4_); - int k1 = this.computeLightValue(p_147463_2_, p_147463_3_, p_147463_4_, p_147463_1_); - int l1; - int i2; - int j2; - int k2; - int l2; - int i3; - int j3; - int k3; - int l3; - - if (k1 > j1) - { - this.lightUpdateBlockList[i1++] = 133152; - } - else if (k1 < j1) - { - this.lightUpdateBlockList[i1++] = 133152 | j1 << 18; - - while (l < i1) - { - l1 = this.lightUpdateBlockList[l++]; - i2 = (l1 & 63) - 32 + p_147463_2_; - j2 = (l1 >> 6 & 63) - 32 + p_147463_3_; - k2 = (l1 >> 12 & 63) - 32 + p_147463_4_; - l2 = l1 >> 18 & 15; - i3 = this.getSavedLightValue(p_147463_1_, i2, j2, k2); - - if (i3 == l2) - { - this.setLightValue(p_147463_1_, i2, j2, k2, 0); - - if (l2 > 0) - { - j3 = MathHelper.abs_int(i2 - p_147463_2_); - k3 = MathHelper.abs_int(j2 - p_147463_3_); - l3 = MathHelper.abs_int(k2 - p_147463_4_); - - if (j3 + k3 + l3 < 17) - { - for (int i4 = 0; i4 < 6; ++i4) - { - int j4 = i2 + Facing.offsetsXForSide[i4]; - int k4 = j2 + Facing.offsetsYForSide[i4]; - int l4 = k2 + Facing.offsetsZForSide[i4]; - int i5 = Math.max(1, this.getBlock(j4, k4, l4).getLightOpacity(this, j4, k4, l4)); - i3 = this.getSavedLightValue(p_147463_1_, j4, k4, l4); - - if (i3 == l2 - i5 && i1 < this.lightUpdateBlockList.length) - { - this.lightUpdateBlockList[i1++] = j4 - p_147463_2_ + 32 | k4 - p_147463_3_ + 32 << 6 | l4 - p_147463_4_ + 32 << 12 | l2 - i5 << 18; - } - } - } - } - } - } - - l = 0; - } - - this.theProfiler.endSection(); - this.theProfiler.startSection("checkedPosition < toCheckCount"); - - while (l < i1) - { - l1 = this.lightUpdateBlockList[l++]; - i2 = (l1 & 63) - 32 + p_147463_2_; - j2 = (l1 >> 6 & 63) - 32 + p_147463_3_; - k2 = (l1 >> 12 & 63) - 32 + p_147463_4_; - l2 = this.getSavedLightValue(p_147463_1_, i2, j2, k2); - i3 = this.computeLightValue(i2, j2, k2, p_147463_1_); - - if (i3 != l2) - { - this.setLightValue(p_147463_1_, i2, j2, k2, i3); - - if (i3 > l2) - { - j3 = Math.abs(i2 - p_147463_2_); - k3 = Math.abs(j2 - p_147463_3_); - l3 = Math.abs(k2 - p_147463_4_); - boolean flag = i1 < this.lightUpdateBlockList.length - 6; - - if (j3 + k3 + l3 < 17 && flag) - { - if (this.getSavedLightValue(p_147463_1_, i2 - 1, j2, k2) < i3) - { - this.lightUpdateBlockList[i1++] = i2 - 1 - p_147463_2_ + 32 + (j2 - p_147463_3_ + 32 << 6) + (k2 - p_147463_4_ + 32 << 12); - } - - if (this.getSavedLightValue(p_147463_1_, i2 + 1, j2, k2) < i3) - { - this.lightUpdateBlockList[i1++] = i2 + 1 - p_147463_2_ + 32 + (j2 - p_147463_3_ + 32 << 6) + (k2 - p_147463_4_ + 32 << 12); - } - - if (this.getSavedLightValue(p_147463_1_, i2, j2 - 1, k2) < i3) - { - this.lightUpdateBlockList[i1++] = i2 - p_147463_2_ + 32 + (j2 - 1 - p_147463_3_ + 32 << 6) + (k2 - p_147463_4_ + 32 << 12); - } - - if (this.getSavedLightValue(p_147463_1_, i2, j2 + 1, k2) < i3) - { - this.lightUpdateBlockList[i1++] = i2 - p_147463_2_ + 32 + (j2 + 1 - p_147463_3_ + 32 << 6) + (k2 - p_147463_4_ + 32 << 12); - } - - if (this.getSavedLightValue(p_147463_1_, i2, j2, k2 - 1) < i3) - { - this.lightUpdateBlockList[i1++] = i2 - p_147463_2_ + 32 + (j2 - p_147463_3_ + 32 << 6) + (k2 - 1 - p_147463_4_ + 32 << 12); - } - - if (this.getSavedLightValue(p_147463_1_, i2, j2, k2 + 1) < i3) - { - this.lightUpdateBlockList[i1++] = i2 - p_147463_2_ + 32 + (j2 - p_147463_3_ + 32 << 6) + (k2 + 1 - p_147463_4_ + 32 << 12); - } - } - } - } - } - - this.theProfiler.endSection(); - return true; - } - } - - /** - * Runs through the list of updates to run and ticks them - */ - public boolean tickUpdates(boolean par1) - { - return false; - } - - public List getPendingBlockUpdates(Chunk par1Chunk, boolean par2) - { - return null; - } - - /** - * Will get all entities within the specified AABB excluding the one passed into it. Args: entityToExclude, aabb - */ - public List getEntitiesWithinAABBExcludingEntity(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) - { - return this.getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB, (IEntitySelector)null); - } - - public List getEntitiesWithinAABBExcludingEntity(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB, IEntitySelector par3IEntitySelector) - { - ArrayList arraylist = new ArrayList(); - int i = MathHelper.floor_double((par2AxisAlignedBB.minX - MAX_ENTITY_RADIUS) / 16.0D); - int j = MathHelper.floor_double((par2AxisAlignedBB.maxX + MAX_ENTITY_RADIUS) / 16.0D); - int k = MathHelper.floor_double((par2AxisAlignedBB.minZ - MAX_ENTITY_RADIUS) / 16.0D); - int l = MathHelper.floor_double((par2AxisAlignedBB.maxZ + MAX_ENTITY_RADIUS) / 16.0D); - - for (int i1 = i; i1 <= j; ++i1) - { - for (int j1 = k; j1 <= l; ++j1) - { - if (this.chunkExists(i1, j1)) - { - this.getChunkFromChunkCoords(i1, j1).getEntitiesWithinAABBForEntity(par1Entity, par2AxisAlignedBB, arraylist, par3IEntitySelector); - } - } - } - - return arraylist; - } - - /** - * Returns all entities of the specified class type which intersect with the AABB. Args: entityClass, aabb - */ - public List getEntitiesWithinAABB(Class par1Class, AxisAlignedBB par2AxisAlignedBB) - { - return this.selectEntitiesWithinAABB(par1Class, par2AxisAlignedBB, (IEntitySelector)null); - } - - public List selectEntitiesWithinAABB(Class par1Class, AxisAlignedBB par2AxisAlignedBB, IEntitySelector par3IEntitySelector) - { - int i = MathHelper.floor_double((par2AxisAlignedBB.minX - MAX_ENTITY_RADIUS) / 16.0D); - int j = MathHelper.floor_double((par2AxisAlignedBB.maxX + MAX_ENTITY_RADIUS) / 16.0D); - int k = MathHelper.floor_double((par2AxisAlignedBB.minZ - MAX_ENTITY_RADIUS) / 16.0D); - int l = MathHelper.floor_double((par2AxisAlignedBB.maxZ + MAX_ENTITY_RADIUS) / 16.0D); - ArrayList arraylist = new ArrayList(); - - for (int i1 = i; i1 <= j; ++i1) - { - for (int j1 = k; j1 <= l; ++j1) - { - if (this.chunkExists(i1, j1)) - { - this.getChunkFromChunkCoords(i1, j1).getEntitiesOfTypeWithinAAAB(par1Class, par2AxisAlignedBB, arraylist, par3IEntitySelector); - } - } - } - - return arraylist; - } - - public Entity findNearestEntityWithinAABB(Class par1Class, AxisAlignedBB par2AxisAlignedBB, Entity par3Entity) - { - List list = this.getEntitiesWithinAABB(par1Class, par2AxisAlignedBB); - Entity entity1 = null; - double d0 = Double.MAX_VALUE; - - for (int i = 0; i < list.size(); ++i) - { - Entity entity2 = (Entity)list.get(i); - - if (entity2 != par3Entity) - { - double d1 = par3Entity.getDistanceSqToEntity(entity2); - - if (d1 <= d0) - { - entity1 = entity2; - d0 = d1; - } - } - } - - return entity1; - } - - /** - * Returns the Entity with the given ID, or null if it doesn't exist in this World. - */ - public abstract Entity getEntityByID(int var1); - - /** - * Accessor for world Loaded Entity List - */ - @SideOnly(Side.CLIENT) - public List getLoadedEntityList() - { - return this.loadedEntityList; - } - - /** - * Args: X, Y, Z, tile entity Marks the chunk the tile entity is in as modified. This is essential as chunks that - * are not marked as modified may be rolled back when exiting the game. - */ - public void markTileEntityChunkModified(int p_147476_1_, int p_147476_2_, int p_147476_3_, TileEntity p_147476_4_) - { - if (this.blockExists(p_147476_1_, p_147476_2_, p_147476_3_)) - { - this.getChunkFromBlockCoords(p_147476_1_, p_147476_3_).setChunkModified(); - } - } - - /** - * Counts how many entities of an entity class exist in the world. Args: entityClass - */ - public int countEntities(Class par1Class) - { - int i = 0; - - for (int j = 0; j < this.loadedEntityList.size(); ++j) - { - Entity entity = (Entity)this.loadedEntityList.get(j); - - if ((!(entity instanceof EntityLiving) || !((EntityLiving)entity).isNoDespawnRequired()) && par1Class.isAssignableFrom(entity.getClass())) - { - ++i; - } - } - - return i; - } - - /** - * adds entities to the loaded entities list, and loads thier skins. - */ - public void addLoadedEntities(List par1List) - { - for (int i = 0; i < par1List.size(); ++i) - { - Entity entity = (Entity)par1List.get(i); - if (!MinecraftForge.EVENT_BUS.post(new EntityJoinWorldEvent(entity, this))) - { - loadedEntityList.add(entity); - this.onEntityAdded(entity); - } - } - } - - /** - * Adds a list of entities to be unloaded on the next pass of World.updateEntities() - */ - public void unloadEntities(List par1List) - { - this.unloadedEntityList.addAll(par1List); - } - - /** - * Returns true if the given Entity can be placed on the given side of the given block position. - */ - public boolean canPlaceEntityOnSide(Block p_147472_1_, int p_147472_2_, int p_147472_3_, int p_147472_4_, boolean p_147472_5_, int p_147472_6_, Entity p_147472_7_, ItemStack p_147472_8_) - { - Block block1 = this.getBlock(p_147472_2_, p_147472_3_, p_147472_4_); - AxisAlignedBB axisalignedbb = p_147472_5_ ? null : p_147472_1_.getCollisionBoundingBoxFromPool(this, p_147472_2_, p_147472_3_, p_147472_4_); - return axisalignedbb != null && !this.checkNoEntityCollision(axisalignedbb, p_147472_7_) ? false : (block1.getMaterial() == Material.circuits && p_147472_1_ == Blocks.anvil ? true : block1.isReplaceable(this, p_147472_2_, p_147472_3_, p_147472_4_) && p_147472_1_.canReplace(this, p_147472_2_, p_147472_3_, p_147472_4_, p_147472_6_, p_147472_8_)); - } - - public PathEntity getPathEntityToEntity(Entity par1Entity, Entity par2Entity, float par3, boolean par4, boolean par5, boolean par6, boolean par7) - { - this.theProfiler.startSection("pathfind"); - int i = MathHelper.floor_double(par1Entity.posX); - int j = MathHelper.floor_double(par1Entity.posY + 1.0D); - int k = MathHelper.floor_double(par1Entity.posZ); - int l = (int)(par3 + 16.0F); - int i1 = i - l; - int j1 = j - l; - int k1 = k - l; - int l1 = i + l; - int i2 = j + l; - int j2 = k + l; - ChunkCache chunkcache = new ChunkCache(this, i1, j1, k1, l1, i2, j2, 0); - PathEntity pathentity = (new PathFinder(chunkcache, par4, par5, par6, par7)).createEntityPathTo(par1Entity, par2Entity, par3); - this.theProfiler.endSection(); - return pathentity; - } - - public PathEntity getEntityPathToXYZ(Entity par1Entity, int par2, int par3, int par4, float par5, boolean par6, boolean par7, boolean par8, boolean par9) - { - this.theProfiler.startSection("pathfind"); - int l = MathHelper.floor_double(par1Entity.posX); - int i1 = MathHelper.floor_double(par1Entity.posY); - int j1 = MathHelper.floor_double(par1Entity.posZ); - int k1 = (int)(par5 + 8.0F); - int l1 = l - k1; - int i2 = i1 - k1; - int j2 = j1 - k1; - int k2 = l + k1; - int l2 = i1 + k1; - int i3 = j1 + k1; - ChunkCache chunkcache = new ChunkCache(this, l1, i2, j2, k2, l2, i3, 0); - PathEntity pathentity = (new PathFinder(chunkcache, par6, par7, par8, par9)).createEntityPathTo(par1Entity, par2, par3, par4, par5); - this.theProfiler.endSection(); - return pathentity; - } - - /** - * Is this block powering in the specified direction Args: x, y, z, direction - */ - public int isBlockProvidingPowerTo(int par1, int par2, int par3, int par4) - { - return this.getBlock(par1, par2, par3).isProvidingStrongPower(this, par1, par2, par3, par4); - } - - /** - * Returns the highest redstone signal strength powering the given block. Args: X, Y, Z. - */ - public int getBlockPowerInput(int par1, int par2, int par3) - { - byte b0 = 0; - int l = Math.max(b0, this.isBlockProvidingPowerTo(par1, par2 - 1, par3, 0)); - - if (l >= 15) - { - return l; - } - else - { - l = Math.max(l, this.isBlockProvidingPowerTo(par1, par2 + 1, par3, 1)); - - if (l >= 15) - { - return l; - } - else - { - l = Math.max(l, this.isBlockProvidingPowerTo(par1, par2, par3 - 1, 2)); - - if (l >= 15) - { - return l; - } - else - { - l = Math.max(l, this.isBlockProvidingPowerTo(par1, par2, par3 + 1, 3)); - - if (l >= 15) - { - return l; - } - else - { - l = Math.max(l, this.isBlockProvidingPowerTo(par1 - 1, par2, par3, 4)); - - if (l >= 15) - { - return l; - } - else - { - l = Math.max(l, this.isBlockProvidingPowerTo(par1 + 1, par2, par3, 5)); - return l >= 15 ? l : l; - } - } - } - } - } - } - - /** - * Returns the indirect signal strength being outputted by the given block in the *opposite* of the given direction. - * Args: X, Y, Z, direction - */ - public boolean getIndirectPowerOutput(int par1, int par2, int par3, int par4) - { - return this.getIndirectPowerLevelTo(par1, par2, par3, par4) > 0; - } - - /** - * Gets the power level from a certain block face. Args: x, y, z, direction - */ - public int getIndirectPowerLevelTo(int par1, int par2, int par3, int par4) - { - Block block = this.getBlock(par1, par2, par3); - return block.shouldCheckWeakPower(this, par1, par2, par3, par4) ? this.getBlockPowerInput(par1, par2, par3) : block.isProvidingWeakPower(this, par1, par2, par3, par4); - } - - /** - * Used to see if one of the blocks next to you or your block is getting power from a neighboring block. Used by - * items like TNT or Doors so they don't have redstone going straight into them. Args: x, y, z - */ - public boolean isBlockIndirectlyGettingPowered(int par1, int par2, int par3) - { - return this.getIndirectPowerLevelTo(par1, par2 - 1, par3, 0) > 0 ? true : (this.getIndirectPowerLevelTo(par1, par2 + 1, par3, 1) > 0 ? true : (this.getIndirectPowerLevelTo(par1, par2, par3 - 1, 2) > 0 ? true : (this.getIndirectPowerLevelTo(par1, par2, par3 + 1, 3) > 0 ? true : (this.getIndirectPowerLevelTo(par1 - 1, par2, par3, 4) > 0 ? true : this.getIndirectPowerLevelTo(par1 + 1, par2, par3, 5) > 0)))); - } - - public int getStrongestIndirectPower(int par1, int par2, int par3) - { - int l = 0; - - for (int i1 = 0; i1 < 6; ++i1) - { - int j1 = this.getIndirectPowerLevelTo(par1 + Facing.offsetsXForSide[i1], par2 + Facing.offsetsYForSide[i1], par3 + Facing.offsetsZForSide[i1], i1); - - if (j1 >= 15) - { - return 15; - } - - if (j1 > l) - { - l = j1; - } - } - - return l; - } - - /** - * Gets the closest player to the entity within the specified distance (if distance is less than 0 then ignored). - * Args: entity, dist - */ - public EntityPlayer getClosestPlayerToEntity(Entity par1Entity, double par2) - { - return this.getClosestPlayer(par1Entity.posX, par1Entity.posY, par1Entity.posZ, par2); - } - - /** - * Gets the closest player to the point within the specified distance (distance can be set to less than 0 to not - * limit the distance). Args: x, y, z, dist - */ - public EntityPlayer getClosestPlayer(double par1, double par3, double par5, double par7) - { - double d4 = -1.0D; - EntityPlayer entityplayer = null; - - for (int i = 0; i < this.playerEntities.size(); ++i) - { - EntityPlayer entityplayer1 = (EntityPlayer)this.playerEntities.get(i); - double d5 = entityplayer1.getDistanceSq(par1, par3, par5); - - if ((par7 < 0.0D || d5 < par7 * par7) && (d4 == -1.0D || d5 < d4)) - { - d4 = d5; - entityplayer = entityplayer1; - } - } - - return entityplayer; - } - - /** - * Returns the closest vulnerable player to this entity within the given radius, or null if none is found - */ - public EntityPlayer getClosestVulnerablePlayerToEntity(Entity par1Entity, double par2) - { - return this.getClosestVulnerablePlayer(par1Entity.posX, par1Entity.posY, par1Entity.posZ, par2); - } - - /** - * Returns the closest vulnerable player within the given radius, or null if none is found. - */ - public EntityPlayer getClosestVulnerablePlayer(double par1, double par3, double par5, double par7) - { - double d4 = -1.0D; - EntityPlayer entityplayer = null; - - for (int i = 0; i < this.playerEntities.size(); ++i) - { - EntityPlayer entityplayer1 = (EntityPlayer)this.playerEntities.get(i); - - if (!entityplayer1.capabilities.disableDamage && entityplayer1.isEntityAlive()) - { - double d5 = entityplayer1.getDistanceSq(par1, par3, par5); - double d6 = par7; - - if (entityplayer1.isSneaking()) - { - d6 = par7 * 0.800000011920929D; - } - - if (entityplayer1.isInvisible()) - { - float f = entityplayer1.getArmorVisibility(); - - if (f < 0.1F) - { - f = 0.1F; - } - - d6 *= (double)(0.7F * f); - } - - if ((par7 < 0.0D || d5 < d6 * d6) && (d4 == -1.0D || d5 < d4)) - { - d4 = d5; - entityplayer = entityplayer1; - } - } - } - - return entityplayer; - } - - /** - * Find a player by name in this world. - */ - public EntityPlayer getPlayerEntityByName(String par1Str) - { - for (int i = 0; i < this.playerEntities.size(); ++i) - { - if (par1Str.equals(((EntityPlayer)this.playerEntities.get(i)).getCommandSenderName())) - { - return (EntityPlayer)this.playerEntities.get(i); - } - } - - return null; - } - - /** - * If on MP, sends a quitting packet. - */ - @SideOnly(Side.CLIENT) - public void sendQuittingDisconnectingPacket() {} - - /** - * Checks whether the session lock file was modified by another process - */ - public void checkSessionLock() throws MinecraftException - { - this.saveHandler.checkSessionLock(); - } - - @SideOnly(Side.CLIENT) - public void func_82738_a(long par1) - { - this.worldInfo.incrementTotalWorldTime(par1); - } - - /** - * Retrieve the world seed from level.dat - */ - public long getSeed() - { - return provider.getSeed(); - } - - public long getTotalWorldTime() - { - return this.worldInfo.getWorldTotalTime(); - } - - public long getWorldTime() - { - return provider.getWorldTime(); - } - - /** - * Sets the world time. - */ - public void setWorldTime(long par1) - { - provider.setWorldTime(par1); - } - - /** - * Returns the coordinates of the spawn point - */ - public ChunkCoordinates getSpawnPoint() - { - return provider.getSpawnPoint(); - } - - public void setSpawnLocation(int par1, int par2, int par3) - { - provider.setSpawnPoint(par1, par2, par3); - } - - /** - * spwans an entity and loads surrounding chunks - */ - @SideOnly(Side.CLIENT) - public void joinEntityInSurroundings(Entity par1Entity) - { - int i = MathHelper.floor_double(par1Entity.posX / 16.0D); - int j = MathHelper.floor_double(par1Entity.posZ / 16.0D); - byte b0 = 2; - - for (int k = i - b0; k <= i + b0; ++k) - { - for (int l = j - b0; l <= j + b0; ++l) - { - this.getChunkFromChunkCoords(k, l); - } - } - - if (!this.loadedEntityList.contains(par1Entity)) - { - if (!MinecraftForge.EVENT_BUS.post(new EntityJoinWorldEvent(par1Entity, this))) - { - this.loadedEntityList.add(par1Entity); - } - } - } - - /** - * Called when checking if a certain block can be mined or not. The 'spawn safe zone' check is located here. - */ - public boolean canMineBlock(EntityPlayer par1EntityPlayer, int par2, int par3, int par4) - { - return provider.canMineBlock(par1EntityPlayer, par2, par3, par4); - } - - public boolean canMineBlockBody(EntityPlayer par1EntityPlayer, int par2, int par3, int par4) - { - return true; - } - - /** - * sends a Packet 38 (Entity Status) to all tracked players of that entity - */ - public void setEntityState(Entity par1Entity, byte par2) {} - - /** - * gets the IChunkProvider this world uses. - */ - public IChunkProvider getChunkProvider() - { - return this.chunkProvider; - } - - /** - * Adds a block event with the given Args to the blockEventCache. During the next tick(), the block specified will - * have its onBlockEvent handler called with the given parameters. Args: X,Y,Z, Block, EventID, EventParameter - */ - public void addBlockEvent(int p_147452_1_, int p_147452_2_, int p_147452_3_, Block p_147452_4_, int p_147452_5_, int p_147452_6_) - { - p_147452_4_.onBlockEventReceived(this, p_147452_1_, p_147452_2_, p_147452_3_, p_147452_5_, p_147452_6_); - } - - /** - * Returns this world's current save handler - */ - public ISaveHandler getSaveHandler() - { - return this.saveHandler; - } - - /** - * Gets the World's WorldInfo instance - */ - public WorldInfo getWorldInfo() - { - return this.worldInfo; - } - - /** - * Gets the GameRules instance. - */ - public GameRules getGameRules() - { - return this.worldInfo.getGameRulesInstance(); - } - - /** - * Updates the flag that indicates whether or not all players in the world are sleeping. - */ - public void updateAllPlayersSleepingFlag() {} - - public float getWeightedThunderStrength(float par1) - { - return (this.prevThunderingStrength + (this.thunderingStrength - this.prevThunderingStrength) * par1) * this.getRainStrength(par1); - } - - /** - * Sets the strength of the thunder. - */ - @SideOnly(Side.CLIENT) - public void setThunderStrength(float p_147442_1_) - { - this.prevThunderingStrength = p_147442_1_; - this.thunderingStrength = p_147442_1_; - } - - /** - * Not sure about this actually. Reverting this one myself. - */ - public float getRainStrength(float par1) - { - return this.prevRainingStrength + (this.rainingStrength - this.prevRainingStrength) * par1; - } - - /** - * Sets the strength of the rain. - */ - @SideOnly(Side.CLIENT) - public void setRainStrength(float par1) - { - this.prevRainingStrength = par1; - this.rainingStrength = par1; - } - - /** - * Returns true if the current thunder strength (weighted with the rain strength) is greater than 0.9 - */ - public boolean isThundering() - { - return (double)this.getWeightedThunderStrength(1.0F) > 0.9D; - } - - /** - * Returns true if the current rain strength is greater than 0.2 - */ - public boolean isRaining() - { - return (double)this.getRainStrength(1.0F) > 0.2D; - } - - public boolean canLightningStrikeAt(int par1, int par2, int par3) - { - if (!this.isRaining()) - { - return false; - } - else if (!this.canBlockSeeTheSky(par1, par2, par3)) - { - return false; - } - else if (this.getPrecipitationHeight(par1, par3) > par2) - { - return false; - } - else - { - BiomeGenBase biomegenbase = this.getBiomeGenForCoords(par1, par3); - return biomegenbase.getEnableSnow() ? false : (this.func_147478_e(par1, par2, par3, false) ? false : biomegenbase.canSpawnLightningBolt()); - } - } - - /** - * Checks to see if the biome rainfall values for a given x,y,z coordinate set are extremely high - */ - public boolean isBlockHighHumidity(int par1, int par2, int par3) - { - return provider.isBlockHighHumidity(par1, par2, par3); - } - - /** - * Assigns the given String id to the given MapDataBase using the MapStorage, removing any existing ones of the same - * id. - */ - public void setItemData(String par1Str, WorldSavedData par2WorldSavedData) - { - this.mapStorage.setData(par1Str, par2WorldSavedData); - } - - /** - * Loads an existing MapDataBase corresponding to the given String id from disk using the MapStorage, instantiating - * the given Class, or returns null if none such file exists. args: Class to instantiate, String dataid - */ - public WorldSavedData loadItemData(Class par1Class, String par2Str) - { - return this.mapStorage.loadData(par1Class, par2Str); - } - - /** - * Returns an unique new data id from the MapStorage for the given prefix and saves the idCounts map to the - * 'idcounts' file. - */ - public int getUniqueDataId(String par1Str) - { - return this.mapStorage.getUniqueDataId(par1Str); - } - - public void playBroadcastSound(int par1, int par2, int par3, int par4, int par5) - { - for (int j1 = 0; j1 < this.worldAccesses.size(); ++j1) - { - ((IWorldAccess)this.worldAccesses.get(j1)).broadcastSound(par1, par2, par3, par4, par5); - } - } - - /** - * See description for func_72706_a. - */ - public void playAuxSFX(int par1, int par2, int par3, int par4, int par5) - { - this.playAuxSFXAtEntity((EntityPlayer)null, par1, par2, par3, par4, par5); - } - - /** - * See description for playAuxSFX. - */ - public void playAuxSFXAtEntity(EntityPlayer par1EntityPlayer, int par2, int par3, int par4, int par5, int par6) - { - try - { - for (int j1 = 0; j1 < this.worldAccesses.size(); ++j1) - { - ((IWorldAccess)this.worldAccesses.get(j1)).playAuxSFX(par1EntityPlayer, par2, par3, par4, par5, par6); - } - } - catch (Throwable throwable) - { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Playing level event"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Level event being played"); - crashreportcategory.addCrashSection("Block coordinates", CrashReportCategory.getLocationInfo(par3, par4, par5)); - crashreportcategory.addCrashSection("Event source", par1EntityPlayer); - crashreportcategory.addCrashSection("Event type", Integer.valueOf(par2)); - crashreportcategory.addCrashSection("Event data", Integer.valueOf(par6)); - throw new ReportedException(crashreport); - } - } - - /** - * Returns current world height. - */ - public int getHeight() - { - return provider.getHeight(); - } - - /** - * Returns current world height. - */ - public int getActualHeight() - { - return provider.getActualHeight(); - } - - /** - * puts the World Random seed to a specific state dependant on the inputs - */ - public Random setRandomSeed(int par1, int par2, int par3) - { - long l = (long)par1 * 341873128712L + (long)par2 * 132897987541L + this.getWorldInfo().getSeed() + (long)par3; - this.rand.setSeed(l); - return this.rand; - } - - /** - * Returns the location of the closest structure of the specified type. If not found returns null. - */ - public ChunkPosition findClosestStructure(String p_147440_1_, int p_147440_2_, int p_147440_3_, int p_147440_4_) - { - return this.getChunkProvider().func_147416_a(this, p_147440_1_, p_147440_2_, p_147440_3_, p_147440_4_); - } - - /** - * set by !chunk.getAreLevelsEmpty - */ - @SideOnly(Side.CLIENT) - public boolean extendedLevelsInChunkCache() - { - return false; - } - - /** - * Returns horizon height for use in rendering the sky. - */ - @SideOnly(Side.CLIENT) - public double getHorizon() - { - return provider.getHorizon(); - } - - /** - * Adds some basic stats of the world to the given crash report. - */ - public CrashReportCategory addWorldInfoToCrashReport(CrashReport par1CrashReport) - { - CrashReportCategory crashreportcategory = par1CrashReport.makeCategoryDepth("Affected level", 1); - crashreportcategory.addCrashSection("Level name", this.worldInfo == null ? "????" : this.worldInfo.getWorldName()); - crashreportcategory.addCrashSectionCallable("All players", new Callable() - { - private static final String __OBFID = "CL_00000143"; - public String call() - { - return World.this.playerEntities.size() + " total; " + World.this.playerEntities.toString(); - } - }); - crashreportcategory.addCrashSectionCallable("Chunk stats", new Callable() - { - private static final String __OBFID = "CL_00000144"; - public String call() - { - return World.this.chunkProvider.makeString(); - } - }); - - try - { - this.worldInfo.addToCrashReport(crashreportcategory); - } - catch (Throwable throwable) - { - crashreportcategory.addCrashSectionThrowable("Level Data Unobtainable", throwable); - } - - return crashreportcategory; - } - - /** - * Starts (or continues) destroying a block with given ID at the given coordinates for the given partially destroyed - * value - */ - public void destroyBlockInWorldPartially(int p_147443_1_, int p_147443_2_, int p_147443_3_, int p_147443_4_, int p_147443_5_) - { - for (int j1 = 0; j1 < this.worldAccesses.size(); ++j1) - { - IWorldAccess iworldaccess = (IWorldAccess)this.worldAccesses.get(j1); - iworldaccess.destroyBlockPartially(p_147443_1_, p_147443_2_, p_147443_3_, p_147443_4_, p_147443_5_); - } - } - - /** - * Return the Vec3Pool object for this world. - */ - public Vec3Pool getWorldVec3Pool() - { - return this.vecPool; - } - - /** - * returns a calendar object containing the current date - */ - public Calendar getCurrentDate() - { - if (this.getTotalWorldTime() % 600L == 0L) - { - this.theCalendar.setTimeInMillis(MinecraftServer.getSystemTimeMillis()); - } - - return this.theCalendar; - } - - @SideOnly(Side.CLIENT) - public void makeFireworks(double par1, double par3, double par5, double par7, double par9, double par11, NBTTagCompound par13NBTTagCompound) {} - - public Scoreboard getScoreboard() - { - return this.worldScoreboard; - } - - public void func_147453_f(int p_147453_1_, int p_147453_2_, int p_147453_3_, Block p_147453_4_) - { - for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) - { - int i1 = p_147453_1_ + dir.offsetX; - int y = p_147453_2_ + dir.offsetY; - int j1 = p_147453_3_ + dir.offsetZ; - Block block1 = this.getBlock(i1, y, j1); - - block1.onNeighborChange(this, i1, y, j1, p_147453_1_, p_147453_2_, p_147453_3_); - if (block1.isNormalCube(this, i1, p_147453_2_, j1)) - { - i1 += dir.offsetX; - y += dir.offsetY; - j1 += dir.offsetZ; - Block block2 = this.getBlock(i1, y, j1); - - if (block2.getWeakChanges(this, i1, y, j1)) - { - block2.onNeighborChange(this, i1, y, j1, p_147453_1_, p_147453_2_, p_147453_3_); - } - } - } - } - - public float func_147462_b(double p_147462_1_, double p_147462_3_, double p_147462_5_) - { - return this.func_147473_B(MathHelper.floor_double(p_147462_1_), MathHelper.floor_double(p_147462_3_), MathHelper.floor_double(p_147462_5_)); - } - - public float func_147473_B(int p_147473_1_, int p_147473_2_, int p_147473_3_) - { - float f = 0.0F; - boolean flag = this.difficultySetting == EnumDifficulty.HARD; - - if (this.blockExists(p_147473_1_, p_147473_2_, p_147473_3_)) - { - float f1 = this.getCurrentMoonPhaseFactor(); - f += MathHelper.clamp_float((float)this.getChunkFromBlockCoords(p_147473_1_, p_147473_3_).inhabitedTime / 3600000.0F, 0.0F, 1.0F) * (flag ? 1.0F : 0.75F); - f += f1 * 0.25F; - } - - if (this.difficultySetting == EnumDifficulty.EASY || this.difficultySetting == EnumDifficulty.PEACEFUL) - { - f *= (float)this.difficultySetting.getDifficultyId() / 2.0F; - } - - return MathHelper.clamp_float(f, 0.0F, flag ? 1.5F : 1.0F); - } - - public void func_147450_X() - { - Iterator iterator = this.worldAccesses.iterator(); - - while (iterator.hasNext()) - { - IWorldAccess iworldaccess = (IWorldAccess)iterator.next(); - iworldaccess.onStaticEntitiesChanged(); - } - } - - - /* ======================================== FORGE START =====================================*/ - /** - * Adds a single TileEntity to the world. - * @param entity The TileEntity to be added. - */ - public void addTileEntity(TileEntity entity) - { - List dest = field_147481_N ? addedTileEntityList : loadedTileEntityList; - if(entity.canUpdate()) - { - dest.add(entity); - } - } - - /** - * Determine if the given block is considered solid on the - * specified side. Used by placement logic. - * - * @param x Block X Position - * @param y Block Y Position - * @param z Block Z Position - * @param side The Side in question - * @return True if the side is solid - */ - public boolean isSideSolid(int x, int y, int z, ForgeDirection side) - { - return isSideSolid(x, y, z, side, false); - } - - /** - * Determine if the given block is considered solid on the - * specified side. Used by placement logic. - * - * @param x Block X Position - * @param y Block Y Position - * @param z Block Z Position - * @param side The Side in question - * @param _default The default to return if the block doesn't exist. - * @return True if the side is solid - */ - @Override - public boolean isSideSolid(int x, int y, int z, ForgeDirection side, boolean _default) - { - if (x < -30000000 || z < -30000000 || x >= 30000000 || z >= 30000000) - { - return _default; - } - - Chunk chunk = this.chunkProvider.provideChunk(x >> 4, z >> 4); - if (chunk == null || chunk.isEmpty()) - { - return _default; - } - return getBlock(x, y, z).isSideSolid(this, x, y, z, side); - } - - /** - * Get the persistent chunks for this world - * - * @return - */ - public ImmutableSetMultimap getPersistentChunks() - { - return ForgeChunkManager.getPersistentChunksFor(this); - } - - /** - * Readded as it was removed, very useful helper function - * - * @param x X position - * @param y Y Position - * @param z Z Position - * @return The blocks light opacity - */ - public int getBlockLightOpacity(int x, int y, int z) - { - if (x < -30000000 || z < -30000000 || x >= 30000000 || z >= 30000000) - { - return 0; - } - - if (y < 0 || y >= 256) - { - return 0; - } - - /** - * Returns back a chunk looked up by chunk coordinates Args: x, y - */ - return getChunkFromChunkCoords(x >> 4, z >> 4).func_150808_b(x & 15, y, z & 15); - } - - /** - * Returns a count of entities that classify themselves as the specified creature type. - */ - public int countEntities(EnumCreatureType type, boolean forSpawnCount) - { - int count = 0; - for (int x = 0; x < loadedEntityList.size(); x++) - { - if (((Entity)loadedEntityList.get(x)).isCreatureType(type, forSpawnCount)) - { - count++; - } - } - return count; - } -} \ No newline at end of file diff --git a/src/main/java/net/minecraft/world/WorldServer.java b/src/main/java/net/minecraft/world/WorldServer.java deleted file mode 100644 index 3ada194..0000000 --- a/src/main/java/net/minecraft/world/WorldServer.java +++ /dev/null @@ -1,1152 +0,0 @@ -package net.minecraft.world; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.Set; -import java.util.TreeSet; - -import mcp.mobius.mobiuscore.profiler.ProfilerSection; -import net.minecraft.block.Block; -import net.minecraft.block.BlockEventData; -import net.minecraft.block.material.Material; -import net.minecraft.crash.CrashReport; -import net.minecraft.crash.CrashReportCategory; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityTracker; -import net.minecraft.entity.EnumCreatureType; -import net.minecraft.entity.INpc; -import net.minecraft.entity.effect.EntityLightningBolt; -import net.minecraft.entity.passive.EntityAnimal; -import net.minecraft.entity.passive.EntityWaterMob; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.network.play.server.S19PacketEntityStatus; -import net.minecraft.network.play.server.S24PacketBlockAction; -import net.minecraft.network.play.server.S27PacketExplosion; -import net.minecraft.network.play.server.S2APacketParticles; -import net.minecraft.network.play.server.S2BPacketChangeGameState; -import net.minecraft.network.play.server.S2CPacketSpawnGlobalEntity; -import net.minecraft.profiler.Profiler; -import net.minecraft.scoreboard.ScoreboardSaveData; -import net.minecraft.scoreboard.ServerScoreboard; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.management.PlayerManager; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.IProgressUpdate; -import net.minecraft.util.IntHashMap; -import net.minecraft.util.ReportedException; -import net.minecraft.util.Vec3; -import net.minecraft.util.WeightedRandom; -import net.minecraft.util.WeightedRandomChestContent; -import net.minecraft.world.biome.BiomeGenBase; -import net.minecraft.world.biome.WorldChunkManager; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.chunk.storage.AnvilChunkLoader; -import net.minecraft.world.chunk.storage.ExtendedBlockStorage; -import net.minecraft.world.chunk.storage.IChunkLoader; -import net.minecraft.world.gen.ChunkProviderServer; -import net.minecraft.world.gen.feature.WorldGeneratorBonusChest; -import net.minecraft.world.storage.ISaveHandler; -import net.minecraftforge.common.ChestGenHooks; -import static net.minecraftforge.common.ChestGenHooks.BONUS_CHEST; -import net.minecraftforge.common.DimensionManager; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.ForgeEventFactory; -import net.minecraftforge.event.world.WorldEvent; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class WorldServer extends World -{ - private static final Logger logger = LogManager.getLogger(); - private final MinecraftServer mcServer; - private final EntityTracker theEntityTracker; - private final PlayerManager thePlayerManager; - private Set pendingTickListEntriesHashSet; - /** All work to do in future ticks. */ - private TreeSet pendingTickListEntriesTreeSet; - public ChunkProviderServer theChunkProviderServer; - /** Whether or not level saving is enabled */ - public boolean levelSaving; - /** is false if there are no players */ - private boolean allPlayersSleeping; - private int updateEntityTick; - /** - * the teleporter to use when the entity is being transferred into the dimension - */ - private final Teleporter worldTeleporter; - private final SpawnerAnimals animalSpawner = new SpawnerAnimals(); - private WorldServer.ServerBlockEventList[] field_147490_S = new WorldServer.ServerBlockEventList[] {new WorldServer.ServerBlockEventList(null), new WorldServer.ServerBlockEventList(null)}; - private int blockEventCacheIndex; - public static final WeightedRandomChestContent[] bonusChestContent = new WeightedRandomChestContent[] {new WeightedRandomChestContent(Items.stick, 0, 1, 3, 10), new WeightedRandomChestContent(Item.getItemFromBlock(Blocks.planks), 0, 1, 3, 10), new WeightedRandomChestContent(Item.getItemFromBlock(Blocks.log), 0, 1, 3, 10), new WeightedRandomChestContent(Items.stone_axe, 0, 1, 1, 3), new WeightedRandomChestContent(Items.wooden_axe, 0, 1, 1, 5), new WeightedRandomChestContent(Items.stone_pickaxe, 0, 1, 1, 3), new WeightedRandomChestContent(Items.wooden_pickaxe, 0, 1, 1, 5), new WeightedRandomChestContent(Items.apple, 0, 2, 3, 5), new WeightedRandomChestContent(Items.bread, 0, 2, 3, 3), new WeightedRandomChestContent(Item.getItemFromBlock(Blocks.log2), 0, 1, 3, 10)}; - private List pendingTickListEntriesThisTick = new ArrayList(); - /** An IntHashMap of entity IDs (integers) to their Entity objects. */ - private IntHashMap entityIdMap; - private static final String __OBFID = "CL_00001437"; - - /** Stores the recently processed (lighting) chunks */ - protected Set doneChunks = new HashSet(); - public List customTeleporters = new ArrayList(); - - public WorldServer(MinecraftServer p_i45284_1_, ISaveHandler p_i45284_2_, String p_i45284_3_, int p_i45284_4_, WorldSettings p_i45284_5_, Profiler p_i45284_6_) - { - super(p_i45284_2_, p_i45284_3_, p_i45284_5_, WorldProvider.getProviderForDimension(p_i45284_4_), p_i45284_6_); - this.mcServer = p_i45284_1_; - this.theEntityTracker = new EntityTracker(this); - this.thePlayerManager = new PlayerManager(this, p_i45284_1_.getConfigurationManager().getViewDistance()); - - if (this.entityIdMap == null) - { - this.entityIdMap = new IntHashMap(); - } - - if (this.pendingTickListEntriesHashSet == null) - { - this.pendingTickListEntriesHashSet = new HashSet(); - } - - if (this.pendingTickListEntriesTreeSet == null) - { - this.pendingTickListEntriesTreeSet = new TreeSet(); - } - - this.worldTeleporter = new Teleporter(this); - this.worldScoreboard = new ServerScoreboard(p_i45284_1_); - ScoreboardSaveData scoreboardsavedata = (ScoreboardSaveData)this.mapStorage.loadData(ScoreboardSaveData.class, "scoreboard"); - - if (scoreboardsavedata == null) - { - scoreboardsavedata = new ScoreboardSaveData(); - this.mapStorage.setData("scoreboard", scoreboardsavedata); - } - - if (!(this instanceof WorldServerMulti)) //Forge: We fix the global mapStorage, which causes us to share scoreboards early. So don't associate the save data with the temporary scoreboard - { - scoreboardsavedata.func_96499_a(this.worldScoreboard); - } - ((ServerScoreboard)this.worldScoreboard).func_96547_a(scoreboardsavedata); - DimensionManager.setWorld(p_i45284_4_, this); - } - - /** - * Runs a single tick for the world - */ - public void tick() - { - ProfilerSection.DIMENSION_BLOCKTICK.start(this.provider.dimensionId); - super.tick(); - - if (this.getWorldInfo().isHardcoreModeEnabled() && this.difficultySetting != EnumDifficulty.HARD) - { - this.difficultySetting = EnumDifficulty.HARD; - } - - this.provider.worldChunkMgr.cleanupCache(); - - if (this.areAllPlayersAsleep()) - { - if (this.getGameRules().getGameRuleBooleanValue("doDaylightCycle")) - { - long i = this.worldInfo.getWorldTime() + 24000L; - this.worldInfo.setWorldTime(i - i % 24000L); - } - - this.wakeAllPlayers(); - } - - this.theProfiler.startSection("mobSpawner"); - - if (this.getGameRules().getGameRuleBooleanValue("doMobSpawning")) - { - this.animalSpawner.findChunksForSpawning(this, this.spawnHostileMobs, this.spawnPeacefulMobs, this.worldInfo.getWorldTotalTime() % 400L == 0L); - } - - this.theProfiler.endStartSection("chunkSource"); - this.chunkProvider.unloadQueuedChunks(); - int j = this.calculateSkylightSubtracted(1.0F); - - if (j != this.skylightSubtracted) - { - this.skylightSubtracted = j; - } - - this.worldInfo.incrementTotalWorldTime(this.worldInfo.getWorldTotalTime() + 1L); - - if (this.getGameRules().getGameRuleBooleanValue("doDaylightCycle")) - { - this.worldInfo.setWorldTime(this.worldInfo.getWorldTime() + 1L); - } - - this.theProfiler.endStartSection("tickPending"); - this.tickUpdates(false); - this.theProfiler.endStartSection("tickBlocks"); - this.func_147456_g(); - this.theProfiler.endStartSection("chunkMap"); - this.thePlayerManager.updatePlayerInstances(); - this.theProfiler.endStartSection("village"); - this.villageCollectionObj.tick(); - this.villageSiegeObj.tick(); - this.theProfiler.endStartSection("portalForcer"); - this.worldTeleporter.removeStalePortalLocations(this.getTotalWorldTime()); - for (Teleporter tele : customTeleporters) - { - tele.removeStalePortalLocations(getTotalWorldTime()); - } - this.theProfiler.endSection(); - this.func_147488_Z(); - ProfilerSection.DIMENSION_BLOCKTICK.stop(this.provider.dimensionId); - } - - /** - * only spawns creatures allowed by the chunkProvider - */ - public BiomeGenBase.SpawnListEntry spawnRandomCreature(EnumCreatureType par1EnumCreatureType, int par2, int par3, int par4) - { - List list = this.getChunkProvider().getPossibleCreatures(par1EnumCreatureType, par2, par3, par4); - list = ForgeEventFactory.getPotentialSpawns(this, par1EnumCreatureType, par2, par3, par4, list); - return list != null && !list.isEmpty() ? (BiomeGenBase.SpawnListEntry)WeightedRandom.getRandomItem(this.rand, list) : null; - } - - /** - * Updates the flag that indicates whether or not all players in the world are sleeping. - */ - public void updateAllPlayersSleepingFlag() - { - this.allPlayersSleeping = !this.playerEntities.isEmpty(); - Iterator iterator = this.playerEntities.iterator(); - - while (iterator.hasNext()) - { - EntityPlayer entityplayer = (EntityPlayer)iterator.next(); - - if (!entityplayer.isPlayerSleeping()) - { - this.allPlayersSleeping = false; - break; - } - } - } - - protected void wakeAllPlayers() - { - this.allPlayersSleeping = false; - Iterator iterator = this.playerEntities.iterator(); - - while (iterator.hasNext()) - { - EntityPlayer entityplayer = (EntityPlayer)iterator.next(); - - if (entityplayer.isPlayerSleeping()) - { - entityplayer.wakeUpPlayer(false, false, true); - } - } - - this.resetRainAndThunder(); - } - - private void resetRainAndThunder() - { - provider.resetRainAndThunder(); - } - - public boolean areAllPlayersAsleep() - { - if (this.allPlayersSleeping && !this.isRemote) - { - Iterator iterator = this.playerEntities.iterator(); - EntityPlayer entityplayer; - - do - { - if (!iterator.hasNext()) - { - return true; - } - - entityplayer = (EntityPlayer)iterator.next(); - } - while (entityplayer.isPlayerFullyAsleep()); - - return false; - } - else - { - return false; - } - } - - /** - * Sets a new spawn location by finding an uncovered block at a random (x,z) location in the chunk. - */ - @SideOnly(Side.CLIENT) - public void setSpawnLocation() - { - if (this.worldInfo.getSpawnY() <= 0) - { - this.worldInfo.setSpawnY(64); - } - - int i = this.worldInfo.getSpawnX(); - int j = this.worldInfo.getSpawnZ(); - int k = 0; - - while (this.getTopBlock(i, j).getMaterial() == Material.air) - { - i += this.rand.nextInt(8) - this.rand.nextInt(8); - j += this.rand.nextInt(8) - this.rand.nextInt(8); - ++k; - - if (k == 10000) - { - break; - } - } - - this.worldInfo.setSpawnX(i); - this.worldInfo.setSpawnZ(j); - } - - protected void func_147456_g() - { - super.func_147456_g(); - int i = 0; - int j = 0; - Iterator iterator = this.activeChunkSet.iterator(); - - doneChunks.retainAll(activeChunkSet); - if (doneChunks.size() == activeChunkSet.size()) - { - doneChunks.clear(); - } - - final long startTime = System.nanoTime(); - - while (iterator.hasNext()) - { - ChunkCoordIntPair chunkcoordintpair = (ChunkCoordIntPair)iterator.next(); - int k = chunkcoordintpair.chunkXPos * 16; - int l = chunkcoordintpair.chunkZPos * 16; - this.theProfiler.startSection("getChunk"); - Chunk chunk = this.getChunkFromChunkCoords(chunkcoordintpair.chunkXPos, chunkcoordintpair.chunkZPos); - this.func_147467_a(k, l, chunk); - this.theProfiler.endStartSection("tickChunk"); - //Limits and evenly distributes the lighting update time - if (System.nanoTime() - startTime <= 4000000 && doneChunks.add(chunkcoordintpair)) - { - chunk.func_150804_b(false); - } - this.theProfiler.endStartSection("thunder"); - int i1; - int j1; - int k1; - int l1; - - if (provider.canDoLightning(chunk) && this.rand.nextInt(100000) == 0 && this.isRaining() && this.isThundering()) - { - this.updateLCG = this.updateLCG * 3 + 1013904223; - i1 = this.updateLCG >> 2; - j1 = k + (i1 & 15); - k1 = l + (i1 >> 8 & 15); - l1 = this.getPrecipitationHeight(j1, k1); - - if (this.canLightningStrikeAt(j1, l1, k1)) - { - this.addWeatherEffect(new EntityLightningBolt(this, (double)j1, (double)l1, (double)k1)); - } - } - - this.theProfiler.endStartSection("iceandsnow"); - - if (provider.canDoRainSnowIce(chunk) && this.rand.nextInt(16) == 0) - { - this.updateLCG = this.updateLCG * 3 + 1013904223; - i1 = this.updateLCG >> 2; - j1 = i1 & 15; - k1 = i1 >> 8 & 15; - l1 = this.getPrecipitationHeight(j1 + k, k1 + l); - - if (this.isBlockFreezableNaturally(j1 + k, l1 - 1, k1 + l)) - { - this.setBlock(j1 + k, l1 - 1, k1 + l, Blocks.ice); - } - - if (this.isRaining() && this.func_147478_e(j1 + k, l1, k1 + l, true)) - { - this.setBlock(j1 + k, l1, k1 + l, Blocks.snow_layer); - } - - if (this.isRaining()) - { - BiomeGenBase biomegenbase = this.getBiomeGenForCoords(j1 + k, k1 + l); - - if (biomegenbase.canSpawnLightningBolt()) - { - this.getBlock(j1 + k, l1 - 1, k1 + l).fillWithRain(this, j1 + k, l1 - 1, k1 + l); - } - } - } - - this.theProfiler.endStartSection("tickBlocks"); - ExtendedBlockStorage[] aextendedblockstorage = chunk.getBlockStorageArray(); - j1 = aextendedblockstorage.length; - - for (k1 = 0; k1 < j1; ++k1) - { - ExtendedBlockStorage extendedblockstorage = aextendedblockstorage[k1]; - - if (extendedblockstorage != null && extendedblockstorage.getNeedsRandomTick()) - { - for (int i3 = 0; i3 < 3; ++i3) - { - this.updateLCG = this.updateLCG * 3 + 1013904223; - int i2 = this.updateLCG >> 2; - int j2 = i2 & 15; - int k2 = i2 >> 8 & 15; - int l2 = i2 >> 16 & 15; - ++j; - Block block = extendedblockstorage.getBlockByExtId(j2, l2, k2); - - if (block.getTickRandomly()) - { - ++i; - block.updateTick(this, j2 + k, l2 + extendedblockstorage.getYLocation(), k2 + l, this.rand); - } - } - } - } - - this.theProfiler.endSection(); - } - } - - /** - * Returns true if the given block will receive a scheduled tick in this tick. Args: X, Y, Z, Block - */ - public boolean isBlockTickScheduledThisTick(int p_147477_1_, int p_147477_2_, int p_147477_3_, Block p_147477_4_) - { - NextTickListEntry nextticklistentry = new NextTickListEntry(p_147477_1_, p_147477_2_, p_147477_3_, p_147477_4_); - return this.pendingTickListEntriesThisTick.contains(nextticklistentry); - } - - /** - * Schedules a tick to a block with a delay (Most commonly the tick rate) - */ - public void scheduleBlockUpdate(int p_147464_1_, int p_147464_2_, int p_147464_3_, Block p_147464_4_, int p_147464_5_) - { - this.scheduleBlockUpdateWithPriority(p_147464_1_, p_147464_2_, p_147464_3_, p_147464_4_, p_147464_5_, 0); - } - - public void scheduleBlockUpdateWithPriority(int p_147454_1_, int p_147454_2_, int p_147454_3_, Block p_147454_4_, int p_147454_5_, int p_147454_6_) - { - NextTickListEntry nextticklistentry = new NextTickListEntry(p_147454_1_, p_147454_2_, p_147454_3_, p_147454_4_); - //Keeping here as a note for future when it may be restored. - //boolean isForced = getPersistentChunks().containsKey(new ChunkCoordIntPair(nextticklistentry.xCoord >> 4, nextticklistentry.zCoord >> 4)); - //byte b0 = isForced ? 0 : 8; - byte b0 = 0; - - if (this.scheduledUpdatesAreImmediate && p_147454_4_.getMaterial() != Material.air) - { - if (p_147454_4_.func_149698_L()) - { - b0 = 8; - - if (this.checkChunksExist(nextticklistentry.xCoord - b0, nextticklistentry.yCoord - b0, nextticklistentry.zCoord - b0, nextticklistentry.xCoord + b0, nextticklistentry.yCoord + b0, nextticklistentry.zCoord + b0)) - { - Block block1 = this.getBlock(nextticklistentry.xCoord, nextticklistentry.yCoord, nextticklistentry.zCoord); - - if (block1.getMaterial() != Material.air && block1 == nextticklistentry.func_151351_a()) - { - block1.updateTick(this, nextticklistentry.xCoord, nextticklistentry.yCoord, nextticklistentry.zCoord, this.rand); - } - } - - return; - } - - p_147454_5_ = 1; - } - - if (this.checkChunksExist(p_147454_1_ - b0, p_147454_2_ - b0, p_147454_3_ - b0, p_147454_1_ + b0, p_147454_2_ + b0, p_147454_3_ + b0)) - { - if (p_147454_4_.getMaterial() != Material.air) - { - nextticklistentry.setScheduledTime((long)p_147454_5_ + this.worldInfo.getWorldTotalTime()); - nextticklistentry.setPriority(p_147454_6_); - } - - if (!this.pendingTickListEntriesHashSet.contains(nextticklistentry)) - { - this.pendingTickListEntriesHashSet.add(nextticklistentry); - this.pendingTickListEntriesTreeSet.add(nextticklistentry); - } - } - } - - public void func_147446_b(int p_147446_1_, int p_147446_2_, int p_147446_3_, Block p_147446_4_, int p_147446_5_, int p_147446_6_) - { - NextTickListEntry nextticklistentry = new NextTickListEntry(p_147446_1_, p_147446_2_, p_147446_3_, p_147446_4_); - nextticklistentry.setPriority(p_147446_6_); - - if (p_147446_4_.getMaterial() != Material.air) - { - nextticklistentry.setScheduledTime((long)p_147446_5_ + this.worldInfo.getWorldTotalTime()); - } - - if (!this.pendingTickListEntriesHashSet.contains(nextticklistentry)) - { - this.pendingTickListEntriesHashSet.add(nextticklistentry); - this.pendingTickListEntriesTreeSet.add(nextticklistentry); - } - } - - /** - * Updates (and cleans up) entities and tile entities - */ - public void updateEntities() - { - if (this.playerEntities.isEmpty() && getPersistentChunks().isEmpty()) - { - if (this.updateEntityTick++ >= 1200) - { - return; - } - } - else - { - this.resetUpdateEntityTick(); - } - - super.updateEntities(); - } - - /** - * Resets the updateEntityTick field to 0 - */ - public void resetUpdateEntityTick() - { - this.updateEntityTick = 0; - } - - /** - * Runs through the list of updates to run and ticks them - */ - public boolean tickUpdates(boolean par1) - { - int i = this.pendingTickListEntriesTreeSet.size(); - - if (i != this.pendingTickListEntriesHashSet.size()) - { - throw new IllegalStateException("TickNextTick list out of synch"); - } - else - { - if (i > 1000) - { - i = 1000; - } - - this.theProfiler.startSection("cleaning"); - NextTickListEntry nextticklistentry; - - for (int j = 0; j < i; ++j) - { - nextticklistentry = (NextTickListEntry)this.pendingTickListEntriesTreeSet.first(); - - if (!par1 && nextticklistentry.scheduledTime > this.worldInfo.getWorldTotalTime()) - { - break; - } - - this.pendingTickListEntriesTreeSet.remove(nextticklistentry); - this.pendingTickListEntriesHashSet.remove(nextticklistentry); - this.pendingTickListEntriesThisTick.add(nextticklistentry); - } - - this.theProfiler.endSection(); - this.theProfiler.startSection("ticking"); - Iterator iterator = this.pendingTickListEntriesThisTick.iterator(); - - while (iterator.hasNext()) - { - nextticklistentry = (NextTickListEntry)iterator.next(); - iterator.remove(); - //Keeping here as a note for future when it may be restored. - //boolean isForced = getPersistentChunks().containsKey(new ChunkCoordIntPair(nextticklistentry.xCoord >> 4, nextticklistentry.zCoord >> 4)); - //byte b0 = isForced ? 0 : 8; - byte b0 = 0; - - if (this.checkChunksExist(nextticklistentry.xCoord - b0, nextticklistentry.yCoord - b0, nextticklistentry.zCoord - b0, nextticklistentry.xCoord + b0, nextticklistentry.yCoord + b0, nextticklistentry.zCoord + b0)) - { - Block block = this.getBlock(nextticklistentry.xCoord, nextticklistentry.yCoord, nextticklistentry.zCoord); - - if (block.getMaterial() != Material.air && Block.isEqualTo(block, nextticklistentry.func_151351_a())) - { - try - { - block.updateTick(this, nextticklistentry.xCoord, nextticklistentry.yCoord, nextticklistentry.zCoord, this.rand); - } - catch (Throwable throwable1) - { - CrashReport crashreport = CrashReport.makeCrashReport(throwable1, "Exception while ticking a block"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being ticked"); - int k; - - try - { - k = this.getBlockMetadata(nextticklistentry.xCoord, nextticklistentry.yCoord, nextticklistentry.zCoord); - } - catch (Throwable throwable) - { - k = -1; - } - - CrashReportCategory.func_147153_a(crashreportcategory, nextticklistentry.xCoord, nextticklistentry.yCoord, nextticklistentry.zCoord, block, k); - throw new ReportedException(crashreport); - } - } - } - else - { - this.scheduleBlockUpdate(nextticklistentry.xCoord, nextticklistentry.yCoord, nextticklistentry.zCoord, nextticklistentry.func_151351_a(), 0); - } - } - - this.theProfiler.endSection(); - this.pendingTickListEntriesThisTick.clear(); - return !this.pendingTickListEntriesTreeSet.isEmpty(); - } - } - - public List getPendingBlockUpdates(Chunk par1Chunk, boolean par2) - { - ArrayList arraylist = null; - ChunkCoordIntPair chunkcoordintpair = par1Chunk.getChunkCoordIntPair(); - int i = (chunkcoordintpair.chunkXPos << 4) - 2; - int j = i + 16 + 2; - int k = (chunkcoordintpair.chunkZPos << 4) - 2; - int l = k + 16 + 2; - - for (int i1 = 0; i1 < 2; ++i1) - { - Iterator iterator; - - if (i1 == 0) - { - iterator = this.pendingTickListEntriesTreeSet.iterator(); - } - else - { - iterator = this.pendingTickListEntriesThisTick.iterator(); - - if (!this.pendingTickListEntriesThisTick.isEmpty()) - { - logger.debug("toBeTicked = " + this.pendingTickListEntriesThisTick.size()); - } - } - - while (iterator.hasNext()) - { - NextTickListEntry nextticklistentry = (NextTickListEntry)iterator.next(); - - if (nextticklistentry.xCoord >= i && nextticklistentry.xCoord < j && nextticklistentry.zCoord >= k && nextticklistentry.zCoord < l) - { - if (par2) - { - this.pendingTickListEntriesHashSet.remove(nextticklistentry); - iterator.remove(); - } - - if (arraylist == null) - { - arraylist = new ArrayList(); - } - - arraylist.add(nextticklistentry); - } - } - } - - return arraylist; - } - - /** - * Will update the entity in the world if the chunk the entity is in is currently loaded or its forced to update. - * Args: entity, forceUpdate - */ - public void updateEntityWithOptionalForce(Entity par1Entity, boolean par2) - { - if (!this.mcServer.getCanSpawnAnimals() && (par1Entity instanceof EntityAnimal || par1Entity instanceof EntityWaterMob)) - { - par1Entity.setDead(); - } - - if (!this.mcServer.getCanSpawnNPCs() && par1Entity instanceof INpc) - { - par1Entity.setDead(); - } - - super.updateEntityWithOptionalForce(par1Entity, par2); - } - - /** - * Creates the chunk provider for this world. Called in the constructor. Retrieves provider from worldProvider? - */ - protected IChunkProvider createChunkProvider() - { - IChunkLoader ichunkloader = this.saveHandler.getChunkLoader(this.provider); - this.theChunkProviderServer = new ChunkProviderServer(this, ichunkloader, this.provider.createChunkGenerator()); - return this.theChunkProviderServer; - } - - public List func_147486_a(int p_147486_1_, int p_147486_2_, int p_147486_3_, int p_147486_4_, int p_147486_5_, int p_147486_6_) - { - ArrayList arraylist = new ArrayList(); - - for(int x = (p_147486_1_ >> 4); x <= (p_147486_4_ >> 4); x++) - { - for(int z = (p_147486_3_ >> 4); z <= (p_147486_6_ >> 4); z++) - { - Chunk chunk = getChunkFromChunkCoords(x, z); - if (chunk != null) - { - for(Object obj : chunk.chunkTileEntityMap.values()) - { - TileEntity entity = (TileEntity)obj; - if (!entity.isInvalid()) - { - if (entity.xCoord >= p_147486_1_ && entity.yCoord >= p_147486_2_ && entity.zCoord >= p_147486_3_ && - entity.xCoord <= p_147486_4_ && entity.yCoord <= p_147486_5_ && entity.zCoord <= p_147486_6_) - { - arraylist.add(entity); - } - } - } - } - } - } - - return arraylist; - } - - /** - * Called when checking if a certain block can be mined or not. The 'spawn safe zone' check is located here. - */ - public boolean canMineBlock(EntityPlayer par1EntityPlayer, int par2, int par3, int par4) - { - return super.canMineBlock(par1EntityPlayer, par2, par3, par4); - } - - public boolean canMineBlockBody(EntityPlayer par1EntityPlayer, int par2, int par3, int par4) - { - return !this.mcServer.isBlockProtected(this, par2, par3, par4, par1EntityPlayer); - } - - protected void initialize(WorldSettings par1WorldSettings) - { - if (this.entityIdMap == null) - { - this.entityIdMap = new IntHashMap(); - } - - if (this.pendingTickListEntriesHashSet == null) - { - this.pendingTickListEntriesHashSet = new HashSet(); - } - - if (this.pendingTickListEntriesTreeSet == null) - { - this.pendingTickListEntriesTreeSet = new TreeSet(); - } - - this.createSpawnPosition(par1WorldSettings); - super.initialize(par1WorldSettings); - } - - /** - * creates a spawn position at random within 256 blocks of 0,0 - */ - protected void createSpawnPosition(WorldSettings par1WorldSettings) - { - if (!this.provider.canRespawnHere()) - { - this.worldInfo.setSpawnPosition(0, this.provider.getAverageGroundLevel(), 0); - } - else - { - this.findingSpawnPoint = true; - WorldChunkManager worldchunkmanager = this.provider.worldChunkMgr; - List list = worldchunkmanager.getBiomesToSpawnIn(); - Random random = new Random(this.getSeed()); - ChunkPosition chunkposition = worldchunkmanager.findBiomePosition(0, 0, 256, list, random); - int i = 0; - int j = this.provider.getAverageGroundLevel(); - int k = 0; - - if (chunkposition != null) - { - i = chunkposition.chunkPosX; - k = chunkposition.chunkPosZ; - } - else - { - logger.warn("Unable to find spawn biome"); - } - - int l = 0; - - while (!this.provider.canCoordinateBeSpawn(i, k)) - { - i += random.nextInt(64) - random.nextInt(64); - k += random.nextInt(64) - random.nextInt(64); - ++l; - - if (l == 1000) - { - break; - } - } - - this.worldInfo.setSpawnPosition(i, j, k); - this.findingSpawnPoint = false; - - if (par1WorldSettings.isBonusChestEnabled()) - { - this.createBonusChest(); - } - } - } - - /** - * Creates the bonus chest in the world. - */ - protected void createBonusChest() - { - WorldGeneratorBonusChest worldgeneratorbonuschest = new WorldGeneratorBonusChest(ChestGenHooks.getItems(BONUS_CHEST, rand), ChestGenHooks.getCount(BONUS_CHEST, rand)); - - for (int i = 0; i < 10; ++i) - { - int j = this.worldInfo.getSpawnX() + this.rand.nextInt(6) - this.rand.nextInt(6); - int k = this.worldInfo.getSpawnZ() + this.rand.nextInt(6) - this.rand.nextInt(6); - int l = this.getTopSolidOrLiquidBlock(j, k) + 1; - - if (worldgeneratorbonuschest.generate(this, this.rand, j, l, k)) - { - break; - } - } - } - - /** - * Gets the hard-coded portal location to use when entering this dimension. - */ - public ChunkCoordinates getEntrancePortalLocation() - { - return this.provider.getEntrancePortalLocation(); - } - - /** - * Saves all chunks to disk while updating progress bar. - */ - public void saveAllChunks(boolean par1, IProgressUpdate par2IProgressUpdate) throws MinecraftException - { - if (this.chunkProvider.canSave()) - { - if (par2IProgressUpdate != null) - { - par2IProgressUpdate.displayProgressMessage("Saving level"); - } - - this.saveLevel(); - - if (par2IProgressUpdate != null) - { - par2IProgressUpdate.resetProgresAndWorkingMessage("Saving chunks"); - } - - this.chunkProvider.saveChunks(par1, par2IProgressUpdate); - MinecraftForge.EVENT_BUS.post(new WorldEvent.Save(this)); - } - } - - /** - * saves chunk data - currently only called during execution of the Save All command - */ - public void saveChunkData() - { - if (this.chunkProvider.canSave()) - { - this.chunkProvider.saveExtraData(); - } - } - - /** - * Saves the chunks to disk. - */ - protected void saveLevel() throws MinecraftException - { - this.checkSessionLock(); - this.saveHandler.saveWorldInfoWithPlayer(this.worldInfo, this.mcServer.getConfigurationManager().getHostPlayerData()); - this.mapStorage.saveAllData(); - this.perWorldStorage.saveAllData(); - } - - public void onEntityAdded(Entity par1Entity) - { - super.onEntityAdded(par1Entity); - this.entityIdMap.addKey(par1Entity.getEntityId(), par1Entity); - Entity[] aentity = par1Entity.getParts(); - - if (aentity != null) - { - for (int i = 0; i < aentity.length; ++i) - { - this.entityIdMap.addKey(aentity[i].getEntityId(), aentity[i]); - } - } - } - - public void onEntityRemoved(Entity par1Entity) - { - super.onEntityRemoved(par1Entity); - this.entityIdMap.removeObject(par1Entity.getEntityId()); - Entity[] aentity = par1Entity.getParts(); - - if (aentity != null) - { - for (int i = 0; i < aentity.length; ++i) - { - this.entityIdMap.removeObject(aentity[i].getEntityId()); - } - } - } - - /** - * Returns the Entity with the given ID, or null if it doesn't exist in this World. - */ - public Entity getEntityByID(int par1) - { - return (Entity)this.entityIdMap.lookup(par1); - } - - /** - * adds a lightning bolt to the list of lightning bolts in this world. - */ - public boolean addWeatherEffect(Entity par1Entity) - { - if (super.addWeatherEffect(par1Entity)) - { - this.mcServer.getConfigurationManager().sendToAllNear(par1Entity.posX, par1Entity.posY, par1Entity.posZ, 512.0D, this.provider.dimensionId, new S2CPacketSpawnGlobalEntity(par1Entity)); - return true; - } - else - { - return false; - } - } - - /** - * sends a Packet 38 (Entity Status) to all tracked players of that entity - */ - public void setEntityState(Entity par1Entity, byte par2) - { - this.getEntityTracker().func_151248_b(par1Entity, new S19PacketEntityStatus(par1Entity, par2)); - } - - /** - * returns a new explosion. Does initiation (at time of writing Explosion is not finished) - */ - public Explosion newExplosion(Entity par1Entity, double par2, double par4, double par6, float par8, boolean par9, boolean par10) - { - Explosion explosion = new Explosion(this, par1Entity, par2, par4, par6, par8); - explosion.isFlaming = par9; - explosion.isSmoking = par10; - explosion.doExplosionA(); - explosion.doExplosionB(false); - - if (!par10) - { - explosion.affectedBlockPositions.clear(); - } - - Iterator iterator = this.playerEntities.iterator(); - - while (iterator.hasNext()) - { - EntityPlayer entityplayer = (EntityPlayer)iterator.next(); - - if (entityplayer.getDistanceSq(par2, par4, par6) < 4096.0D) - { - ((EntityPlayerMP)entityplayer).playerNetServerHandler.sendPacket(new S27PacketExplosion(par2, par4, par6, par8, explosion.affectedBlockPositions, (Vec3)explosion.func_77277_b().get(entityplayer))); - } - } - - return explosion; - } - - /** - * Adds a block event with the given Args to the blockEventCache. During the next tick(), the block specified will - * have its onBlockEvent handler called with the given parameters. Args: X,Y,Z, Block, EventID, EventParameter - */ - public void addBlockEvent(int p_147452_1_, int p_147452_2_, int p_147452_3_, Block p_147452_4_, int p_147452_5_, int p_147452_6_) - { - BlockEventData blockeventdata = new BlockEventData(p_147452_1_, p_147452_2_, p_147452_3_, p_147452_4_, p_147452_5_, p_147452_6_); - Iterator iterator = this.field_147490_S[this.blockEventCacheIndex].iterator(); - BlockEventData blockeventdata1; - - do - { - if (!iterator.hasNext()) - { - this.field_147490_S[this.blockEventCacheIndex].add(blockeventdata); - return; - } - - blockeventdata1 = (BlockEventData)iterator.next(); - } - while (!blockeventdata1.equals(blockeventdata)); - } - - private void func_147488_Z() - { - while (!this.field_147490_S[this.blockEventCacheIndex].isEmpty()) - { - int i = this.blockEventCacheIndex; - this.blockEventCacheIndex ^= 1; - Iterator iterator = this.field_147490_S[i].iterator(); - - while (iterator.hasNext()) - { - BlockEventData blockeventdata = (BlockEventData)iterator.next(); - - if (this.func_147485_a(blockeventdata)) - { - this.mcServer.getConfigurationManager().sendToAllNear((double)blockeventdata.func_151340_a(), (double)blockeventdata.func_151342_b(), (double)blockeventdata.func_151341_c(), 64.0D, this.provider.dimensionId, new S24PacketBlockAction(blockeventdata.func_151340_a(), blockeventdata.func_151342_b(), blockeventdata.func_151341_c(), blockeventdata.getBlock(), blockeventdata.getEventID(), blockeventdata.getEventParameter())); - } - } - - this.field_147490_S[i].clear(); - } - } - - private boolean func_147485_a(BlockEventData p_147485_1_) - { - Block block = this.getBlock(p_147485_1_.func_151340_a(), p_147485_1_.func_151342_b(), p_147485_1_.func_151341_c()); - return block == p_147485_1_.getBlock() ? block.onBlockEventReceived(this, p_147485_1_.func_151340_a(), p_147485_1_.func_151342_b(), p_147485_1_.func_151341_c(), p_147485_1_.getEventID(), p_147485_1_.getEventParameter()) : false; - } - - /** - * Syncs all changes to disk and wait for completion. - */ - public void flush() - { - this.saveHandler.flush(); - } - - /** - * Updates all weather states. - */ - protected void updateWeather() - { - boolean flag = this.isRaining(); - super.updateWeather(); - - if (this.prevRainingStrength != this.rainingStrength) - { - this.mcServer.getConfigurationManager().sendPacketToAllPlayersInDimension(new S2BPacketChangeGameState(7, this.rainingStrength), this.provider.dimensionId); - } - - if (this.prevThunderingStrength != this.thunderingStrength) - { - this.mcServer.getConfigurationManager().sendPacketToAllPlayersInDimension(new S2BPacketChangeGameState(8, this.thunderingStrength), this.provider.dimensionId); - } - - if (flag != this.isRaining()) - { - if (flag) - { - this.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S2BPacketChangeGameState(2, 0.0F)); - } - else - { - this.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S2BPacketChangeGameState(1, 0.0F)); - } - - this.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S2BPacketChangeGameState(7, this.rainingStrength)); - this.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S2BPacketChangeGameState(8, this.thunderingStrength)); - } - } - - public MinecraftServer func_73046_m() - { - return this.mcServer; - } - - /** - * Gets the EntityTracker - */ - public EntityTracker getEntityTracker() - { - return this.theEntityTracker; - } - - public PlayerManager getPlayerManager() - { - return this.thePlayerManager; - } - - public Teleporter getDefaultTeleporter() - { - return this.worldTeleporter; - } - - public void func_147487_a(String p_147487_1_, double p_147487_2_, double p_147487_4_, double p_147487_6_, int p_147487_8_, double p_147487_9_, double p_147487_11_, double p_147487_13_, double p_147487_15_) - { - S2APacketParticles s2apacketparticles = new S2APacketParticles(p_147487_1_, (float)p_147487_2_, (float)p_147487_4_, (float)p_147487_6_, (float)p_147487_9_, (float)p_147487_11_, (float)p_147487_13_, (float)p_147487_15_, p_147487_8_); - - for (int j = 0; j < this.playerEntities.size(); ++j) - { - EntityPlayerMP entityplayermp = (EntityPlayerMP)this.playerEntities.get(j); - ChunkCoordinates chunkcoordinates = entityplayermp.getPlayerCoordinates(); - double d7 = p_147487_2_ - (double)chunkcoordinates.posX; - double d8 = p_147487_4_ - (double)chunkcoordinates.posY; - double d9 = p_147487_6_ - (double)chunkcoordinates.posZ; - double d10 = d7 * d7 + d8 * d8 + d9 * d9; - - if (d10 <= 256.0D) - { - entityplayermp.playerNetServerHandler.sendPacket(s2apacketparticles); - } - } - } - - public File getChunkSaveLocation() - { - return ((AnvilChunkLoader)theChunkProviderServer.currentChunkLoader).chunkSaveLocation; - } - - static class ServerBlockEventList extends ArrayList - { - private static final String __OBFID = "CL_00001439"; - - private ServerBlockEventList() {} - - ServerBlockEventList(Object par1ServerBlockEvent) - { - this(); - } - } -} \ No newline at end of file diff --git a/src/main/java/net/minecraft/world/gen/ChunkProviderServer.java b/src/main/java/net/minecraft/world/gen/ChunkProviderServer.java deleted file mode 100644 index 3736c1d..0000000 --- a/src/main/java/net/minecraft/world/gen/ChunkProviderServer.java +++ /dev/null @@ -1,383 +0,0 @@ -package net.minecraft.world.gen; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import cpw.mods.fml.common.registry.GameRegistry; -import net.minecraft.crash.CrashReport; -import net.minecraft.crash.CrashReportCategory; -import net.minecraft.entity.EnumCreatureType; -import net.minecraft.util.ChunkCoordinates; -import net.minecraft.util.IProgressUpdate; -import net.minecraft.util.LongHashMap; -import net.minecraft.util.ReportedException; -import net.minecraft.world.ChunkCoordIntPair; -import net.minecraft.world.ChunkPosition; -import net.minecraft.world.MinecraftException; -import net.minecraft.world.World; -import net.minecraft.world.WorldServer; -import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.EmptyChunk; -import net.minecraft.world.chunk.IChunkProvider; -import net.minecraft.world.chunk.storage.IChunkLoader; -import net.minecraftforge.common.DimensionManager; -import net.minecraftforge.common.ForgeChunkManager; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class ChunkProviderServer implements IChunkProvider -{ - private static final Logger logger = LogManager.getLogger(); - /** - * used by unload100OldestChunks to iterate the loadedChunkHashMap for unload (underlying assumption, first in, - * first out) - */ - public Set chunksToUnload = new HashSet(); - public Chunk defaultEmptyChunk; - public IChunkProvider currentChunkProvider; - public IChunkLoader currentChunkLoader; - /** - * if this is false, the defaultEmptyChunk will be returned by the provider - */ - public boolean loadChunkOnProvideRequest = true; - public LongHashMap loadedChunkHashMap = new LongHashMap(); - public List loadedChunks = new ArrayList(); - public WorldServer worldObj; - public static final String __OBFID = "CL_00001436"; - - public ChunkProviderServer(WorldServer par1WorldServer, IChunkLoader par2IChunkLoader, IChunkProvider par3IChunkProvider) - { - this.defaultEmptyChunk = new EmptyChunk(par1WorldServer, 0, 0); - this.worldObj = par1WorldServer; - this.currentChunkLoader = par2IChunkLoader; - this.currentChunkProvider = par3IChunkProvider; - } - - /** - * Checks to see if a chunk exists at x, y - */ - public boolean chunkExists(int par1, int par2) - { - return this.loadedChunkHashMap.containsItem(ChunkCoordIntPair.chunkXZ2Int(par1, par2)); - } - - /** - * marks chunk for unload by "unload100OldestChunks" if there is no spawn point, or if the center of the chunk is - * outside 200 blocks (x or z) of the spawn - */ - public void unloadChunksIfNotNearSpawn(int par1, int par2) - { - if (this.worldObj.provider.canRespawnHere() && DimensionManager.shouldLoadSpawn(this.worldObj.provider.dimensionId)) - { - ChunkCoordinates chunkcoordinates = this.worldObj.getSpawnPoint(); - int k = par1 * 16 + 8 - chunkcoordinates.posX; - int l = par2 * 16 + 8 - chunkcoordinates.posZ; - short short1 = 128; - - if (k < -short1 || k > short1 || l < -short1 || l > short1) - { - this.chunksToUnload.add(Long.valueOf(ChunkCoordIntPair.chunkXZ2Int(par1, par2))); - } - } - else - { - this.chunksToUnload.add(Long.valueOf(ChunkCoordIntPair.chunkXZ2Int(par1, par2))); - } - } - - /** - * marks all chunks for unload, ignoring those near the spawn - */ - public void unloadAllChunks() - { - Iterator iterator = this.loadedChunks.iterator(); - - while (iterator.hasNext()) - { - Chunk chunk = (Chunk)iterator.next(); - this.unloadChunksIfNotNearSpawn(chunk.xPosition, chunk.zPosition); - } - } - - /** - * loads or generates the chunk at the chunk location specified - */ - public Chunk loadChunk(int par1, int par2) - { - long k = ChunkCoordIntPair.chunkXZ2Int(par1, par2); - this.chunksToUnload.remove(Long.valueOf(k)); - Chunk chunk = (Chunk)this.loadedChunkHashMap.getValueByKey(k); - - if (chunk == null) - { - chunk = ForgeChunkManager.fetchDormantChunk(k, this.worldObj); - if (chunk == null) - { - chunk = this.safeLoadChunk(par1, par2); - } - - if (chunk == null) - { - if (this.currentChunkProvider == null) - { - chunk = this.defaultEmptyChunk; - } - else - { - try - { - chunk = this.currentChunkProvider.provideChunk(par1, par2); - } - catch (Throwable throwable) - { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception generating new chunk"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Chunk to be generated"); - crashreportcategory.addCrashSection("Location", String.format("%d,%d", new Object[] {Integer.valueOf(par1), Integer.valueOf(par2)})); - crashreportcategory.addCrashSection("Position hash", Long.valueOf(k)); - crashreportcategory.addCrashSection("Generator", this.currentChunkProvider.makeString()); - throw new ReportedException(crashreport); - } - } - } - - this.loadedChunkHashMap.add(k, chunk); - this.loadedChunks.add(chunk); - chunk.onChunkLoad(); - chunk.populateChunk(this, this, par1, par2); - } - - return chunk; - } - - /** - * Will return back a chunk, if it doesn't exist and its not a MP client it will generates all the blocks for the - * specified chunk from the map seed and chunk seed - */ - public Chunk provideChunk(int par1, int par2) - { - Chunk chunk = (Chunk)this.loadedChunkHashMap.getValueByKey(ChunkCoordIntPair.chunkXZ2Int(par1, par2)); - return chunk == null ? (!this.worldObj.findingSpawnPoint && !this.loadChunkOnProvideRequest ? this.defaultEmptyChunk : this.loadChunk(par1, par2)) : chunk; - } - - /** - * used by loadChunk, but catches any exceptions if the load fails. - */ - private Chunk safeLoadChunk(int par1, int par2) - { - if (this.currentChunkLoader == null) - { - return null; - } - else - { - try - { - Chunk chunk = this.currentChunkLoader.loadChunk(this.worldObj, par1, par2); - - if (chunk != null) - { - chunk.lastSaveTime = this.worldObj.getTotalWorldTime(); - - if (this.currentChunkProvider != null) - { - this.currentChunkProvider.recreateStructures(par1, par2); - } - } - - return chunk; - } - catch (Exception exception) - { - logger.error("Couldn\'t load chunk", exception); - return null; - } - } - } - - /** - * used by saveChunks, but catches any exceptions if the save fails. - */ - private void safeSaveExtraChunkData(Chunk par1Chunk) - { - if (this.currentChunkLoader != null) - { - try - { - this.currentChunkLoader.saveExtraChunkData(this.worldObj, par1Chunk); - } - catch (Exception exception) - { - logger.error("Couldn\'t save entities", exception); - } - } - } - - /** - * used by saveChunks, but catches any exceptions if the save fails. - */ - private void safeSaveChunk(Chunk par1Chunk) - { - if (this.currentChunkLoader != null) - { - try - { - par1Chunk.lastSaveTime = this.worldObj.getTotalWorldTime(); - this.currentChunkLoader.saveChunk(this.worldObj, par1Chunk); - } - catch (IOException ioexception) - { - logger.error("Couldn\'t save chunk", ioexception); - } - catch (MinecraftException minecraftexception) - { - logger.error("Couldn\'t save chunk; already in use by another instance of Minecraft?", minecraftexception); - } - } - } - - /** - * Populates chunk with ores etc etc - */ - public void populate(IChunkProvider par1IChunkProvider, int par2, int par3) - { - Chunk chunk = this.provideChunk(par2, par3); - - if (!chunk.isTerrainPopulated) - { - chunk.func_150809_p(); - - if (this.currentChunkProvider != null) - { - this.currentChunkProvider.populate(par1IChunkProvider, par2, par3); - GameRegistry.generateWorld(par2, par3, worldObj, currentChunkProvider, par1IChunkProvider); - chunk.setChunkModified(); - } - } - } - - /** - * Two modes of operation: if passed true, save all Chunks in one go. If passed false, save up to two chunks. - * Return true if all chunks have been saved. - */ - public boolean saveChunks(boolean par1, IProgressUpdate par2IProgressUpdate) - { - int i = 0; - - for (int j = 0; j < this.loadedChunks.size(); ++j) - { - Chunk chunk = (Chunk)this.loadedChunks.get(j); - - if (par1) - { - this.safeSaveExtraChunkData(chunk); - } - - if (chunk.needsSaving(par1)) - { - this.safeSaveChunk(chunk); - chunk.isModified = false; - ++i; - - if (i == 24 && !par1) - { - return false; - } - } - } - - return true; - } - - /** - * Save extra data not associated with any Chunk. Not saved during autosave, only during world unload. Currently - * unimplemented. - */ - public void saveExtraData() - { - if (this.currentChunkLoader != null) - { - this.currentChunkLoader.saveExtraData(); - } - } - - /** - * Unloads chunks that are marked to be unloaded. This is not guaranteed to unload every such chunk. - */ - public boolean unloadQueuedChunks() - { - if (!this.worldObj.levelSaving) - { - for (ChunkCoordIntPair forced : this.worldObj.getPersistentChunks().keySet()) - { - this.chunksToUnload.remove(ChunkCoordIntPair.chunkXZ2Int(forced.chunkXPos, forced.chunkZPos)); - } - - for (int i = 0; i < 100; ++i) - { - if (!this.chunksToUnload.isEmpty()) - { - Long olong = (Long)this.chunksToUnload.iterator().next(); - Chunk chunk = (Chunk)this.loadedChunkHashMap.getValueByKey(olong.longValue()); - chunk.onChunkUnload(); - this.safeSaveChunk(chunk); - this.safeSaveExtraChunkData(chunk); - this.chunksToUnload.remove(olong); - this.loadedChunkHashMap.remove(olong.longValue()); - this.loadedChunks.remove(chunk); - ForgeChunkManager.putDormantChunk(ChunkCoordIntPair.chunkXZ2Int(chunk.xPosition, chunk.zPosition), chunk); - if(loadedChunks.size() == 0 && ForgeChunkManager.getPersistentChunksFor(this.worldObj).size() == 0 && !DimensionManager.shouldLoadSpawn(this.worldObj.provider.dimensionId)){ - DimensionManager.unloadWorld(this.worldObj.provider.dimensionId); - return currentChunkProvider.unloadQueuedChunks(); - } - } - } - - if (this.currentChunkLoader != null) - { - this.currentChunkLoader.chunkTick(); - } - } - - return this.currentChunkProvider.unloadQueuedChunks(); - } - - /** - * Returns if the IChunkProvider supports saving. - */ - public boolean canSave() - { - return !this.worldObj.levelSaving; - } - - /** - * Converts the instance data to a readable string. - */ - public String makeString() - { - return "ServerChunkCache: " + this.loadedChunkHashMap.getNumHashElements() + " Drop: " + this.chunksToUnload.size(); - } - - /** - * Returns a list of creatures of the specified type that can spawn at the given location. - */ - public List getPossibleCreatures(EnumCreatureType par1EnumCreatureType, int par2, int par3, int par4) - { - return this.currentChunkProvider.getPossibleCreatures(par1EnumCreatureType, par2, par3, par4); - } - - public ChunkPosition func_147416_a(World p_147416_1_, String p_147416_2_, int p_147416_3_, int p_147416_4_, int p_147416_5_) - { - return this.currentChunkProvider.func_147416_a(p_147416_1_, p_147416_2_, p_147416_3_, p_147416_4_, p_147416_5_); - } - - public int getLoadedChunkCount() - { - return this.loadedChunkHashMap.getNumHashElements(); - } - - public void recreateStructures(int par1, int par2) {} -} \ No newline at end of file diff --git a/src/main/resources/assets/mapwriter/lang/en_US.lang b/src/main/resources/assets/mapwriter/lang/en_US.lang new file mode 100644 index 0000000..3ad0e73 --- /dev/null +++ b/src/main/resources/assets/mapwriter/lang/en_US.lang @@ -0,0 +1,8 @@ +key.mw_open_gui=Open map GUI +key.mw_new_marker=New Waypoint +key.mw_next_map_mode=Next map mode +key.mw_next_marker_group=Next waypoint group +key.mw_teleport=Teleport to waypoint +key.mw_zoom_in=Minimap zoom in +key.mw_zoom_out=Minimap zoom out +key.mw_underground_mode=Underground map mode diff --git a/src/main/resources/assets/mapwriter/textures/map/arrow_north.png b/src/main/resources/assets/mapwriter/textures/map/arrow_north.png new file mode 100644 index 0000000..16a4cb5 Binary files /dev/null and b/src/main/resources/assets/mapwriter/textures/map/arrow_north.png differ diff --git a/src/main/resources/assets/mapwriter/textures/map/arrow_player.png b/src/main/resources/assets/mapwriter/textures/map/arrow_player.png new file mode 100644 index 0000000..4767437 Binary files /dev/null and b/src/main/resources/assets/mapwriter/textures/map/arrow_player.png differ diff --git a/src/main/resources/assets/mapwriter/textures/map/background.png b/src/main/resources/assets/mapwriter/textures/map/background.png new file mode 100644 index 0000000..e67bcd3 Binary files /dev/null and b/src/main/resources/assets/mapwriter/textures/map/background.png differ diff --git a/src/main/resources/assets/mapwriter/textures/map/border_round.png b/src/main/resources/assets/mapwriter/textures/map/border_round.png new file mode 100644 index 0000000..d4b4b07 Binary files /dev/null and b/src/main/resources/assets/mapwriter/textures/map/border_round.png differ diff --git a/src/main/resources/assets/mapwriter/textures/map/border_square.png b/src/main/resources/assets/mapwriter/textures/map/border_square.png new file mode 100644 index 0000000..092e583 Binary files /dev/null and b/src/main/resources/assets/mapwriter/textures/map/border_square.png differ diff --git a/src/main/resources/mobius_at.cfg b/src/main/resources/mobius_at.cfg index 664cd27..412e244 100644 --- a/src/main/resources/mobius_at.cfg +++ b/src/main/resources/mobius_at.cfg @@ -1,12 +1,2 @@ -public cpw.mods.fml.common.SingleIntervalHandler.wrapped -public mi.a -public mi.b -public mi.c -public mi.d -public mi.e -public mi.f -public mi.g -public mi.h -public mi.i -public mi.b(Laoj;)V -public mi.a(Laoj;)V \ No newline at end of file +public net.minecraft.world.gen.ChunkProviderServer field_73245_g +public net.minecraft.world.World field_72993_I \ No newline at end of file