From 612733ff255028a03ce4886edd280eda5b27f472 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 6 Jun 2017 01:12:19 +0100 Subject: [PATCH 01/89] Cheapen the pulsar recipe. --- common/buildcraft/transport/BCTransportRecipes.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/common/buildcraft/transport/BCTransportRecipes.java b/common/buildcraft/transport/BCTransportRecipes.java index 805c8f2ce0..03a38f4646 100644 --- a/common/buildcraft/transport/BCTransportRecipes.java +++ b/common/buildcraft/transport/BCTransportRecipes.java @@ -114,16 +114,17 @@ public static void init() { if (BCTransportItems.plugPulsar != null) { RecipeBuilderShaped builder = new RecipeBuilderShaped(); - builder.add("rer"); - builder.add("gpg"); + builder.add(" e "); + builder.add("rpr"); + builder.add(" l "); if (BCCoreBlocks.engine != null && BCCoreBlocks.engine.isRegistered(EnumEngineType.WOOD)) { builder.map('e', BCCoreBlocks.engine.getStack(EnumEngineType.WOOD)); } else { builder.map('e', Blocks.REDSTONE_BLOCK); } builder.map('p', BCTransportItems.plugBlocker, Blocks.COBBLESTONE); - builder.map('g', "gearIron"); builder.map('r', "dustRedstone"); + builder.map('l', Blocks.LEVER); builder.setResult(new ItemStack(BCTransportItems.plugPulsar)); builder.register(); } From 37c5f96dbe252672e0f091e0b8a434e092c5e747 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Tue, 6 Jun 2017 20:26:42 +0300 Subject: [PATCH 02/89] Fix #3177 --- BuildCraftAPI | 2 +- common/buildcraft/builders/BCBuilders.java | 2 + .../builders/BCBuildersRegistries.java | 22 +++++++++ .../builders/snapshot/SnapshotBuilder.java | 9 ++-- .../builders/snapshot/TemplateBuilder.java | 26 +++++----- .../snapshot/TemplateHandlerDefault.java | 34 +++++++++++++ .../builders/snapshot/TemplateRegistry.java | 49 +++++++++++++++++++ .../buildcraft/builders/tile/TileQuarry.java | 4 +- .../factory/tile/TileMiningWell.java | 4 +- common/buildcraft/lib/BCLibEventDist.java | 4 +- common/buildcraft/lib/BCLibRegistries.java | 4 +- .../lib/list/ListMatchHandlerArmor.java | 4 +- common/buildcraft/lib/misc/BlockUtil.java | 11 +++-- ...layerUtil.java => FakePlayerProvider.java} | 17 ++++--- .../transport/BCTransportRegistries.java | 12 ++--- .../transport/pipe/StripesRegistry.java | 26 +++------- .../pipe/behaviour/PipeBehaviourStripes.java | 10 ++-- .../transport/plug/FacadeStateManager.java | 4 +- 18 files changed, 171 insertions(+), 73 deletions(-) create mode 100644 common/buildcraft/builders/BCBuildersRegistries.java create mode 100644 common/buildcraft/builders/snapshot/TemplateHandlerDefault.java create mode 100644 common/buildcraft/builders/snapshot/TemplateRegistry.java rename common/buildcraft/lib/misc/{FakePlayerUtil.java => FakePlayerProvider.java} (71%) diff --git a/BuildCraftAPI b/BuildCraftAPI index f154d3096a..550ef59001 160000 --- a/BuildCraftAPI +++ b/BuildCraftAPI @@ -1 +1 @@ -Subproject commit f154d3096a38472419d92683913890314e609357 +Subproject commit 550ef59001df7444a53a03097d28e8b5babae3f0 diff --git a/common/buildcraft/builders/BCBuilders.java b/common/buildcraft/builders/BCBuilders.java index 4520d137ae..74f3d19de9 100644 --- a/common/buildcraft/builders/BCBuilders.java +++ b/common/buildcraft/builders/BCBuilders.java @@ -55,6 +55,7 @@ public class BCBuilders { public static void preInit(FMLPreInitializationEvent evt) { RegistryHelper.useOtherModConfigFor(MODID, BCCore.MODID); + BCBuildersRegistries.preInit(); BCBuildersItems.preInit(); BCBuildersBlocks.preInit(); @@ -98,6 +99,7 @@ public static void preInit(FMLPreInitializationEvent evt) { @Mod.EventHandler public static void init(FMLInitializationEvent evt) { BCBuildersProxy.getProxy().fmlInit(); + BCBuildersRegistries.init(); BCBuildersRecipes.init(); } diff --git a/common/buildcraft/builders/BCBuildersRegistries.java b/common/buildcraft/builders/BCBuildersRegistries.java new file mode 100644 index 0000000000..6fdf1f64d4 --- /dev/null +++ b/common/buildcraft/builders/BCBuildersRegistries.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.builders; + +import buildcraft.api.template.TemplateApi; + +import buildcraft.builders.snapshot.TemplateHandlerDefault; +import buildcraft.builders.snapshot.TemplateRegistry; + +public class BCBuildersRegistries { + public static void preInit() { + TemplateApi.templateRegistry = TemplateRegistry.INSTANCE; + } + + public static void init() { + TemplateApi.templateRegistry.addHandler(TemplateHandlerDefault.INSTANCE); + } +} diff --git a/common/buildcraft/builders/snapshot/SnapshotBuilder.java b/common/buildcraft/builders/snapshot/SnapshotBuilder.java index 7c3e2881bc..05d9010e50 100644 --- a/common/buildcraft/builders/snapshot/SnapshotBuilder.java +++ b/common/buildcraft/builders/snapshot/SnapshotBuilder.java @@ -25,10 +25,11 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.BlockEvent; +import buildcraft.api.core.BuildCraftAPI; import buildcraft.api.mj.MjAPI; import buildcraft.lib.misc.BlockUtil; -import buildcraft.lib.misc.FakePlayerUtil; +import buildcraft.lib.misc.FakePlayerProvider; import buildcraft.lib.misc.MessageUtil; import buildcraft.lib.misc.data.Box; import buildcraft.lib.net.PacketBufferBC; @@ -205,10 +206,10 @@ public boolean tick() { tile.getWorldBC(), breakTask.pos, tile.getWorldBC().getBlockState(breakTask.pos), - FakePlayerUtil.INSTANCE.getFakePlayer( + BuildCraftAPI.fakePlayerProvider.getFakePlayer( (WorldServer) tile.getWorldBC(), - tile.getBuilderPos(), - tile.getOwner() + tile.getOwner(), + tile.getBuilderPos() ) ); MinecraftForge.EVENT_BUS.post(breakEvent); diff --git a/common/buildcraft/builders/snapshot/TemplateBuilder.java b/common/buildcraft/builders/snapshot/TemplateBuilder.java index 3744e53054..b922d6ba1e 100644 --- a/common/buildcraft/builders/snapshot/TemplateBuilder.java +++ b/common/buildcraft/builders/snapshot/TemplateBuilder.java @@ -11,13 +11,14 @@ import java.util.Optional; import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldServer; -import buildcraft.lib.fake.FakePlayerBC; -import buildcraft.lib.misc.FakePlayerUtil; +import net.minecraftforge.common.util.FakePlayer; + +import buildcraft.api.core.BuildCraftAPI; +import buildcraft.api.template.TemplateApi; + import buildcraft.lib.misc.data.Box; public class TemplateBuilder extends SnapshotBuilder { @@ -55,23 +56,18 @@ protected List getToPlaceItems(BlockPos blockPos) { @Override protected boolean doPlaceTask(PlaceTask placeTask) { - FakePlayerBC fakePlayer = FakePlayerUtil.INSTANCE.getFakePlayer( + FakePlayer fakePlayer = BuildCraftAPI.fakePlayerProvider.getFakePlayer( (WorldServer) tile.getWorldBC(), - tile.getBuilderPos(), - tile.getOwner() + tile.getOwner(), + tile.getBuilderPos() ); fakePlayer.setHeldItem(fakePlayer.getActiveHand(), placeTask.items.get(0)); - EnumActionResult result = placeTask.items.get(0).onItemUse( - fakePlayer, + return TemplateApi.templateRegistry.handle( tile.getWorldBC(), placeTask.pos, - fakePlayer.getActiveHand(), - EnumFacing.UP, - 0.5F, - 0.0F, - 0.5F + fakePlayer, + placeTask.items.get(0) ); - return result == EnumActionResult.SUCCESS; } @Override diff --git a/common/buildcraft/builders/snapshot/TemplateHandlerDefault.java b/common/buildcraft/builders/snapshot/TemplateHandlerDefault.java new file mode 100644 index 0000000000..93cd9298d3 --- /dev/null +++ b/common/buildcraft/builders/snapshot/TemplateHandlerDefault.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.builders.snapshot; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +import buildcraft.api.template.ITemplateHandler; + +public enum TemplateHandlerDefault implements ITemplateHandler { + INSTANCE; + + @Override + public boolean handle(World world, BlockPos pos, EntityPlayer player, ItemStack stack) { + return stack.onItemUse( + player, + world, + pos, + player.getActiveHand(), + EnumFacing.UP, + 0.5F, + 0.0F, + 0.5F + ) == EnumActionResult.SUCCESS; + } +} diff --git a/common/buildcraft/builders/snapshot/TemplateRegistry.java b/common/buildcraft/builders/snapshot/TemplateRegistry.java new file mode 100644 index 0000000000..08c0010f3d --- /dev/null +++ b/common/buildcraft/builders/snapshot/TemplateRegistry.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.builders.snapshot; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +import buildcraft.api.core.EnumHandlerPriority; +import buildcraft.api.template.ITemplateHandler; +import buildcraft.api.template.ITemplateRegistry; + +public enum TemplateRegistry implements ITemplateRegistry { + INSTANCE; + + private final EnumMap> handlers = new EnumMap<>(EnumHandlerPriority.class); + + TemplateRegistry() { + for (EnumHandlerPriority priority : EnumHandlerPriority.VALUES) { + handlers.put(priority, new ArrayList<>()); + } + } + + @Override + public void addHandler(ITemplateHandler handler, EnumHandlerPriority priority) { + handlers.get(priority).add(handler); + } + + @Override + public boolean handle(World world, BlockPos pos, EntityPlayer player, ItemStack stack) { + for (EnumHandlerPriority priority : EnumHandlerPriority.VALUES) { + for (ITemplateHandler handler : handlers.get(priority)) { + if (handler.handle(world, pos, player, stack)) { + return true; + } + } + } + return false; + } +} diff --git a/common/buildcraft/builders/tile/TileQuarry.java b/common/buildcraft/builders/tile/TileQuarry.java index 8b6dadb749..9622e24eed 100644 --- a/common/buildcraft/builders/tile/TileQuarry.java +++ b/common/buildcraft/builders/tile/TileQuarry.java @@ -44,6 +44,7 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import buildcraft.api.core.BuildCraftAPI; import buildcraft.api.core.EnumPipePart; import buildcraft.api.core.IAreaProvider; import buildcraft.api.mj.MjAPI; @@ -58,7 +59,6 @@ import buildcraft.lib.misc.BlockUtil; import buildcraft.lib.misc.BoundingBoxUtil; import buildcraft.lib.misc.CapUtil; -import buildcraft.lib.misc.FakePlayerUtil; import buildcraft.lib.misc.InventoryUtil; import buildcraft.lib.misc.LocaleUtil; import buildcraft.lib.misc.MessageUtil; @@ -630,7 +630,7 @@ protected boolean onReceivePower() { @Override protected boolean finish() { - EntityPlayer fake = FakePlayerUtil.INSTANCE.getFakePlayer((WorldServer) world, pos, getOwner()); + EntityPlayer fake = BuildCraftAPI.fakePlayerProvider.getFakePlayer((WorldServer) world, getOwner(), pos); IBlockState state = world.getBlockState(breakPos); if (state.getBlockHardness(world, breakPos) < 0) { diff --git a/common/buildcraft/factory/tile/TileMiningWell.java b/common/buildcraft/factory/tile/TileMiningWell.java index f8abfd25a0..40e2ccc110 100644 --- a/common/buildcraft/factory/tile/TileMiningWell.java +++ b/common/buildcraft/factory/tile/TileMiningWell.java @@ -14,13 +14,13 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.BlockEvent; +import buildcraft.api.core.BuildCraftAPI; import buildcraft.api.core.EnumPipePart; import buildcraft.api.mj.IMjReceiver; import buildcraft.lib.inventory.AutomaticProvidingTransactor; import buildcraft.lib.misc.BlockUtil; import buildcraft.lib.misc.CapUtil; -import buildcraft.lib.misc.FakePlayerUtil; import buildcraft.lib.misc.InventoryUtil; import buildcraft.lib.mj.MjBatteryReciver; @@ -39,7 +39,7 @@ protected void mine() { progress += battery.extractPower(0, target - progress); if (progress >= target) { progress = 0; - EntityPlayer fakePlayer = FakePlayerUtil.INSTANCE.getFakePlayer((WorldServer) world, pos, getOwner()); + EntityPlayer fakePlayer = BuildCraftAPI.fakePlayerProvider.getFakePlayer((WorldServer) world, getOwner(), pos); BlockEvent.BreakEvent breakEvent = new BlockEvent.BreakEvent(world, currentPos, world.getBlockState(currentPos), fakePlayer); MinecraftForge.EVENT_BUS.post(breakEvent); if (!breakEvent.isCanceled()) { diff --git a/common/buildcraft/lib/BCLibEventDist.java b/common/buildcraft/lib/BCLibEventDist.java index 8652df935f..f9b1259f4a 100644 --- a/common/buildcraft/lib/BCLibEventDist.java +++ b/common/buildcraft/lib/BCLibEventDist.java @@ -39,7 +39,7 @@ import buildcraft.lib.client.sprite.SpriteHolderRegistry; import buildcraft.lib.debug.BCAdvDebugging; import buildcraft.lib.marker.MarkerCache; -import buildcraft.lib.misc.FakePlayerUtil; +import buildcraft.lib.misc.FakePlayerProvider; import buildcraft.lib.misc.MessageUtil; import buildcraft.lib.misc.data.ModelVariableData; import buildcraft.lib.net.cache.BuildCraftObjectCaches; @@ -61,7 +61,7 @@ public void onEntityJoinWorld(EntityJoinWorldEvent event) { public void onWorldUnload(WorldEvent.Unload event) { MarkerCache.onWorldUnload(event.getWorld()); if (event.getWorld() instanceof WorldServer) { - FakePlayerUtil.INSTANCE.unloadWorld((WorldServer) event.getWorld()); + FakePlayerProvider.INSTANCE.unloadWorld((WorldServer) event.getWorld()); } } diff --git a/common/buildcraft/lib/BCLibRegistries.java b/common/buildcraft/lib/BCLibRegistries.java index ed463fbafb..b910403248 100644 --- a/common/buildcraft/lib/BCLibRegistries.java +++ b/common/buildcraft/lib/BCLibRegistries.java @@ -15,7 +15,7 @@ import buildcraft.lib.crops.CropHandlerReeds; import buildcraft.lib.fluid.CoolantRegistry; import buildcraft.lib.fluid.FuelRegistry; -import buildcraft.lib.misc.FakePlayerUtil; +import buildcraft.lib.misc.FakePlayerProvider; import buildcraft.lib.recipe.AssemblyRecipeRegistry; import buildcraft.lib.recipe.IntegrationRecipeRegistry; import buildcraft.lib.recipe.RefineryRecipeRegistry; @@ -27,7 +27,7 @@ public static void fmlPreInit() { BuildcraftRecipeRegistry.refineryRecipes = RefineryRecipeRegistry.INSTANCE; BuildcraftFuelRegistry.fuel = FuelRegistry.INSTANCE; BuildcraftFuelRegistry.coolant = CoolantRegistry.INSTANCE; - BuildCraftAPI.fakePlayerProvider = FakePlayerUtil.INSTANCE; + BuildCraftAPI.fakePlayerProvider = FakePlayerProvider.INSTANCE; CropManager.setDefaultHandler(CropHandlerPlantable.INSTANCE); CropManager.registerHandler(CropHandlerReeds.INSTANCE); diff --git a/common/buildcraft/lib/list/ListMatchHandlerArmor.java b/common/buildcraft/lib/list/ListMatchHandlerArmor.java index 2de179c3dd..9d6ff61367 100644 --- a/common/buildcraft/lib/list/ListMatchHandlerArmor.java +++ b/common/buildcraft/lib/list/ListMatchHandlerArmor.java @@ -16,16 +16,16 @@ import net.minecraftforge.common.DimensionManager; +import buildcraft.api.core.BuildCraftAPI; import buildcraft.api.lists.ListMatchHandler; import buildcraft.lib.BCLibProxy; -import buildcraft.lib.misc.FakePlayerUtil; public class ListMatchHandlerArmor extends ListMatchHandler { private static EnumSet getArmorTypes(ItemStack stack) { EntityPlayer player = BCLibProxy.getProxy().getClientPlayer(); if (player == null) { - player = FakePlayerUtil.INSTANCE.getBuildCraftPlayer(DimensionManager.getWorld(0)); + player = BuildCraftAPI.fakePlayerProvider.getBuildCraftPlayer(DimensionManager.getWorld(0)); } EnumSet types = EnumSet.noneOf(EntityEquipmentSlot.class); diff --git a/common/buildcraft/lib/misc/BlockUtil.java b/common/buildcraft/lib/misc/BlockUtil.java index 7f84b31ef9..bb7da0826e 100644 --- a/common/buildcraft/lib/misc/BlockUtil.java +++ b/common/buildcraft/lib/misc/BlockUtil.java @@ -57,6 +57,7 @@ import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fml.common.FMLCommonHandler; +import buildcraft.api.core.BuildCraftAPI; import buildcraft.api.mj.MjAPI; import buildcraft.lib.BCLibConfig; @@ -71,7 +72,7 @@ public static NonNullList getItemStackFromBlock(WorldServer world, Bl } List dropsList = block.getDrops(world, pos, state, 0); - EntityPlayer fakePlayer = FakePlayerUtil.INSTANCE.getFakePlayer(world, pos, owner); + EntityPlayer fakePlayer = BuildCraftAPI.fakePlayerProvider.getFakePlayer(world, owner, pos); float dropChance = ForgeEventFactory.fireBlockHarvesting(dropsList, world, pos, state, 0, 1.0F, false, fakePlayer); NonNullList returnList = NonNullList.create(); @@ -101,7 +102,7 @@ public static boolean breakBlock(WorldServer world, BlockPos pos, int forcedLife } public static boolean harvestBlock(WorldServer world, BlockPos pos, @Nonnull ItemStack tool, BlockPos ownerPos, GameProfile owner) { - FakePlayer fakePlayer = FakePlayerUtil.INSTANCE.getFakePlayer(world, ownerPos, owner); + FakePlayer fakePlayer = BuildCraftAPI.fakePlayerProvider.getFakePlayer(world, owner, ownerPos); BreakEvent breakEvent = new BreakEvent(world, pos, world.getBlockState(pos), fakePlayer); MinecraftForge.EVENT_BUS.post(breakEvent); @@ -123,7 +124,7 @@ public static boolean harvestBlock(WorldServer world, BlockPos pos, @Nonnull Ite } public static FakePlayer getFakePlayerWithTool(WorldServer world, @Nonnull ItemStack tool, GameProfile owner) { - FakePlayer player = FakePlayerUtil.INSTANCE.getFakePlayer(world, owner); + FakePlayer player = BuildCraftAPI.fakePlayerProvider.getFakePlayer(world, owner); int i = 0; while (player.getHeldItemMainhand() != tool && i < 9) { @@ -139,7 +140,7 @@ public static FakePlayer getFakePlayerWithTool(WorldServer world, @Nonnull ItemS } public static boolean breakBlock(WorldServer world, BlockPos pos, NonNullList drops, BlockPos ownerPos, GameProfile owner) { - FakePlayer fakePlayer = FakePlayerUtil.INSTANCE.getFakePlayer(world, ownerPos, owner); + FakePlayer fakePlayer = BuildCraftAPI.fakePlayerProvider.getFakePlayer(world, owner, ownerPos); BreakEvent breakEvent = new BreakEvent(world, pos, world.getBlockState(pos), fakePlayer); MinecraftForge.EVENT_BUS.post(breakEvent); @@ -198,7 +199,7 @@ public static boolean canChangeBlock(IBlockState state, World world, BlockPos po public static float getBlockHardnessMining(World world, BlockPos pos, IBlockState state, GameProfile owner) { if (world instanceof WorldServer) { - EntityPlayer fakePlayer = FakePlayerUtil.INSTANCE.getFakePlayer((WorldServer) world, owner); + EntityPlayer fakePlayer = BuildCraftAPI.fakePlayerProvider.getFakePlayer((WorldServer) world, owner); float relativeHardness = state.getPlayerRelativeBlockHardness(fakePlayer, world, pos); if (relativeHardness <= 0.0F) { // Forge's getPlayerRelativeBlockHardness hook returns 0.0F if the hardness is < 0.0F. diff --git a/common/buildcraft/lib/misc/FakePlayerUtil.java b/common/buildcraft/lib/misc/FakePlayerProvider.java similarity index 71% rename from common/buildcraft/lib/misc/FakePlayerUtil.java rename to common/buildcraft/lib/misc/FakePlayerProvider.java index 91fa72d5b1..ebade57980 100644 --- a/common/buildcraft/lib/misc/FakePlayerUtil.java +++ b/common/buildcraft/lib/misc/FakePlayerProvider.java @@ -15,30 +15,33 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldServer; -import buildcraft.api.core.IBCFakePlayer; +import buildcraft.api.core.IFakePlayerProvider; import buildcraft.lib.fake.FakePlayerBC; -public enum FakePlayerUtil implements IBCFakePlayer { +public enum FakePlayerProvider implements IFakePlayerProvider { INSTANCE; private final Map players = new HashMap<>(); - @Deprecated - public final GameProfile gameProfile = new GameProfile(UUID.nameUUIDFromBytes("buildcraft.core".getBytes()), "[BuildCraft]"); + private final GameProfile gameProfile = new GameProfile( + UUID.nameUUIDFromBytes("buildcraft.core".getBytes()), + "[BuildCraft]" + ); @Override @Deprecated public FakePlayerBC getBuildCraftPlayer(WorldServer world) { - return getFakePlayer(world, BlockPos.ORIGIN, gameProfile); + return getFakePlayer(world, gameProfile, BlockPos.ORIGIN); } @Override public FakePlayerBC getFakePlayer(WorldServer world, GameProfile profile) { - return getFakePlayer(world, BlockPos.ORIGIN, profile); + return getFakePlayer(world, profile, BlockPos.ORIGIN); } - public FakePlayerBC getFakePlayer(WorldServer world, BlockPos pos, GameProfile profile) { + @Override + public FakePlayerBC getFakePlayer(WorldServer world, GameProfile profile, BlockPos pos) { players.computeIfAbsent(profile, p -> new FakePlayerBC(world, profile)); FakePlayerBC player = players.get(profile); player.world = world; diff --git a/common/buildcraft/transport/BCTransportRegistries.java b/common/buildcraft/transport/BCTransportRegistries.java index 3cc47e5fff..c42ab98c4a 100644 --- a/common/buildcraft/transport/BCTransportRegistries.java +++ b/common/buildcraft/transport/BCTransportRegistries.java @@ -12,7 +12,7 @@ import net.minecraft.item.ItemMinecart; import net.minecraft.util.EnumFacing; -import buildcraft.api.transport.IStripesRegistry.HandlerPriority; +import buildcraft.api.core.EnumHandlerPriority; import buildcraft.api.transport.pipe.ICustomPipeConnection; import buildcraft.api.transport.pipe.PipeApi; import buildcraft.api.transport.pipe.PipeConnectionAPI; @@ -57,12 +57,12 @@ public static void init() { PipeApi.stripeRegistry.addHandler(StripesHandlerShears.INSTANCE); // PipeApi.stripeRegistry.addHandler(new StripesHandlerPipes()); // PipeApi.stripeRegistry.addHandler(new StripesHandlerPipeWires()); - PipeApi.stripeRegistry.addHandler(StripesHandlerEntityInteract.INSTANCE, HandlerPriority.LOW); + PipeApi.stripeRegistry.addHandler(StripesHandlerEntityInteract.INSTANCE, EnumHandlerPriority.LOW); PipeApi.stripeRegistry.addHandler(StripesHandlerHoe.INSTANCE); - // PipeApi.stripeRegistry.addHandler(new StripesHandlerRightClick(), HandlerPriority.LOW); - PipeApi.stripeRegistry.addHandler(StripesHandlerDispenser.INSTANCE, HandlerPriority.LOW); - PipeApi.stripeRegistry.addHandler(StripesHandlerPlaceBlock.INSTANCE, HandlerPriority.LOW); - PipeApi.stripeRegistry.addHandler(StripesHandlerUse.INSTANCE, HandlerPriority.LOW); + // PipeApi.stripeRegistry.addHandler(new StripesHandlerRightClick(), EnumHandlerPriority.LOW); + PipeApi.stripeRegistry.addHandler(StripesHandlerDispenser.INSTANCE, EnumHandlerPriority.LOW); + PipeApi.stripeRegistry.addHandler(StripesHandlerPlaceBlock.INSTANCE, EnumHandlerPriority.LOW); + PipeApi.stripeRegistry.addHandler(StripesHandlerUse.INSTANCE, EnumHandlerPriority.LOW); StripesHandlerDispenser.ITEM_CLASSES.add(ItemBucket.class); StripesHandlerDispenser.ITEM_CLASSES.add(ItemMinecart.class); diff --git a/common/buildcraft/transport/pipe/StripesRegistry.java b/common/buildcraft/transport/pipe/StripesRegistry.java index 2befbad4d4..86f77bd0a5 100644 --- a/common/buildcraft/transport/pipe/StripesRegistry.java +++ b/common/buildcraft/transport/pipe/StripesRegistry.java @@ -16,6 +16,7 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import buildcraft.api.core.EnumHandlerPriority; import buildcraft.api.transport.IStripesActivator; import buildcraft.api.transport.IStripesHandlerBlock; import buildcraft.api.transport.IStripesHandlerItem; @@ -24,34 +25,23 @@ public enum StripesRegistry implements IStripesRegistry { INSTANCE; - private final HandlerPriority[] PRIORITIES = HandlerPriority.values(); - private final EnumMap> itemHandlers = new EnumMap<>(HandlerPriority.class); - private final EnumMap> blockHandlers = new EnumMap<>(HandlerPriority.class); + private final EnumMap> itemHandlers = new EnumMap<>(EnumHandlerPriority.class); + private final EnumMap> blockHandlers = new EnumMap<>(EnumHandlerPriority.class); StripesRegistry() { - for (HandlerPriority priority : PRIORITIES) { + for (EnumHandlerPriority priority : EnumHandlerPriority.VALUES) { itemHandlers.put(priority, new ArrayList<>()); blockHandlers.put(priority, new ArrayList<>()); } } @Override - public void addHandler(IStripesHandlerItem handler) { - addHandler(handler, HandlerPriority.NORMAL); - } - - @Override - public void addHandler(IStripesHandlerItem handler, HandlerPriority priority) { + public void addHandler(IStripesHandlerItem handler, EnumHandlerPriority priority) { itemHandlers.get(priority).add(handler); } @Override - public void addHandler(IStripesHandlerBlock handler) { - addHandler(handler, HandlerPriority.NORMAL); - } - - @Override - public void addHandler(IStripesHandlerBlock handler, HandlerPriority priority) { + public void addHandler(IStripesHandlerBlock handler, EnumHandlerPriority priority) { blockHandlers.get(priority).add(handler); } @@ -63,7 +53,7 @@ public boolean handleItem(World world, ItemStack stack, EntityPlayer player, IStripesActivator activator) { - for (HandlerPriority priority : PRIORITIES) { + for (EnumHandlerPriority priority : EnumHandlerPriority.VALUES) { for (IStripesHandlerItem handler : itemHandlers.get(priority)) { if (handler.handle(world, pos, direction, stack, player, activator)) { return true; @@ -80,7 +70,7 @@ public boolean handleBlock(World world, EnumFacing direction, EntityPlayer player, IStripesActivator activator) { - for (HandlerPriority priority : PRIORITIES) { + for (EnumHandlerPriority priority : EnumHandlerPriority.VALUES) { for (IStripesHandlerBlock handler : blockHandlers.get(priority)) { if (handler.handle(world, pos, direction, player, activator)) { return true; diff --git a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourStripes.java b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourStripes.java index 1bdc7436dd..69f38c6a8f 100644 --- a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourStripes.java +++ b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourStripes.java @@ -29,6 +29,7 @@ import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; +import buildcraft.api.core.BuildCraftAPI; import buildcraft.api.mj.IMjConnector; import buildcraft.api.mj.IMjRedstoneReceiver; import buildcraft.api.mj.MjAPI; @@ -47,7 +48,6 @@ import buildcraft.api.transport.pluggable.PipePluggable; import buildcraft.lib.misc.BlockUtil; -import buildcraft.lib.misc.FakePlayerUtil; import buildcraft.lib.misc.InventoryUtil; import buildcraft.lib.misc.MessageUtil; import buildcraft.lib.misc.NBTUtilBC; @@ -174,10 +174,10 @@ public void onTick() { world, pos.offset(direction), world.getBlockState(pos.offset(direction)), - FakePlayerUtil.INSTANCE.getFakePlayer( + BuildCraftAPI.fakePlayerProvider.getFakePlayer( (WorldServer) world, - pos, - pipe.getHolder().getOwner() + pipe.getHolder().getOwner(), + pos ) ); MinecraftForge.EVENT_BUS.post(breakEvent); @@ -209,7 +209,7 @@ public void onDrop(PipeEventItem.Drop event) { IPipeHolder holder = pipe.getHolder(); World world = holder.getPipeWorld(); BlockPos pos = holder.getPipePos(); - FakePlayer player = FakePlayerUtil.INSTANCE.getFakePlayer((WorldServer) world, pos, holder.getOwner()); + FakePlayer player = BuildCraftAPI.fakePlayerProvider.getFakePlayer((WorldServer) world, holder.getOwner(), pos); player.inventory.clear(); // set the main hand of the fake player to the stack player.inventory.setInventorySlotContents(player.inventory.currentItem, event.getStack()); diff --git a/common/buildcraft/transport/plug/FacadeStateManager.java b/common/buildcraft/transport/plug/FacadeStateManager.java index 99ffa6d1e0..988606648d 100644 --- a/common/buildcraft/transport/plug/FacadeStateManager.java +++ b/common/buildcraft/transport/plug/FacadeStateManager.java @@ -138,7 +138,7 @@ public static void receiveInterModComms(IMCMessage message) { * {@link #isValidFacadeState(IBlockState)} *
  • OR {@link #STR_SUCCESS} if every state of the block is valid for a facade. * - */ + */ private static String isValidFacadeBlock(Block block) { String disablingMod = disabledBlocks.get(block); if (disablingMod != null) { @@ -162,7 +162,7 @@ private static String isValidFacadeBlock(Block block) { *
  • *
  • OR {@link #STR_SUCCESS} if this state is valid for a facade. * - */ + */ private static String isValidFacadeState(IBlockState state) { if (state.getBlock().hasTileEntity(state)) { return "it has a tile entity"; From 1dd9c4724d2e603a4a1b81af04913da1b320d788 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 6 Jun 2017 18:36:55 +0100 Subject: [PATCH 03/89] Fix API --- BuildCraftAPI | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BuildCraftAPI b/BuildCraftAPI index 550ef59001..c140a9e9f3 160000 --- a/BuildCraftAPI +++ b/BuildCraftAPI @@ -1 +1 @@ -Subproject commit 550ef59001df7444a53a03097d28e8b5babae3f0 +Subproject commit c140a9e9f3d7554250910cc0d7e6b5faeebbf92e From 724f35eda7621d8e2af0df3564f5465658993bec Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 6 Jun 2017 20:14:43 +0100 Subject: [PATCH 04/89] Make the pipe pulsar require the assembly table to be crafted. --- BuildCraftAPI | 2 +- .../transport/BCTransportRecipes.java | 107 +++++++++++------- 2 files changed, 70 insertions(+), 39 deletions(-) diff --git a/BuildCraftAPI b/BuildCraftAPI index c140a9e9f3..94acfa5cc6 160000 --- a/BuildCraftAPI +++ b/BuildCraftAPI @@ -1 +1 @@ -Subproject commit c140a9e9f3d7554250910cc0d7e6b5faeebbf92e +Subproject commit 94acfa5cc6c8481dec6e1c22eed8a39932d30b51 diff --git a/common/buildcraft/transport/BCTransportRecipes.java b/common/buildcraft/transport/BCTransportRecipes.java index 03a38f4646..92f6347dc2 100644 --- a/common/buildcraft/transport/BCTransportRecipes.java +++ b/common/buildcraft/transport/BCTransportRecipes.java @@ -6,6 +6,9 @@ package buildcraft.transport; +import java.util.HashSet; +import java.util.Set; + import com.google.common.collect.ImmutableSet; import net.minecraft.init.Blocks; @@ -19,6 +22,7 @@ import net.minecraftforge.oredict.RecipeSorter; import net.minecraftforge.oredict.ShapelessOreRecipe; +import buildcraft.api.BCBlocks; import buildcraft.api.BCItems; import buildcraft.api.enums.EnumEngineType; import buildcraft.api.enums.EnumRedstoneChipset; @@ -32,6 +36,7 @@ import buildcraft.lib.misc.ColourUtil; import buildcraft.lib.recipe.AssemblyRecipeRegistry; import buildcraft.lib.recipe.NBTAwareShapedOreRecipe; +import buildcraft.lib.recipe.OredictionaryNames; import buildcraft.lib.recipe.RecipeBuilderShaped; import buildcraft.core.BCCoreBlocks; @@ -79,8 +84,10 @@ public static void init() { addPipeRecipe(BCTransportItems.pipeItemIron, "ingotIron"); addPipeRecipe(BCTransportItems.pipeItemGold, "ingotGold"); addPipeRecipe(BCTransportItems.pipeItemClay, Blocks.CLAY); - addPipeRecipe(BCTransportItems.pipeItemSandstone, new ItemStack(Blocks.SANDSTONE, 1, OreDictionary.WILDCARD_VALUE)); - addPipeRecipe(BCTransportItems.pipeItemVoid, new ItemStack(Items.DYE, 1, EnumDyeColor.BLACK.getDyeDamage()), "dustRedstone"); + addPipeRecipe(BCTransportItems.pipeItemSandstone, + new ItemStack(Blocks.SANDSTONE, 1, OreDictionary.WILDCARD_VALUE)); + addPipeRecipe(BCTransportItems.pipeItemVoid, new ItemStack(Items.DYE, 1, EnumDyeColor.BLACK.getDyeDamage()), + "dustRedstone"); addPipeRecipe(BCTransportItems.pipeItemObsidian, Blocks.OBSIDIAN); addPipeRecipe(BCTransportItems.pipeItemDiamond, Items.DIAMOND); addPipeRecipe(BCTransportItems.pipeItemLapis, Blocks.LAPIS_BLOCK); @@ -113,20 +120,32 @@ public static void init() { } if (BCTransportItems.plugPulsar != null) { - RecipeBuilderShaped builder = new RecipeBuilderShaped(); - builder.add(" e "); - builder.add("rpr"); - builder.add(" l "); + ItemStack output = new ItemStack(BCTransportItems.plugPulsar); + + ItemStack redstoneEngine; if (BCCoreBlocks.engine != null && BCCoreBlocks.engine.isRegistered(EnumEngineType.WOOD)) { - builder.map('e', BCCoreBlocks.engine.getStack(EnumEngineType.WOOD)); + redstoneEngine = BCCoreBlocks.engine.getStack(EnumEngineType.WOOD); } else { - builder.map('e', Blocks.REDSTONE_BLOCK); + redstoneEngine = new ItemStack(Blocks.REDSTONE_BLOCK); + } + + if (BCBlocks.SILICON_TABLE_ASSEMBLY != null) { + Set input = new HashSet<>(); + input.add(ArrayStackFilter.definition(redstoneEngine)); + input.add(OreStackFilter.definition(2, "ingotIron")); + AssemblyRecipe recipe = new AssemblyRecipe("plug_pulsar", 1000 * MjAPI.MJ, input, output); + AssemblyRecipeRegistry.INSTANCE.addRecipe(recipe); + } else { + RecipeBuilderShaped builder = new RecipeBuilderShaped(); + builder.add("rer"); + builder.add("gpg"); + builder.map('p', BCTransportItems.plugBlocker, Blocks.COBBLESTONE); + builder.map('r', "dustRedstone"); + builder.map('e', redstoneEngine); + builder.map('g', OredictionaryNames.GEAR_IRON); + builder.setResult(output); + builder.register(); } - builder.map('p', BCTransportItems.plugBlocker, Blocks.COBBLESTONE); - builder.map('r', "dustRedstone"); - builder.map('l', Blocks.LEVER); - builder.setResult(new ItemStack(BCTransportItems.plugPulsar)); - builder.register(); } if (BCTransportItems.plugGate != null) { @@ -150,7 +169,8 @@ public static void init() { makeGateRecipe(builder, EnumGateMaterial.NETHER_BRICK, EnumGateModifier.NO_MODIFIER); // Iron modifier addition - GateVariant variant = new GateVariant(EnumGateLogic.AND, EnumGateMaterial.IRON, EnumGateModifier.NO_MODIFIER); + GateVariant variant = + new GateVariant(EnumGateLogic.AND, EnumGateMaterial.IRON, EnumGateModifier.NO_MODIFIER); ItemStack ironGateBase = BCTransportItems.plugGate.getStack(variant); builder = new RecipeBuilderShaped(); builder.add(" m "); @@ -187,27 +207,36 @@ public static void init() { } StackDefinition lapis = OreStackFilter.definition("gemLapis"); makeGateAssembly(20_000, EnumGateMaterial.IRON, EnumGateModifier.NO_MODIFIER, EnumRedstoneChipset.IRON); - makeGateAssembly(40_000, EnumGateMaterial.NETHER_BRICK, EnumGateModifier.NO_MODIFIER, EnumRedstoneChipset.IRON, ArrayStackFilter.definition(new ItemStack(Blocks.NETHER_BRICK))); + makeGateAssembly(40_000, EnumGateMaterial.NETHER_BRICK, EnumGateModifier.NO_MODIFIER, + EnumRedstoneChipset.IRON, ArrayStackFilter.definition(new ItemStack(Blocks.NETHER_BRICK))); makeGateAssembly(80_000, EnumGateMaterial.GOLD, EnumGateModifier.NO_MODIFIER, EnumRedstoneChipset.GOLD); makeGateModifierAssembly(40_000, EnumGateMaterial.IRON, EnumGateModifier.LAPIS, lapis); - makeGateModifierAssembly(60_000, EnumGateMaterial.IRON, EnumGateModifier.QUARTZ, ArrayStackFilter.definition(EnumRedstoneChipset.QUARTZ.getStack())); - makeGateModifierAssembly(80_000, EnumGateMaterial.IRON, EnumGateModifier.DIAMOND, ArrayStackFilter.definition(EnumRedstoneChipset.DIAMOND.getStack())); + makeGateModifierAssembly(60_000, EnumGateMaterial.IRON, EnumGateModifier.QUARTZ, + ArrayStackFilter.definition(EnumRedstoneChipset.QUARTZ.getStack())); + makeGateModifierAssembly(80_000, EnumGateMaterial.IRON, EnumGateModifier.DIAMOND, + ArrayStackFilter.definition(EnumRedstoneChipset.DIAMOND.getStack())); makeGateModifierAssembly(80_000, EnumGateMaterial.NETHER_BRICK, EnumGateModifier.LAPIS, lapis); - makeGateModifierAssembly(100_000, EnumGateMaterial.NETHER_BRICK, EnumGateModifier.QUARTZ, ArrayStackFilter.definition(EnumRedstoneChipset.QUARTZ.getStack())); - makeGateModifierAssembly(120_000, EnumGateMaterial.NETHER_BRICK, EnumGateModifier.DIAMOND, ArrayStackFilter.definition(EnumRedstoneChipset.DIAMOND.getStack())); + makeGateModifierAssembly(100_000, EnumGateMaterial.NETHER_BRICK, EnumGateModifier.QUARTZ, + ArrayStackFilter.definition(EnumRedstoneChipset.QUARTZ.getStack())); + makeGateModifierAssembly(120_000, EnumGateMaterial.NETHER_BRICK, EnumGateModifier.DIAMOND, + ArrayStackFilter.definition(EnumRedstoneChipset.DIAMOND.getStack())); makeGateModifierAssembly(100_000, EnumGateMaterial.GOLD, EnumGateModifier.LAPIS, lapis); - makeGateModifierAssembly(140_000, EnumGateMaterial.GOLD, EnumGateModifier.QUARTZ, ArrayStackFilter.definition(EnumRedstoneChipset.QUARTZ.getStack())); - makeGateModifierAssembly(180_000, EnumGateMaterial.GOLD, EnumGateModifier.DIAMOND, ArrayStackFilter.definition(EnumRedstoneChipset.DIAMOND.getStack())); + makeGateModifierAssembly(140_000, EnumGateMaterial.GOLD, EnumGateModifier.QUARTZ, + ArrayStackFilter.definition(EnumRedstoneChipset.QUARTZ.getStack())); + makeGateModifierAssembly(180_000, EnumGateMaterial.GOLD, EnumGateModifier.DIAMOND, + ArrayStackFilter.definition(EnumRedstoneChipset.DIAMOND.getStack())); } if (BCTransportItems.wire != null) { for (EnumDyeColor color : ColourUtil.COLOURS) { String name = String.format("wire-%s", color.getUnlocalizedName()); - ImmutableSet input = ImmutableSet.of(OreStackFilter.definition("dustRedstone"), OreStackFilter.definition(ColourUtil.getDyeName(color))); - AssemblyRecipeRegistry.INSTANCE.addRecipe(new AssemblyRecipe(name, 10_000 * MjAPI.MJ, input, new ItemStack(BCTransportItems.wire, 8, color.getMetadata()))); + ImmutableSet input = ImmutableSet.of(OreStackFilter.definition("dustRedstone"), + OreStackFilter.definition(ColourUtil.getDyeName(color))); + AssemblyRecipeRegistry.INSTANCE.addRecipe(new AssemblyRecipe(name, 10_000 * MjAPI.MJ, input, + new ItemStack(BCTransportItems.wire, 8, color.getMetadata()))); } } @@ -228,7 +257,8 @@ public static void init() { StackDefinition glass = OreStackFilter.definition("blockGlass"); ImmutableSet input = ImmutableSet.of(glass); ItemStack output = BCTransportItems.plugLens.getStack(null, false); - AssemblyRecipeRegistry.INSTANCE.addRecipe(new AssemblyRecipe("lens-regular", 500 * MjAPI.MJ, input, output)); + AssemblyRecipeRegistry.INSTANCE + .addRecipe(new AssemblyRecipe("lens-regular", 500 * MjAPI.MJ, input, output)); output = BCTransportItems.plugLens.getStack(null, true); input = ImmutableSet.of(glass, ArrayStackFilter.definition(new ItemStack(Blocks.IRON_BARS))); @@ -236,34 +266,34 @@ public static void init() { } if (BCTransportItems.plugLightSensor != null) { - BuildcraftRecipeRegistry.assemblyRecipes.addRecipe( - new AssemblyRecipe( - "light-sensor", - 500 * MjAPI.MJ, - ImmutableSet.of(ArrayStackFilter.definition(Blocks.DAYLIGHT_DETECTOR)), - new ItemStack(BCTransportItems.plugLightSensor) - ) - ); + BuildcraftRecipeRegistry.assemblyRecipes.addRecipe(new AssemblyRecipe("light-sensor", 500 * MjAPI.MJ, + ImmutableSet.of(ArrayStackFilter.definition(Blocks.DAYLIGHT_DETECTOR)), + new ItemStack(BCTransportItems.plugLightSensor))); } if (BCTransportItems.plugFacade != null) { AssemblyRecipeRegistry.INSTANCE.addRecipeProvider(FacadeAssemblyRecipes.INSTANCE); - RecipeSorter.register("buildcraftlib:facade_swap", FacadeSwapRecipe.class, RecipeSorter.Category.SHAPELESS, "before:minecraft:shapeless"); + RecipeSorter.register("buildcraftlib:facade_swap", FacadeSwapRecipe.class, RecipeSorter.Category.SHAPELESS, + "before:minecraft:shapeless"); GameRegistry.addRecipe(FacadeSwapRecipe.INSTANCE); } } - private static void makeGateModifierAssembly(int multiplier, EnumGateMaterial material, EnumGateModifier modifier, StackDefinition... mods) { + private static void makeGateModifierAssembly(int multiplier, EnumGateMaterial material, EnumGateModifier modifier, + StackDefinition... mods) { for (EnumGateLogic logic : EnumGateLogic.VALUES) { String name = String.format("gate-modifier-%s-%s-%s", logic, material, modifier); - ItemStack toUpgrade = BCTransportItems.plugGate.getStack(new GateVariant(logic, material, EnumGateModifier.NO_MODIFIER)); + ItemStack toUpgrade = + BCTransportItems.plugGate.getStack(new GateVariant(logic, material, EnumGateModifier.NO_MODIFIER)); ItemStack output = BCTransportItems.plugGate.getStack(new GateVariant(logic, material, modifier)); - ImmutableSet input = new ImmutableSet.Builder().add(ArrayStackFilter.definition(toUpgrade)).add(mods).build(); + ImmutableSet input = new ImmutableSet.Builder() + .add(ArrayStackFilter.definition(toUpgrade)).add(mods).build(); AssemblyRecipeRegistry.INSTANCE.addRecipe(new AssemblyRecipe(name, MjAPI.MJ * multiplier, input, output)); } } - private static void makeGateAssembly(int multiplier, EnumGateMaterial material, EnumGateModifier modifier, EnumRedstoneChipset chipset, StackDefinition... additional) { + private static void makeGateAssembly(int multiplier, EnumGateMaterial material, EnumGateModifier modifier, + EnumRedstoneChipset chipset, StackDefinition... additional) { ImmutableSet.Builder temp = ImmutableSet.builder(); temp.add(ArrayStackFilter.definition(chipset.getStack())); temp.add(additional); @@ -278,7 +308,8 @@ private static void makeGateAssembly(int multiplier, EnumGateMaterial material, AssemblyRecipeRegistry.INSTANCE.addRecipe(new AssemblyRecipe(name, MjAPI.MJ * multiplier, input, output)); } - private static void makeGateRecipe(RecipeBuilderShaped builder, EnumGateMaterial material, EnumGateModifier modifier) { + private static void makeGateRecipe(RecipeBuilderShaped builder, EnumGateMaterial material, + EnumGateModifier modifier) { GateVariant variant = new GateVariant(EnumGateLogic.AND, material, modifier); builder.setResult(BCTransportItems.plugGate.getStack(variant)); builder.registerNbtAware(); From cf373e3dd7cb5a21661e99971ac9ad5ef2956693 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Wed, 7 Jun 2017 02:09:54 +0300 Subject: [PATCH 05/89] Attempts to optimize pump --- common/buildcraft/factory/tile/TilePump.java | 103 ++++++++----------- common/buildcraft/lib/misc/BlockUtil.java | 15 ++- 2 files changed, 49 insertions(+), 69 deletions(-) diff --git a/common/buildcraft/factory/tile/TilePump.java b/common/buildcraft/factory/tile/TilePump.java index 9f7373051b..724f77c987 100644 --- a/common/buildcraft/factory/tile/TilePump.java +++ b/common/buildcraft/factory/tile/TilePump.java @@ -13,17 +13,12 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; -import java.util.Optional; import java.util.PriorityQueue; import java.util.Queue; -import java.util.concurrent.TimeUnit; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.google.common.math.IntMath; +import com.google.common.collect.ImmutableList; +import net.minecraft.block.Block; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -50,9 +45,10 @@ public class TilePump extends TileMiner { private final Tank tank = new Tank("tank", 16 * Fluid.BUCKET_VOLUME, this); private boolean queueBuilt = false; private Queue queue = new PriorityQueue<>( - Comparator.comparing(blockPos -> - IntMath.pow(blockPos.getX() - pos.getX(), 2) + IntMath.pow(blockPos.getZ() - pos.getZ(), 2) - ).reversed() + Comparator.comparing(blockPos -> + (blockPos.getX() - pos.getX()) * (blockPos.getX() - pos.getX()) + + (blockPos.getZ() - pos.getZ()) * (blockPos.getZ() - pos.getZ()) + ).reversed() ); private Map> paths = new HashMap<>(); @@ -67,76 +63,63 @@ protected IMjReceiver createMjReceiver() { } private void buildQueue() { + world.profiler.startSection("prepare"); queue.clear(); paths.clear(); List nextPosesToCheck = new ArrayList<>(); - List> nextPaths = new ArrayList<>(); List checkedButFlowingPoses = new ArrayList<>(); - LoadingCache> fluidCache = CacheBuilder.newBuilder() - .expireAfterAccess(10, TimeUnit.SECONDS) - .build(CacheLoader.from(blockPos -> Optional.ofNullable(BlockUtil.getFluidWithFlowing(world, blockPos)))); - int y = pos.getY() - 1; - if (nextPosesToCheck.isEmpty()) { - for (; y >= 0; y--) { - BlockPos posToCheck = new BlockPos(pos.getX(), y, pos.getZ()); - if (fluidCache.getUnchecked(posToCheck).isPresent()) { - if (!queue.contains(posToCheck)) { - nextPosesToCheck.add(posToCheck); - nextPaths.add(new ArrayList<>(Collections.singletonList(posToCheck))); - break; - } - } else if (!world.isAirBlock(posToCheck) && world.getBlockState(posToCheck).getBlock() != BCFactoryBlocks.tube) { + Block block = null; + for (BlockPos posToCheck = pos.down(); posToCheck.getY() > 0; posToCheck = posToCheck.down()) { + if (BlockUtil.getFluidWithFlowing(world, posToCheck) != null) { + if (!queue.contains(posToCheck)) { + block = world.getBlockState(posToCheck).getBlock(); + nextPosesToCheck.add(posToCheck); + paths.put(posToCheck, Collections.singletonList(posToCheck)); break; } + } else if (!world.isAirBlock(posToCheck) && world.getBlockState(posToCheck).getBlock() != BCFactoryBlocks.tube) { + break; } - if (nextPosesToCheck.isEmpty()) { - return; - } } + if (nextPosesToCheck.isEmpty()) { + return; + } + world.profiler.endStartSection("build"); while (!nextPosesToCheck.isEmpty()) { List nextPosesToCheckCopy = new ArrayList<>(nextPosesToCheck); nextPosesToCheck.clear(); - List> nextPathsCopy = new ArrayList<>(nextPaths); - nextPaths.clear(); - int i = 0; for (BlockPos posToCheck : nextPosesToCheckCopy) { - List path = nextPathsCopy.get(i); - if (!queue.contains(posToCheck)) { - if (BlockUtil.getFluid(world, posToCheck) != null) { - queue.add(posToCheck); - paths.put(posToCheck, path); - } else { - checkedButFlowingPoses.add(posToCheck); - } - } - for (EnumFacing side : new EnumFacing[] { - EnumFacing.UP, - EnumFacing.NORTH, - EnumFacing.SOUTH, - EnumFacing.WEST, - EnumFacing.EAST + EnumFacing.UP, + EnumFacing.NORTH, + EnumFacing.SOUTH, + EnumFacing.WEST, + EnumFacing.EAST }) { BlockPos offsetPos = posToCheck.offset(side); if (Math.pow(offsetPos.getX() - pos.getX(), 2) + Math.pow(offsetPos.getZ() - pos.getZ(), 2) > Math.pow(64, 2)) { continue; } - if (fluidCache.getUnchecked(posToCheck).isPresent() - && Objects.equals(fluidCache.getUnchecked(offsetPos), fluidCache.getUnchecked(posToCheck)) - && !queue.contains(offsetPos) - && !checkedButFlowingPoses.contains(offsetPos)) { - List currentPath = new ArrayList<>(path); - currentPath.add(offsetPos); - if (!nextPosesToCheck.contains(offsetPos) && !nextPosesToCheckCopy.contains(offsetPos)) { - nextPosesToCheck.add(offsetPos); - nextPaths.add(currentPath); + if (!queue.contains(offsetPos) && + !checkedButFlowingPoses.contains(offsetPos) && + !nextPosesToCheck.contains(offsetPos) && + !nextPosesToCheckCopy.contains(offsetPos) && + getLocalState(offsetPos).getBlock() == block) { + ImmutableList.Builder pathBuilder = new ImmutableList.Builder<>(); + pathBuilder.addAll(paths.get(posToCheck)); + pathBuilder.add(offsetPos); + paths.put(offsetPos, pathBuilder.build()); + if (true || BlockUtil.getFluid(world, posToCheck) != null) { + queue.add(posToCheck); + } else { + checkedButFlowingPoses.add(posToCheck); } + nextPosesToCheck.add(offsetPos); } } - - i++; } } + world.profiler.endSection(); } private boolean canDrain(BlockPos blockPos) { @@ -189,9 +172,9 @@ public void mine() { if (progress >= target) { FluidStack drain = BlockUtil.drainBlock(world, currentPos, false); if (drain != null && - paths.get(currentPos).stream() - .allMatch(blockPos -> BlockUtil.getFluidWithFlowing(world, blockPos) != null) && - canDrain(currentPos)) { + paths.get(currentPos).stream() + .allMatch(blockPos -> BlockUtil.getFluidWithFlowing(world, blockPos) != null) && + canDrain(currentPos)) { tank.fillInternal(drain, true); progress = 0; int count = 0; diff --git a/common/buildcraft/lib/misc/BlockUtil.java b/common/buildcraft/lib/misc/BlockUtil.java index bb7da0826e..1559106354 100644 --- a/common/buildcraft/lib/misc/BlockUtil.java +++ b/common/buildcraft/lib/misc/BlockUtil.java @@ -246,16 +246,13 @@ public static Fluid getFluid(World world, BlockPos pos) { public static Fluid getFluidWithFlowing(World world, BlockPos pos) { IBlockState blockState = world.getBlockState(pos); Block block = blockState.getBlock(); - Fluid fluid = FluidRegistry.lookupFluidForBlock(block); - if (fluid == null) { - if (block == Blocks.FLOWING_WATER) { - fluid = FluidRegistry.WATER; - } - if (block == Blocks.FLOWING_LAVA) { - fluid = FluidRegistry.LAVA; - } + if (block == Blocks.FLOWING_WATER) { + return FluidRegistry.WATER; } - return fluid; + if (block == Blocks.FLOWING_LAVA) { + return FluidRegistry.LAVA; + } + return FluidRegistry.lookupFluidForBlock(block); } public static Fluid getFluid(Block block) { From 0a60a40bddd80784e17903c690b8972a57b689c4 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Wed, 7 Jun 2017 03:26:18 +0300 Subject: [PATCH 06/89] Actually optimize pump --- common/buildcraft/factory/tile/TilePump.java | 38 ++++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/common/buildcraft/factory/tile/TilePump.java b/common/buildcraft/factory/tile/TilePump.java index 724f77c987..6bcad19d37 100644 --- a/common/buildcraft/factory/tile/TilePump.java +++ b/common/buildcraft/factory/tile/TilePump.java @@ -11,14 +11,15 @@ import java.util.Collections; import java.util.Comparator; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; +import java.util.Set; import com.google.common.collect.ImmutableList; -import net.minecraft.block.Block; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -66,13 +67,13 @@ private void buildQueue() { world.profiler.startSection("prepare"); queue.clear(); paths.clear(); + Set checked = new HashSet<>(); List nextPosesToCheck = new ArrayList<>(); - List checkedButFlowingPoses = new ArrayList<>(); - Block block = null; + Fluid fluid = null; for (BlockPos posToCheck = pos.down(); posToCheck.getY() > 0; posToCheck = posToCheck.down()) { if (BlockUtil.getFluidWithFlowing(world, posToCheck) != null) { if (!queue.contains(posToCheck)) { - block = world.getBlockState(posToCheck).getBlock(); + fluid = BlockUtil.getFluidWithFlowing(world, posToCheck); nextPosesToCheck.add(posToCheck); paths.put(posToCheck, Collections.singletonList(posToCheck)); break; @@ -82,6 +83,7 @@ private void buildQueue() { } } if (nextPosesToCheck.isEmpty()) { + world.profiler.endSection(); return; } world.profiler.endStartSection("build"); @@ -97,24 +99,22 @@ private void buildQueue() { EnumFacing.EAST }) { BlockPos offsetPos = posToCheck.offset(side); - if (Math.pow(offsetPos.getX() - pos.getX(), 2) + Math.pow(offsetPos.getZ() - pos.getZ(), 2) > Math.pow(64, 2)) { + if ((offsetPos.getX() - pos.getX()) * (offsetPos.getX() - pos.getX()) + + (offsetPos.getZ() - pos.getZ()) * (offsetPos.getZ() - pos.getZ()) > 64 * 64) { continue; } - if (!queue.contains(offsetPos) && - !checkedButFlowingPoses.contains(offsetPos) && - !nextPosesToCheck.contains(offsetPos) && - !nextPosesToCheckCopy.contains(offsetPos) && - getLocalState(offsetPos).getBlock() == block) { - ImmutableList.Builder pathBuilder = new ImmutableList.Builder<>(); - pathBuilder.addAll(paths.get(posToCheck)); - pathBuilder.add(offsetPos); - paths.put(offsetPos, pathBuilder.build()); - if (true || BlockUtil.getFluid(world, posToCheck) != null) { - queue.add(posToCheck); - } else { - checkedButFlowingPoses.add(posToCheck); + if (!checked.contains(offsetPos)) { + if (BlockUtil.getFluidWithFlowing(world, offsetPos) == fluid) { + ImmutableList.Builder pathBuilder = new ImmutableList.Builder<>(); + pathBuilder.addAll(paths.get(posToCheck)); + pathBuilder.add(offsetPos); + paths.put(offsetPos, pathBuilder.build()); + if (BlockUtil.getFluid(world, posToCheck) != null) { + queue.add(posToCheck); + } + nextPosesToCheck.add(offsetPos); } - nextPosesToCheck.add(offsetPos); + checked.add(offsetPos); } } } From ba35be204d30d76ad62ab4fcc838654c9fcd3f7f Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Wed, 7 Jun 2017 03:59:19 +0300 Subject: [PATCH 07/89] Fix big number --- common/buildcraft/factory/tile/TilePump.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/common/buildcraft/factory/tile/TilePump.java b/common/buildcraft/factory/tile/TilePump.java index 6bcad19d37..6df59c9a3e 100644 --- a/common/buildcraft/factory/tile/TilePump.java +++ b/common/buildcraft/factory/tile/TilePump.java @@ -32,6 +32,7 @@ import buildcraft.api.core.EnumPipePart; import buildcraft.api.mj.IMjReceiver; +import buildcraft.api.mj.MjAPI; import buildcraft.lib.fluid.Tank; import buildcraft.lib.misc.BlockUtil; @@ -166,7 +167,7 @@ public void mine() { if (tank.isFull()) { return; } - long target = 10000000; + long target = 10 * MjAPI.MJ; if (currentPos != null && paths.containsKey(currentPos)) { progress += battery.extractPower(0, target - progress); if (progress >= target) { From ec81474b32a52226f4836967230d637cd950bd03 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Wed, 7 Jun 2017 14:01:50 +0300 Subject: [PATCH 08/89] Fix gen layers --- .../energy/generation/GenLayerAddOilDesert.java | 9 ++++++--- .../energy/generation/GenLayerAddOilOcean.java | 9 ++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/common/buildcraft/energy/generation/GenLayerAddOilDesert.java b/common/buildcraft/energy/generation/GenLayerAddOilDesert.java index 7dd2025fdb..47a3ed5be1 100644 --- a/common/buildcraft/energy/generation/GenLayerAddOilDesert.java +++ b/common/buildcraft/energy/generation/GenLayerAddOilDesert.java @@ -14,9 +14,11 @@ import net.minecraftforge.common.BiomeDictionary; +import buildcraft.api.core.BCLog; + public class GenLayerAddOilDesert extends GenLayerBiomeReplacer { - protected static final double NOISE_FIELD_SCALE = 0.001; - protected static final double NOISE_FIELD_THRESHOLD = 0.7; + private static final double NOISE_FIELD_SCALE = 0.001; + private static final double NOISE_FIELD_THRESHOLD = 0.7; private static final List REQUIRED_TYPES = Arrays.asList( BiomeDictionary.Type.HOT, @@ -32,7 +34,8 @@ public GenLayerAddOilDesert(long worldSeed, long seed, GenLayer parent) { protected boolean canReplaceBiome(int biomeId) { Biome biome = Biome.getBiomeForId(biomeId); if (biome == null) { - throw new IllegalArgumentException("Couldn't find a biome with an ID of " + biomeId); + BCLog.logger.warn("Couldn't find a biome with an ID of " + biomeId); + return false; } return BiomeDictionary.getTypes(biome).containsAll(REQUIRED_TYPES); } diff --git a/common/buildcraft/energy/generation/GenLayerAddOilOcean.java b/common/buildcraft/energy/generation/GenLayerAddOilOcean.java index e6b9af108a..ba26a72f30 100644 --- a/common/buildcraft/energy/generation/GenLayerAddOilOcean.java +++ b/common/buildcraft/energy/generation/GenLayerAddOilOcean.java @@ -14,9 +14,11 @@ import net.minecraftforge.common.BiomeDictionary; +import buildcraft.api.core.BCLog; + public class GenLayerAddOilOcean extends GenLayerBiomeReplacer { - public static final double NOISE_FIELD_SCALE = 0.0005; - public static final double NOISE_FIELD_THRESHOLD = 0.9; + private static final double NOISE_FIELD_SCALE = 0.0005; + private static final double NOISE_FIELD_THRESHOLD = 0.9; @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") private static final List REQUIRED_TYPES = Arrays.asList( @@ -31,7 +33,8 @@ public GenLayerAddOilOcean(long worldSeed, long seed, GenLayer parent) { protected boolean canReplaceBiome(int biomeId) { Biome biome = Biome.getBiomeForId(biomeId); if (biome == null) { - throw new IllegalArgumentException("Couldn't find a biome with an ID of " + biomeId); + BCLog.logger.warn("Couldn't find a biome with an ID of " + biomeId); + return false; } return BiomeDictionary.getTypes(biome).containsAll(REQUIRED_TYPES); } From fd997bdd420801b579738249b5dbb1701d354b53 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Wed, 7 Jun 2017 15:07:05 +0300 Subject: [PATCH 09/89] Fix pump wrongly queue building --- common/buildcraft/factory/tile/TilePump.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/common/buildcraft/factory/tile/TilePump.java b/common/buildcraft/factory/tile/TilePump.java index 6df59c9a3e..7014cdfb38 100644 --- a/common/buildcraft/factory/tile/TilePump.java +++ b/common/buildcraft/factory/tile/TilePump.java @@ -73,12 +73,13 @@ private void buildQueue() { Fluid fluid = null; for (BlockPos posToCheck = pos.down(); posToCheck.getY() > 0; posToCheck = posToCheck.down()) { if (BlockUtil.getFluidWithFlowing(world, posToCheck) != null) { - if (!queue.contains(posToCheck)) { - fluid = BlockUtil.getFluidWithFlowing(world, posToCheck); - nextPosesToCheck.add(posToCheck); - paths.put(posToCheck, Collections.singletonList(posToCheck)); - break; + fluid = BlockUtil.getFluidWithFlowing(world, posToCheck); + nextPosesToCheck.add(posToCheck); + paths.put(posToCheck, Collections.singletonList(posToCheck)); + if (BlockUtil.getFluid(world, posToCheck) != null) { + queue.add(posToCheck); } + break; } else if (!world.isAirBlock(posToCheck) && world.getBlockState(posToCheck).getBlock() != BCFactoryBlocks.tube) { break; } @@ -110,8 +111,8 @@ private void buildQueue() { pathBuilder.addAll(paths.get(posToCheck)); pathBuilder.add(offsetPos); paths.put(offsetPos, pathBuilder.build()); - if (BlockUtil.getFluid(world, posToCheck) != null) { - queue.add(posToCheck); + if (BlockUtil.getFluid(world, offsetPos) != null) { + queue.add(offsetPos); } nextPosesToCheck.add(offsetPos); } From 4ece0714bb3e6193c3e3e33e0bdb9fab2f65138d Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Wed, 7 Jun 2017 16:27:47 +0100 Subject: [PATCH 10/89] Fix fluid blocks not blocking light --- common/buildcraft/energy/BCEnergyFluids.java | 1 + 1 file changed, 1 insertion(+) diff --git a/common/buildcraft/energy/BCEnergyFluids.java b/common/buildcraft/energy/BCEnergyFluids.java index 75bd96799d..196a7cfcf0 100644 --- a/common/buildcraft/energy/BCEnergyFluids.java +++ b/common/buildcraft/energy/BCEnergyFluids.java @@ -135,6 +135,7 @@ private static BCFluid defineFluid(int[] data, int heat, String name) { FluidManager.register(def, true); BCFluidBlock block = (BCFluidBlock) def.getBlock(); + block.setLightOpacity(3); // Distance that the fluid will travel: 1->16 // Higher heat values travel a little further block.setQuantaPerBlock(baseQuanta + (baseQuanta > 6 ? heat : heat / 2)); From 9ad1a8b9b0c712354eb801cab712fc3749892bde Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Sat, 10 Jun 2017 12:47:18 +0300 Subject: [PATCH 11/89] Remove unsed --- .../builders/snapshot/SchematicBlockDefault.java | 10 ---------- .../buildcraft/transport/pipe/flow/PipeFlowPower.java | 4 +--- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/common/buildcraft/builders/snapshot/SchematicBlockDefault.java b/common/buildcraft/builders/snapshot/SchematicBlockDefault.java index 356e61d2b2..3344ab252f 100644 --- a/common/buildcraft/builders/snapshot/SchematicBlockDefault.java +++ b/common/buildcraft/builders/snapshot/SchematicBlockDefault.java @@ -186,14 +186,6 @@ protected void setCanBeReplacedWithBlocks(SchematicBlockContext context, Set rules) { - } - - @SuppressWarnings({"unused", "WeakerAccess"}) - protected void setRequiredFluids(SchematicBlockContext context, Set rules) { - } - @Override public void init(SchematicBlockContext context) { Set rules = RulesLoader.getRules(context.blockState); @@ -205,8 +197,6 @@ public void init(SchematicBlockContext context) { setPlaceBlock /* */(context, rules); setUpdateBlockOffsets /* */(context, rules); setCanBeReplacedWithBlocks /**/(context, rules); - setRequiredItems /* */(context, rules); - setRequiredFluids /* */(context, rules); } @Override diff --git a/common/buildcraft/transport/pipe/flow/PipeFlowPower.java b/common/buildcraft/transport/pipe/flow/PipeFlowPower.java index 2686a06e8b..41125eda12 100644 --- a/common/buildcraft/transport/pipe/flow/PipeFlowPower.java +++ b/common/buildcraft/transport/pipe/flow/PipeFlowPower.java @@ -327,9 +327,7 @@ private void step() { long now = pipe.getHolder().getPipeWorld().getTotalWorldTime(); if (currentWorldTime != now) { currentWorldTime = now; - for (EnumFacing face : EnumFacing.VALUES) { - sections.get(face).step(); - } + sections.values().forEach(Section::step); } } From a7d2b496a69b81c8e2c563f5630eeb8cb48f3818 Mon Sep 17 00:00:00 2001 From: afdw Date: Sat, 10 Jun 2017 14:51:59 +0300 Subject: [PATCH 12/89] Fix formatting --- .../builders/tile/TileArchitectTable.java | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/common/buildcraft/builders/tile/TileArchitectTable.java b/common/buildcraft/builders/tile/TileArchitectTable.java index 6c3c9045e0..a40c3a8bab 100644 --- a/common/buildcraft/builders/tile/TileArchitectTable.java +++ b/common/buildcraft/builders/tile/TileArchitectTable.java @@ -225,16 +225,21 @@ private void scanSingleBlock() { } private ISchematicBlock readSchematicBlock(BlockPos worldScanPos) { - return SchematicBlockManager.getSchematicBlock(world, pos.offset(world.getBlockState(pos).getValue( - BlockBCBase_Neptune.PROP_FACING).getOpposite()), worldScanPos, world.getBlockState(worldScanPos), world - .getBlockState(worldScanPos).getBlock()); + return SchematicBlockManager.getSchematicBlock( + world, + pos.offset(world.getBlockState(pos).getValue(BlockBCBase_Neptune.PROP_FACING).getOpposite()), + worldScanPos, + world.getBlockState(worldScanPos), + world.getBlockState(worldScanPos).getBlock() + ); } private void scanEntities() { BlockPos basePos = pos.offset(world.getBlockState(pos).getValue(BlockArchitectTable.PROP_FACING).getOpposite()); - world.getEntitiesWithinAABB(Entity.class, box.getBoundingBox()).stream().map(entity -> SchematicEntityManager - .getSchematicEntity(world, basePos, entity)).filter(Objects::nonNull).forEach( - blueprintScannedEntities::add); + world.getEntitiesWithinAABB(Entity.class, box.getBoundingBox()).stream() + .map(entity -> SchematicEntityManager.getSchematicEntity(world, basePos, entity)) + .filter(Objects::nonNull) + .forEach(blueprintScannedEntities::add); } private void finishScanning() { From a13effaa258a557beafaa7cd75be4139578ebb8b Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Thu, 15 Jun 2017 14:59:38 +0100 Subject: [PATCH 13/89] Fix laser recipe. --- common/buildcraft/silicon/BCSiliconRecipes.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/common/buildcraft/silicon/BCSiliconRecipes.java b/common/buildcraft/silicon/BCSiliconRecipes.java index 6e9fa75769..6c1ef8b04d 100644 --- a/common/buildcraft/silicon/BCSiliconRecipes.java +++ b/common/buildcraft/silicon/BCSiliconRecipes.java @@ -36,13 +36,14 @@ public static void init() { if (BCBlocks.SILICON_LASER != null) { RecipeBuilderShaped builder = new RecipeBuilderShaped(); builder.add("rro"); - builder.add("rdo"); + builder.add("rdd"); builder.add("rro"); builder.map('r', "dustRedstone"); builder.map('o', Blocks.OBSIDIAN); builder.map('d', "gemDiamond"); builder.setResult(new ItemStack(BCBlocks.SILICON_LASER)); builder.register(); + builder.registerRotated(); } if (BCItems.SILICON_REDSTONE_CLIPSET != null) { From 3f4b0227677917e6be623adc2e3b7e6ca694bfac Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Mon, 19 Jun 2017 05:24:46 +0300 Subject: [PATCH 14/89] Fix #3678 --- common/buildcraft/core/marker/volume/EnumAddonSlot.java | 9 ++++++++- common/buildcraft/lib/misc/BoundingBoxUtil.java | 9 ++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/common/buildcraft/core/marker/volume/EnumAddonSlot.java b/common/buildcraft/core/marker/volume/EnumAddonSlot.java index cba80acbcb..632af04669 100644 --- a/common/buildcraft/core/marker/volume/EnumAddonSlot.java +++ b/common/buildcraft/core/marker/volume/EnumAddonSlot.java @@ -45,7 +45,14 @@ public AxisAlignedBB getBoundingBox(VolumeBox box) { directions.get(EnumFacing.Axis.Y) == EnumFacing.AxisDirection.POSITIVE ? boxBB.maxY : boxBB.minY, directions.get(EnumFacing.Axis.Z) == EnumFacing.AxisDirection.POSITIVE ? boxBB.maxZ : boxBB.minZ ); - return new AxisAlignedBB(boxOffset, boxOffset).expandXyz(1 / 16D); + return new AxisAlignedBB( + boxOffset.xCoord, + boxOffset.yCoord, + boxOffset.zCoord, + boxOffset.xCoord, + boxOffset.yCoord, + boxOffset.zCoord + ).expandXyz(1 / 16D); } public static Pair getSelectingBoxAndSlot(EntityPlayer player, List boxes) { diff --git a/common/buildcraft/lib/misc/BoundingBoxUtil.java b/common/buildcraft/lib/misc/BoundingBoxUtil.java index e03cd5f3c5..31516b12f0 100644 --- a/common/buildcraft/lib/misc/BoundingBoxUtil.java +++ b/common/buildcraft/lib/misc/BoundingBoxUtil.java @@ -56,7 +56,14 @@ public static AxisAlignedBB makeFrom(Vec3d from, Vec3d to, double radius) { } public static AxisAlignedBB makeAround(Vec3d around, double radius) { - return new AxisAlignedBB(around.subtract(radius, radius, radius), around.addVector(radius, radius, radius)); + return new AxisAlignedBB( + around.xCoord, + around.yCoord, + around.zCoord, + around.xCoord, + around.yCoord, + around.zCoord + ).expandXyz(radius); } public static AxisAlignedBB makeFrom(BlockPos pos, @Nullable IBox box, @Nullable Collection additional) { From 40ddbd7094cec6ee8fa9fcdbcfe753e7be063dcd Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Tue, 20 Jun 2017 07:39:24 +0300 Subject: [PATCH 15/89] Builders optimizations --- .../builders/snapshot/BlueprintBuilder.java | 7 +- .../builders/snapshot/SnapshotBuilder.java | 183 +++++++++++------- .../builders/snapshot/TemplateBuilder.java | 2 +- .../buildcraft/builders/tile/TileBuilder.java | 5 +- 4 files changed, 117 insertions(+), 80 deletions(-) diff --git a/common/buildcraft/builders/snapshot/BlueprintBuilder.java b/common/buildcraft/builders/snapshot/BlueprintBuilder.java index 315766bf02..b9837fb1a1 100644 --- a/common/buildcraft/builders/snapshot/BlueprintBuilder.java +++ b/common/buildcraft/builders/snapshot/BlueprintBuilder.java @@ -127,7 +127,7 @@ protected boolean canPlace(BlockPos blockPos) { .map(blockPos::add) .allMatch(pos -> getBuildingInfo().toPlace.containsKey(pos) - ? isBlockCorrect(pos) + ? checkResults.get(pos) == CheckResult.CORRECT : !getToBreak().contains(pos) || tile.getWorldBC().isAirBlock(pos) ) && !getBuildingInfo().toPlace.get(blockPos).isAir() && @@ -209,7 +209,10 @@ public boolean tick() { remainingDisplayRequired.addAll(StackUtil.mergeSameItems( Stream.concat( getToPlace().stream() - .filter(blockPos -> !isBlockCorrect(blockPos)) + .filter(blockPos -> + checkResults.get(blockPos) != CheckResult.UNKNOWN && + checkResults.get(blockPos) != CheckResult.CORRECT + ) .flatMap(blockPos -> getDisplayRequired( buildingInfo.toPlaceRequiredItems.get(blockPos), diff --git a/common/buildcraft/builders/snapshot/SnapshotBuilder.java b/common/buildcraft/builders/snapshot/SnapshotBuilder.java index 05d9010e50..bc1d06d44f 100644 --- a/common/buildcraft/builders/snapshot/SnapshotBuilder.java +++ b/common/buildcraft/builders/snapshot/SnapshotBuilder.java @@ -8,9 +8,14 @@ import java.io.IOException; import java.util.ArrayDeque; +import java.util.Collections; import java.util.Comparator; +import java.util.Deque; +import java.util.HashMap; import java.util.Iterator; +import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.Queue; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -38,16 +43,18 @@ public abstract class SnapshotBuilder { private static final int MAX_QUEUE_SIZE = 64; protected final T tile; - private Queue breakTasks = new ArrayDeque<>(); - public Queue clientBreakTasks = new ArrayDeque<>(); - public Queue prevClientBreakTasks = new ArrayDeque<>(); - private Queue placeTasks = new ArrayDeque<>(); - public Queue clientPlaceTasks = new ArrayDeque<>(); - public Queue prevClientPlaceTasks = new ArrayDeque<>(); + private final Queue breakTasks = new ArrayDeque<>(); + public final Queue clientBreakTasks = new ArrayDeque<>(); + public final Queue prevClientBreakTasks = new ArrayDeque<>(); + private final Queue placeTasks = new ArrayDeque<>(); + public final Queue clientPlaceTasks = new ArrayDeque<>(); + public final Queue prevClientPlaceTasks = new ArrayDeque<>(); + private final LinkedList toCheck = new LinkedList<>(); + protected final Map checkResults = new HashMap<>(); public Vec3d robotPos = null; public Vec3d prevRobotPos = null; - public int leftToBreak; - public int leftToPlace; + public int leftToBreak = 0; + public int leftToPlace = 0; protected SnapshotBuilder(T tile) { this.tile = tile; @@ -93,6 +100,44 @@ public Vec3d getPlaceTaskItemPos(PlaceTask placeTask) { .add(new Vec3d(0.5, 1, 0.5)); } + public void updateSnapshot() { + toCheck.addAll(getToBreak()); + toCheck.addAll(getToPlace()); + toCheck.sort(Comparator.comparing(blockPos -> + Math.pow(blockPos.getX() - getBox().center().getX(), 2) + + Math.pow(blockPos.getY() - getBox().center().getY(), 2) + + Math.pow(blockPos.getZ() - getBox().center().getZ(), 2) + )); + toCheck.forEach(blockPos -> checkResults.put(blockPos, CheckResult.UNKNOWN)); + } + + public void cancel() { + breakTasks.forEach(breakTask -> + tile.getBattery().addPower( + Math.min(breakTask.getTarget(), tile.getBattery().getCapacity() - tile.getBattery().getStored()), + false + ) + ); + placeTasks.forEach(placeTask -> + tile.getBattery().addPower( + Math.min(placeTask.getTarget(), tile.getBattery().getCapacity() - tile.getBattery().getStored()), + false + ) + ); + breakTasks.clear(); + clientBreakTasks.clear(); + prevClientBreakTasks.clear(); + placeTasks.clear(); + clientPlaceTasks.clear(); + prevClientPlaceTasks.clear(); + toCheck.clear(); + checkResults.clear(); + robotPos = null; + prevRobotPos = null; + leftToBreak = 0; + leftToPlace = 0; + } + /** * @return true is building is finished, false otherwise */ @@ -109,13 +154,17 @@ public boolean tick() { prevRobotPos = robotPos; if (!breakTasks.isEmpty()) { Vec3d newRobotPos = breakTasks.stream() - .map(BreakTask::getPos) + .map(breakTask -> breakTask.pos) .map(Vec3d::new) .reduce(Vec3d.ZERO, Vec3d::add) .scale(1D / breakTasks.size()); newRobotPos = new Vec3d( newRobotPos.xCoord, - breakTasks.stream().map(BreakTask::getPos).mapToDouble(BlockPos::getY).max().orElse(newRobotPos.yCoord), + breakTasks.stream() + .map(breakTask -> breakTask.pos) + .mapToDouble(BlockPos::getY) + .max() + .orElse(newRobotPos.yCoord), newRobotPos.zCoord ); newRobotPos = newRobotPos.add(new Vec3d(0, 3, 0)); @@ -130,21 +179,30 @@ public boolean tick() { return false; } - breakTasks.removeIf(breakTask -> tile.getWorldBC().isAirBlock(breakTask.pos) || isBlockCorrect(breakTask.pos)); - placeTasks.removeIf(placeTask -> isBlockCorrect(placeTask.pos)); + for (int i = 0; i < 10; i++) { + BlockPos blockPos = toCheck.pollFirst(); + check(blockPos); + toCheck.addLast(blockPos); + } + + breakTasks.removeIf(breakTask -> checkResults.get(breakTask.pos) == CheckResult.CORRECT); + placeTasks.removeIf(placeTask -> checkResults.get(placeTask.pos) == CheckResult.CORRECT); boolean isDone = true; if (tile.canExcavate()) { - List blocks = Stream.concat(getToBreak().stream(), getToPlace().stream()) + List blocks = checkResults.keySet().stream() .sorted(Comparator.comparing(blockPos -> Math.pow(blockPos.getX() - getBox().center().getX(), 2) + Math.pow(blockPos.getZ() - getBox().center().getZ(), 2) + 100_000 - Math.abs(blockPos.getY() - tile.getBuilderPos().getY()) * 100_000 )) - .filter(blockPos -> breakTasks.stream().map(BreakTask::getPos).noneMatch(Predicate.isEqual(blockPos))) - .filter(blockPos -> !tile.getWorldBC().isAirBlock(blockPos)) - .filter(blockPos -> !isBlockCorrect(blockPos)) + .filter(blockPos -> checkResults.get(blockPos) == CheckResult.TO_BREAK) + .filter(blockPos -> + breakTasks.stream() + .map(breakTask -> breakTask.pos) + .noneMatch(Predicate.isEqual(blockPos)) + ) .filter(blockPos -> BlockUtil.getFluidWithFlowing(tile.getWorldBC(), blockPos) == null) .collect(Collectors.toList()); leftToBreak = blocks.size(); @@ -163,14 +221,18 @@ public boolean tick() { } { - List blocks = getToPlace().stream() + List blocks = checkResults.keySet().stream() .sorted(Comparator.comparing(blockPos -> 100_000 - (Math.pow(blockPos.getX() - tile.getBuilderPos().getX(), 2) + Math.pow(blockPos.getZ() - tile.getBuilderPos().getZ(), 2)) + Math.abs(blockPos.getY() - tile.getBuilderPos().getY()) * 100_000 )) - .filter(blockPos -> placeTasks.stream().map(PlaceTask::getPos).noneMatch(Predicate.isEqual(blockPos))) - .filter(blockPos -> !isBlockCorrect(blockPos)) + .filter(blockPos -> checkResults.get(blockPos) == CheckResult.TO_PLACE) + .filter(blockPos -> + placeTasks.stream() + .map(placeTask -> placeTask.pos) + .noneMatch(Predicate.isEqual(blockPos)) + ) .filter(this::canPlace) .collect(Collectors.toList()); leftToPlace = blocks.size(); @@ -226,6 +288,7 @@ public boolean tick() { false ); } + check(breakTask.pos); iterator.remove(); } else { tile.getWorldBC().sendBlockBreakProgress( @@ -253,6 +316,7 @@ public boolean tick() { ); cancelPlaceTask(placeTask); } + check(placeTask.pos); iterator.remove(); } } @@ -261,6 +325,25 @@ public boolean tick() { return isDone; } + protected void check(BlockPos blockPos) { + if (getToBreak().contains(blockPos)) { + if (tile.getWorldBC().isAirBlock(blockPos)) { + checkResults.put(blockPos, CheckResult.CORRECT); + } else { + checkResults.put(blockPos, CheckResult.TO_BREAK); + } + } + if (getToPlace().contains(blockPos)) { + if (isBlockCorrect(blockPos)) { + checkResults.put(blockPos, CheckResult.CORRECT); + } else if (tile.getWorldBC().isAirBlock(blockPos)) { + checkResults.put(blockPos, CheckResult.TO_PLACE); + } else { + checkResults.put(blockPos, CheckResult.TO_BREAK); + } + } + } + public void writeToByteBuf(PacketBufferBC buffer) { buffer.writeInt(breakTasks.size()); breakTasks.forEach(breakTask -> breakTask.writePayload(buffer)); @@ -279,21 +362,6 @@ public void readFromByteBuf(PacketBufferBC buffer) { leftToPlace = buffer.readInt(); } - public void cancel() { - breakTasks.forEach(breakTask -> - tile.getBattery().addPower( - Math.min(breakTask.getTarget(), tile.getBattery().getCapacity() - tile.getBattery().getStored()), - false - ) - ); - placeTasks.forEach(placeTask -> - tile.getBattery().addPower( - Math.min(placeTask.getTarget(), tile.getBattery().getCapacity() - tile.getBattery().getStored()), - false - ) - ); - } - public class BreakTask { public BlockPos pos; public long power; @@ -308,22 +376,6 @@ public BreakTask(PacketBufferBC buffer) { power = buffer.readLong(); } - public BlockPos getPos() { - return pos; - } - - public void setPos(BlockPos pos) { - this.pos = pos; - } - - public long getPower() { - return power; - } - - public void setPower(long power) { - this.power = power; - } - public long getTarget() { return BlockUtil.computeBlockBreakPower(tile.getWorldBC(), pos); } @@ -357,30 +409,6 @@ public PlaceTask(PacketBufferBC buffer) { power = buffer.readLong(); } - public BlockPos getPos() { - return pos; - } - - public void setPos(BlockPos pos) { - this.pos = pos; - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } - - public long getPower() { - return power; - } - - public void setPower(long power) { - this.power = power; - } - public long getTarget() { return (long) (Math.sqrt(pos.distanceSq(tile.getBuilderPos())) * 10 * MjAPI.MJ); } @@ -392,4 +420,11 @@ public void writePayload(PacketBufferBC buffer) { buffer.writeLong(power); } } + + protected enum CheckResult { + UNKNOWN, + CORRECT, + TO_BREAK, + TO_PLACE; + } } diff --git a/common/buildcraft/builders/snapshot/TemplateBuilder.java b/common/buildcraft/builders/snapshot/TemplateBuilder.java index b922d6ba1e..b7d41076f0 100644 --- a/common/buildcraft/builders/snapshot/TemplateBuilder.java +++ b/common/buildcraft/builders/snapshot/TemplateBuilder.java @@ -46,7 +46,7 @@ protected List getToPlace() { @Override protected boolean canPlace(BlockPos blockPos) { - return tile.getWorldBC().isAirBlock(blockPos); + return true; } @Override diff --git a/common/buildcraft/builders/tile/TileBuilder.java b/common/buildcraft/builders/tile/TileBuilder.java index 2a70ac250c..adc7322ab5 100644 --- a/common/buildcraft/builders/tile/TileBuilder.java +++ b/common/buildcraft/builders/tile/TileBuilder.java @@ -136,9 +136,7 @@ protected void onSlotChange(IItemHandlerModifiable itemHandler, int slot, @Nonnu } private void updateSnapshot() { - if (getBuilder() != null) { - getBuilder().cancel(); - } + Optional.ofNullable(getBuilder()).ifPresent(SnapshotBuilder::cancel); if (snapshot != null && getCurrentBasePos() != null) { snapshotType = snapshot.getType(); EnumFacing facing = world.getBlockState(pos).getValue(BlockBCBase_Neptune.PROP_FACING); @@ -150,6 +148,7 @@ private void updateSnapshot() { blueprintBuildingInfo = ((Blueprint) snapshot).new BuildingInfo(getCurrentBasePos(), rotation); } currentBox = Optional.ofNullable(getBuilder()).map(SnapshotBuilder::getBox).orElse(null); + Optional.ofNullable(getBuilder()).ifPresent(SnapshotBuilder::updateSnapshot); } else { snapshotType = null; templateBuildingInfo = null; From 878448c3184ef0b135b4bfe6a7cdf69547a7afea Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Tue, 20 Jun 2017 07:56:37 +0300 Subject: [PATCH 16/89] Add block watcher --- .../builders/snapshot/SnapshotBuilder.java | 101 ++++++++++++++++++ .../buildcraft/builders/tile/TileBuilder.java | 14 +++ .../buildcraft/builders/tile/TileFiller.java | 12 +++ 3 files changed, 127 insertions(+) diff --git a/common/buildcraft/builders/snapshot/SnapshotBuilder.java b/common/buildcraft/builders/snapshot/SnapshotBuilder.java index bc1d06d44f..965fe0e367 100644 --- a/common/buildcraft/builders/snapshot/SnapshotBuilder.java +++ b/common/buildcraft/builders/snapshot/SnapshotBuilder.java @@ -22,9 +22,18 @@ import java.util.stream.IntStream; import java.util.stream.Stream; +import javax.annotation.Nullable; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; +import net.minecraft.util.SoundCategory; +import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; +import net.minecraft.world.IWorldEventListener; +import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.MinecraftForge; @@ -43,6 +52,86 @@ public abstract class SnapshotBuilder { private static final int MAX_QUEUE_SIZE = 64; protected final T tile; + private final IWorldEventListener worldEventListener = new IWorldEventListener() { + @Override + public void notifyBlockUpdate(World world, + BlockPos pos, + IBlockState oldState, + IBlockState newState, + int flags) { + if (tile.getBuilder() == SnapshotBuilder.this) { + check(pos); + } + } + + @Override + public void notifyLightSet(BlockPos pos) { + } + + @Override + public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2, int z2) { + } + + @Override + public void playSoundToAllNearExcept(@Nullable EntityPlayer player, + SoundEvent soundIn, + SoundCategory category, + double x, + double y, + double z, + float volume, + float pitch) { + } + + @Override + public void playRecord(SoundEvent soundIn, BlockPos pos) { + } + + @Override + public void spawnParticle(int particleID, + boolean ignoreRange, + double xCoord, + double yCoord, + double zCoord, + double xSpeed, + double ySpeed, + double zSpeed, + int... parameters) { + } + + @Override + public void spawnParticle(int id, + boolean ignoreRange, + boolean p_190570_3_, + double x, + double y, + double z, + double xSpeed, + double ySpeed, + double zSpeed, + int... parameters) { + } + + @Override + public void onEntityAdded(Entity entityIn) { + } + + @Override + public void onEntityRemoved(Entity entityIn) { + } + + @Override + public void broadcastSound(int soundID, BlockPos pos, int data) { + } + + @Override + public void playEvent(EntityPlayer player, int type, BlockPos blockPosIn, int data) { + } + + @Override + public void sendBlockBreakProgress(int breakerId, BlockPos pos, int progress) { + } + }; private final Queue breakTasks = new ArrayDeque<>(); public final Queue clientBreakTasks = new ArrayDeque<>(); public final Queue prevClientBreakTasks = new ArrayDeque<>(); @@ -60,6 +149,18 @@ protected SnapshotBuilder(T tile) { this.tile = tile; } + public void validate() { + if (!tile.getWorldBC().isRemote) { + tile.getWorldBC().addEventListener(worldEventListener); + } + } + + public void invalidate() { + if (!tile.getWorldBC().isRemote) { + tile.getWorldBC().removeEventListener(worldEventListener); + } + } + protected abstract List getToBreak(); protected abstract List getToPlace(); diff --git a/common/buildcraft/builders/tile/TileBuilder.java b/common/buildcraft/builders/tile/TileBuilder.java index adc7322ab5..2386938749 100644 --- a/common/buildcraft/builders/tile/TileBuilder.java +++ b/common/buildcraft/builders/tile/TileBuilder.java @@ -135,6 +135,20 @@ protected void onSlotChange(IItemHandlerModifiable itemHandler, int slot, @Nonnu super.onSlotChange(itemHandler, slot, before, after); } + @Override + public void validate() { + super.validate(); + templateBuilder.validate(); + blueprintBuilder.validate(); + } + + @Override + public void invalidate() { + super.invalidate(); + templateBuilder.invalidate(); + blueprintBuilder.invalidate(); + } + private void updateSnapshot() { Optional.ofNullable(getBuilder()).ifPresent(SnapshotBuilder::cancel); if (snapshot != null && getCurrentBasePos() != null) { diff --git a/common/buildcraft/builders/tile/TileFiller.java b/common/buildcraft/builders/tile/TileFiller.java index 813ec57271..4e27b6e0e9 100644 --- a/common/buildcraft/builders/tile/TileFiller.java +++ b/common/buildcraft/builders/tile/TileFiller.java @@ -112,6 +112,18 @@ public void onPlacedBy(EntityLivingBase placer, ItemStack stack) { } } + @Override + public void validate() { + super.validate(); + builder.validate(); + } + + @Override + public void invalidate() { + super.invalidate(); + builder.invalidate(); + } + @Override public void update() { battery.tick(getWorld(), getPos()); From f1f8fbf40f4492830a51f9eb20cff2750e148d81 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Tue, 20 Jun 2017 08:37:27 +0300 Subject: [PATCH 17/89] Fix unchecked --- common/buildcraft/lib/tile/item/ItemHandlerManager.java | 3 +-- .../transport/pipe/behaviour/PipeBehaviourStripes.java | 7 +++---- common/buildcraft/transport/pipe/flow/PipeFlowFluids.java | 3 +-- common/buildcraft/transport/pipe/flow/PipeFlowItems.java | 5 ++--- common/buildcraft/transport/pipe/flow/PipeFlowPower.java | 5 ++--- 5 files changed, 9 insertions(+), 14 deletions(-) diff --git a/common/buildcraft/lib/tile/item/ItemHandlerManager.java b/common/buildcraft/lib/tile/item/ItemHandlerManager.java index c83f5a6aae..ad6fca26b3 100644 --- a/common/buildcraft/lib/tile/item/ItemHandlerManager.java +++ b/common/buildcraft/lib/tile/item/ItemHandlerManager.java @@ -113,11 +113,10 @@ public boolean hasCapability(@Nonnull Capability capability, EnumFacing facin } @Override - @SuppressWarnings("unchecked") public T getCapability(@Nonnull Capability capability, EnumFacing facing) { if (capability == CapUtil.CAP_ITEMS) { Wrapper wrapper = wrappers.get(EnumPipePart.fromFacing(facing)); - return (T) wrapper.combined; + return CapUtil.CAP_ITEMS.cast(wrapper.combined); } return null; } diff --git a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourStripes.java b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourStripes.java index 69f38c6a8f..c65adc9745 100644 --- a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourStripes.java +++ b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourStripes.java @@ -240,17 +240,16 @@ public boolean sendItem(@Nonnull ItemStack stack, EnumFacing from) { } } - @SuppressWarnings("unchecked") @Override public T getCapability(@Nonnull Capability capability, EnumFacing facing) { if (capability == MjAPI.CAP_REDSTONE_RECEIVER) { - return (T) this; + return MjAPI.CAP_REDSTONE_RECEIVER.cast(this); } if (capability == MjAPI.CAP_RECEIVER) { - return (T) this; + return MjAPI.CAP_RECEIVER.cast(this); } if (capability == MjAPI.CAP_CONNECTOR) { - return (T) this; + return MjAPI.CAP_CONNECTOR.cast(this); } return super.getCapability(capability, facing); } diff --git a/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java b/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java index bd4a211bbb..512d564e56 100644 --- a/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java +++ b/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java @@ -151,11 +151,10 @@ public boolean canConnect(EnumFacing face, TileEntity oTile) { return oTile.hasCapability(CapUtil.CAP_FLUIDS, face.getOpposite()); } - @SuppressWarnings("unchecked") @Override public T getCapability(@Nonnull Capability capability, EnumFacing facing) { if (capability == CapUtil.CAP_FLUIDS) { - return (T) sections.get(EnumPipePart.fromFacing(facing)); + return CapUtil.CAP_FLUIDS.cast(sections.get(EnumPipePart.fromFacing(facing))); } return super.getCapability(capability, facing); } diff --git a/common/buildcraft/transport/pipe/flow/PipeFlowItems.java b/common/buildcraft/transport/pipe/flow/PipeFlowItems.java index afda4cbe3c..aea298434a 100644 --- a/common/buildcraft/transport/pipe/flow/PipeFlowItems.java +++ b/common/buildcraft/transport/pipe/flow/PipeFlowItems.java @@ -168,13 +168,12 @@ public int tryExtractItems(int count, EnumFacing from, EnumDyeColor colour, ISta // PipeFlow - @SuppressWarnings("unchecked") @Override public T getCapability(@Nonnull Capability capability, EnumFacing facing) { if (capability == PipeApi.CAP_INJECTABLE) { - return (T) this; + return PipeApi.CAP_INJECTABLE.cast(this); } else if (capability == CapUtil.CAP_ITEM_TRANSACTOR) { - return (T) ItemTransactorHelper.wrapInjectable(this, facing); + return CapUtil.CAP_ITEM_TRANSACTOR.cast(ItemTransactorHelper.wrapInjectable(this, facing)); } else { return super.getCapability(capability, facing); } diff --git a/common/buildcraft/transport/pipe/flow/PipeFlowPower.java b/common/buildcraft/transport/pipe/flow/PipeFlowPower.java index 41125eda12..6f3289683b 100644 --- a/common/buildcraft/transport/pipe/flow/PipeFlowPower.java +++ b/common/buildcraft/transport/pipe/flow/PipeFlowPower.java @@ -183,15 +183,14 @@ public boolean onFlowActivate(EntityPlayer player, RayTraceResult trace, float h return super.onFlowActivate(player, trace, hitX, hitY, hitZ, part); } - @SuppressWarnings("unchecked") @Override public T getCapability(@Nonnull Capability capability, EnumFacing facing) { if (facing == null) { return null; } else if (capability == MjAPI.CAP_RECEIVER) { - return isReceiver ? (T) sections.get(facing) : null; + return isReceiver ? MjAPI.CAP_RECEIVER.cast(sections.get(facing)) : null; } else if (capability == MjAPI.CAP_CONNECTOR) { - return (T) sections.get(facing); + return MjAPI.CAP_CONNECTOR.cast(sections.get(facing)); } else { return null; } From 1a16b9b7f0d67f7203e362a577478f6e6fbe5f18 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Wed, 21 Jun 2017 00:43:18 +0100 Subject: [PATCH 18/89] Fix maven dir --- BuildCraftAPI | 2 +- build.gradle | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/BuildCraftAPI b/BuildCraftAPI index 94acfa5cc6..c19b30eb7f 160000 --- a/BuildCraftAPI +++ b/BuildCraftAPI @@ -1 +1 @@ -Subproject commit 94acfa5cc6c8481dec6e1c22eed8a39932d30b51 +Subproject commit c19b30eb7f697d263a5c868ee12cac90c206c705 diff --git a/build.gradle b/build.gradle index af11fd62d4..bae2382f56 100644 --- a/build.gradle +++ b/build.gradle @@ -426,21 +426,21 @@ def sftp(String subPath, Closure antFileset = {}) { publishing { repositories { maven { - url "build/maven" + url System.getenv("MAVEN_DIR") ?: "build/maven" } } publications { pub_apiJar(MavenPublication) { groupId "com.mod-buildcraft" artifactId "buildcraft-api" - version "8.0" + version "7.99" artifact apiJar } pub_apiSrcJar(MavenPublication) { groupId "com.mod-buildcraft" artifactId "buildcraft-api" - version "8.0" + version "7.99" artifact apiSrcJar } From 8c5f80d3612beee28c8ef7f07b282c02af2d02ba Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Wed, 21 Jun 2017 23:23:57 +0100 Subject: [PATCH 19/89] Fix incorrect usage of SPacketUpdateTile --- common/buildcraft/lib/tile/TileBC_Neptune.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/common/buildcraft/lib/tile/TileBC_Neptune.java b/common/buildcraft/lib/tile/TileBC_Neptune.java index 9e0a7c130d..17ab4b42f6 100644 --- a/common/buildcraft/lib/tile/TileBC_Neptune.java +++ b/common/buildcraft/lib/tile/TileBC_Neptune.java @@ -413,9 +413,7 @@ public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) { @Override public SPacketUpdateTileEntity getUpdatePacket() { - IBlockState state = world.getBlockState(pos); - int meta = state.getBlock().getMetaFromState(state); - return new SPacketUpdateTileEntity(pos, meta, getUpdateTag()); + return new SPacketUpdateTileEntity(pos, 0, getUpdateTag()); } @Override From 95817696239d4c4f676b493af98af6c614fd3f69 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Wed, 21 Jun 2017 23:42:28 +0100 Subject: [PATCH 20/89] Fix #3681 --- BuildCraftAPI | 2 +- .../pipe/behaviour/PipeBehaviourWood.java | 2 ++ .../behaviour/PipeBehaviourWoodDiamond.java | 14 ++++++++++++-- .../transport/pipe/flow/PipeFlowFluids.java | 19 ++++++++++++------- 4 files changed, 27 insertions(+), 10 deletions(-) diff --git a/BuildCraftAPI b/BuildCraftAPI index c19b30eb7f..b3f9692622 160000 --- a/BuildCraftAPI +++ b/BuildCraftAPI @@ -1 +1 @@ -Subproject commit c19b30eb7f697d263a5c868ee12cac90c206c705 +Subproject commit b3f969262229f2f127ab95f9d55af245571336f3 diff --git a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourWood.java b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourWood.java index 055e2ac73b..60972ed6e4 100644 --- a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourWood.java +++ b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourWood.java @@ -9,6 +9,7 @@ import java.util.List; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; @@ -122,6 +123,7 @@ protected int extractItems(IFlowItems flow, EnumFacing dir, int count) { return flow.tryExtractItems(count, dir, null, StackFilter.ALL); } + @Nullable protected FluidStack extractFluid(IFlowFluid flow, EnumFacing dir, int millibuckets) { return flow.tryExtractFluid(millibuckets, dir, null); } diff --git a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourWoodDiamond.java b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourWoodDiamond.java index 490ee2c244..6113922986 100644 --- a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourWoodDiamond.java +++ b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourWoodDiamond.java @@ -10,6 +10,8 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.RayTraceResult; @@ -169,11 +171,18 @@ protected FluidStack extractFluid(IFlowFluid flow, EnumFacing dir, int millibuck default: case WHITE_LIST: // Firstly try the advanced version - if that fails we will need to try the basic version - FluidStack extracted = flow.tryExtractFluidAdv(millibuckets, dir, new ArrayFluidFilter(filters.stacks)); + ActionResult result = flow.tryExtractFluidAdv(millibuckets, dir, new ArrayFluidFilter(filters.stacks)); + FluidStack extracted = result.getResult(); + if (result.getType() != EnumActionResult.PASS) { + return extracted; + } if (extracted == null || extracted.amount <= 0) { for (int i = 0; i < filters.getSlots(); i++) { ItemStack stack = filters.getStackInSlot(i); + if (stack.isEmpty()) { + continue; + } extracted = flow.tryExtractFluid(millibuckets, dir, FluidUtil.getFluidContained(stack)); if (extracted != null && extracted.amount > 0) { return extracted; @@ -183,7 +192,8 @@ protected FluidStack extractFluid(IFlowFluid flow, EnumFacing dir, int millibuck return null; case BLACK_LIST: // We cannot fallback to the basic version - only use the advanced version - return flow.tryExtractFluidAdv(millibuckets, dir, new InvertedFluidFilter(new ArrayFluidFilter(filters.stacks))); + InvertedFluidFilter filter = new InvertedFluidFilter(new ArrayFluidFilter(filters.stacks)); + return flow.tryExtractFluidAdv(millibuckets, dir, filter).getResult(); case ROUND_ROBIN: // We can't do this -- amounts might differ and its just ugly return null; diff --git a/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java b/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java index 512d564e56..702971600e 100644 --- a/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java +++ b/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java @@ -21,6 +21,8 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.Vec3d; import net.minecraft.util.text.TextFormatting; @@ -64,6 +66,9 @@ public class PipeFlowFluids extends PipeFlow implements IFlowFluid, IDebuggable private static final int COOLDOWN_INPUT = -DIRECTION_COOLDOWN; private static final int COOLDOWN_OUTPUT = DIRECTION_COOLDOWN; + private static final ActionResult FAILED_EXTRACT = ActionResult.newResult(EnumActionResult.FAIL, null); + private static final ActionResult PASSED_EXTRACT = ActionResult.newResult(EnumActionResult.PASS, null); + public static final int NET_FLUID_AMOUNTS = 2; /** The number of pixels the fluid moves by per millisecond */ @@ -207,19 +212,19 @@ public FluidStack tryExtractFluid(int millibuckets, EnumFacing from, FluidStack } @Override - public FluidStack tryExtractFluidAdv(int millibuckets, EnumFacing from, IFluidFilter filter) { + public ActionResult tryExtractFluidAdv(int millibuckets, EnumFacing from, IFluidFilter filter) { // Mostly a copy of the above method if (from == null || filter == null || millibuckets <= 0) { - return null; + return FAILED_EXTRACT; } IFluidHandler fluidHandler = pipe.getHolder().getCapabilityFromPipe(from, CapUtil.CAP_FLUIDS); if (!(fluidHandler instanceof IFluidHandlerAdv)) { - return null; + return PASSED_EXTRACT; } IFluidHandlerAdv handlerAdv = (IFluidHandlerAdv) fluidHandler; if (currentFluid != null) { if (!filter.matches(currentFluid)) { - return null; + return FAILED_EXTRACT; } final IFluidFilter existing = filter; filter = (fluid) -> currentFluid.isFluidEqual(fluid) && existing.matches(fluid); @@ -227,11 +232,11 @@ public FluidStack tryExtractFluidAdv(int millibuckets, EnumFacing from, IFluidFi Section section = sections.get(EnumPipePart.fromFacing(from)); millibuckets = Math.min(millibuckets, section.getMaxFilled()); if (millibuckets <= 0) { - return null; + return FAILED_EXTRACT; } FluidStack toAdd = handlerAdv.drain(filter, millibuckets, true); if (toAdd == null || toAdd.amount <= 0) { - return null; + return FAILED_EXTRACT; } millibuckets = toAdd.amount; if (currentFluid == null) { @@ -243,7 +248,7 @@ public FluidStack tryExtractFluidAdv(int millibuckets, EnumFacing from, IFluidFi BCLog.logger.warn("[tryExtractFluidAdv] Filled " + reallyFilled + " != extracted " + millibuckets // + " (handler = " + fluidHandler.getClass() + ") @" + pipe.getHolder().getPipePos()); } - return toAdd; + return ActionResult.newResult(EnumActionResult.SUCCESS, toAdd); } // IDebuggable From f98d21fad2a72fd0f0585f395f2374605cb1a702 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Wed, 21 Jun 2017 23:54:42 +0100 Subject: [PATCH 21/89] Fix #3683 --- common/buildcraft/core/client/RenderTickListener.java | 1 + common/buildcraft/core/marker/VolumeConnection.java | 2 +- common/buildcraft/core/marker/VolumeSubCache.java | 2 +- .../buildcraft/lib/client/render/laser/LaserRenderer_BC8.java | 3 +++ 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/common/buildcraft/core/client/RenderTickListener.java b/common/buildcraft/core/client/RenderTickListener.java index f62d0cf93a..aa61b4c9fa 100644 --- a/common/buildcraft/core/client/RenderTickListener.java +++ b/common/buildcraft/core/client/RenderTickListener.java @@ -47,6 +47,7 @@ import buildcraft.lib.marker.MarkerCache; import buildcraft.lib.marker.MarkerSubCache; import buildcraft.lib.misc.MatrixUtil; +import buildcraft.lib.misc.SpriteUtil; import buildcraft.lib.misc.StackUtil; import buildcraft.lib.misc.VecUtil; import buildcraft.lib.misc.data.Box; diff --git a/common/buildcraft/core/marker/VolumeConnection.java b/common/buildcraft/core/marker/VolumeConnection.java index 451dc8d0d9..2c7d845a34 100644 --- a/common/buildcraft/core/marker/VolumeConnection.java +++ b/common/buildcraft/core/marker/VolumeConnection.java @@ -45,7 +45,7 @@ public static boolean tryCreateConnection(VolumeSubCache subCache, BlockPos from public static boolean canCreateConnection(VolumeSubCache subCache, BlockPos from, BlockPos to) { EnumFacing directOffset = PositionUtil.getDirectFacingOffset(from, to); if (directOffset == null) return false; - for (int i = 1; i < BCCoreConfig.markerMaxDistance; i++) { + for (int i = 1; i <= BCCoreConfig.markerMaxDistance; i++) { BlockPos offset = from.offset(directOffset, i); if (offset.equals(to)) return true; if (subCache.hasLoadedOrUnloadedMarker(offset)) return false; diff --git a/common/buildcraft/core/marker/VolumeSubCache.java b/common/buildcraft/core/marker/VolumeSubCache.java index e0760d27d1..0a7ee0c17e 100644 --- a/common/buildcraft/core/marker/VolumeSubCache.java +++ b/common/buildcraft/core/marker/VolumeSubCache.java @@ -85,7 +85,7 @@ public ImmutableList getValidConnections(BlockPos from) { ImmutableList.Builder valids = ImmutableList.builder(); for (EnumFacing face : EnumFacing.VALUES) { if (taken.contains(face.getAxis())) continue; - for (int i = 1; i < BCCoreConfig.markerMaxDistance; i++) { + for (int i = 1; i <= BCCoreConfig.markerMaxDistance; i++) { BlockPos toTry = from.offset(face, i); if (hasLoadedOrUnloadedMarker(toTry)) { if (!canConnect(from, toTry)) break; diff --git a/common/buildcraft/lib/client/render/laser/LaserRenderer_BC8.java b/common/buildcraft/lib/client/render/laser/LaserRenderer_BC8.java index 17b83add25..3db972ab54 100644 --- a/common/buildcraft/lib/client/render/laser/LaserRenderer_BC8.java +++ b/common/buildcraft/lib/client/render/laser/LaserRenderer_BC8.java @@ -25,6 +25,7 @@ import net.minecraft.world.World; import buildcraft.lib.client.render.laser.LaserData_BC8.LaserType; +import buildcraft.lib.misc.SpriteUtil; public class LaserRenderer_BC8 { private static final Map COMPILED_LASER_TYPES = new HashMap<>(); @@ -145,6 +146,7 @@ public static void renderLaserStatic(LaserData_BC8 data) { profiler.startSection("compute"); LaserCompiledList compiled = COMPILED_STATIC_LASERS.getUnchecked(data); profiler.endStartSection("render"); + SpriteUtil.bindBlockTextureMap(); compiled.render(); profiler.endSection(); } @@ -155,6 +157,7 @@ public static void renderLaserDynamic(LaserData_BC8 data, VertexBuffer buffer) { profiler.startSection("compute"); LaserCompiledBuffer compiled = COMPILED_DYNAMIC_LASERS.getUnchecked(data); profiler.endStartSection("render"); + SpriteUtil.bindBlockTextureMap(); compiled.render(buffer); profiler.endSection(); } From a1d0d550dcfb1c9dad6f1edcabcebcb29fbb1469 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Sat, 24 Jun 2017 14:43:11 +0300 Subject: [PATCH 22/89] Fix null profile --- common/buildcraft/lib/misc/FakePlayerProvider.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/common/buildcraft/lib/misc/FakePlayerProvider.java b/common/buildcraft/lib/misc/FakePlayerProvider.java index ebade57980..8ebe6418a1 100644 --- a/common/buildcraft/lib/misc/FakePlayerProvider.java +++ b/common/buildcraft/lib/misc/FakePlayerProvider.java @@ -42,7 +42,10 @@ public FakePlayerBC getFakePlayer(WorldServer world, GameProfile profile) { @Override public FakePlayerBC getFakePlayer(WorldServer world, GameProfile profile, BlockPos pos) { - players.computeIfAbsent(profile, p -> new FakePlayerBC(world, profile)); + if (profile == null) { + profile = gameProfile; + } + players.computeIfAbsent(profile, p -> new FakePlayerBC(world, p)); FakePlayerBC player = players.get(profile); player.world = world; player.posX = pos.getX(); From e8b2343bc8396f67eb516600d86bec7cd8a4690e Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Sun, 25 Jun 2017 09:49:48 +0300 Subject: [PATCH 23/89] Replace == with equals --- common/buildcraft/transport/plug/FacadeStateManager.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/common/buildcraft/transport/plug/FacadeStateManager.java b/common/buildcraft/transport/plug/FacadeStateManager.java index 988606648d..3376c1c920 100644 --- a/common/buildcraft/transport/plug/FacadeStateManager.java +++ b/common/buildcraft/transport/plug/FacadeStateManager.java @@ -192,14 +192,14 @@ public static void postInit() { for (Block block : ForgeRegistries.BLOCKS) { String result = isValidFacadeBlock(block); // These strings are hardcoded, so we can get away with not needing the .equals check - if (result != STR_PASS && result != STR_SUCCESS) { + if (!Objects.equals(result, STR_PASS) && !Objects.equals(result, STR_SUCCESS)) { if (DEBUG) { BCLog.logger .info("[transport.facade] Disallowed block " + block.getRegistryName() + " because " + result); } continue; } else if (DEBUG) { - if (result == STR_SUCCESS) { + if (Objects.equals(result, STR_SUCCESS)) { BCLog.logger.info("[transport.facade] Allowed block " + block.getRegistryName()); } } @@ -211,9 +211,9 @@ public static void postInit() { if (!checkedStates.add(state)) { continue; } - if (result != STR_SUCCESS) { + if (!Objects.equals(result, STR_SUCCESS)) { result = isValidFacadeState(state); - if (result == STR_SUCCESS) { + if (Objects.equals(result, STR_SUCCESS)) { if (DEBUG) { BCLog.logger.info("[transport.facade] Allowed state " + state); } From 4ce1fa9d09430fdb1abf144823b92af70a95d66e Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Sun, 25 Jun 2017 10:23:34 +0300 Subject: [PATCH 24/89] Fix #3687 --- .../builders/block/BlockArchitectTable.java | 2 +- common/buildcraft/builders/block/BlockBuilder.java | 2 +- common/buildcraft/builders/block/BlockFiller.java | 2 +- common/buildcraft/builders/block/BlockQuarry.java | 2 +- common/buildcraft/lib/block/BlockBCBase_Neptune.java | 11 +++++++++++ common/buildcraft/lib/block/IBlockWithFacing.java | 4 ++-- 6 files changed, 17 insertions(+), 6 deletions(-) diff --git a/common/buildcraft/builders/block/BlockArchitectTable.java b/common/buildcraft/builders/block/BlockArchitectTable.java index c9b3a6044f..a507ec7305 100644 --- a/common/buildcraft/builders/block/BlockArchitectTable.java +++ b/common/buildcraft/builders/block/BlockArchitectTable.java @@ -66,7 +66,7 @@ public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, En } @Override - public boolean canBeRotated(World world, BlockPos pos, IBlockState state, EnumFacing sideWrenched) { + public boolean canBeRotated(World world, BlockPos pos, IBlockState state) { return false; } } diff --git a/common/buildcraft/builders/block/BlockBuilder.java b/common/buildcraft/builders/block/BlockBuilder.java index 26d5979a32..05aca7b9f3 100644 --- a/common/buildcraft/builders/block/BlockBuilder.java +++ b/common/buildcraft/builders/block/BlockBuilder.java @@ -72,7 +72,7 @@ public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, En } @Override - public boolean canBeRotated(World world, BlockPos pos, IBlockState state, EnumFacing sideWrenched) { + public boolean canBeRotated(World world, BlockPos pos, IBlockState state) { TileEntity tile = world.getTileEntity(pos); return !(tile instanceof TileBuilder) || ((TileBuilder) tile).getBuilder() == null; } diff --git a/common/buildcraft/builders/block/BlockFiller.java b/common/buildcraft/builders/block/BlockFiller.java index aecb950a2c..d95f416947 100644 --- a/common/buildcraft/builders/block/BlockFiller.java +++ b/common/buildcraft/builders/block/BlockFiller.java @@ -71,7 +71,7 @@ public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, En } @Override - public boolean canBeRotated(World world, BlockPos pos, IBlockState state, EnumFacing sideWrenched) { + public boolean canBeRotated(World world, BlockPos pos, IBlockState state) { return false; } } diff --git a/common/buildcraft/builders/block/BlockQuarry.java b/common/buildcraft/builders/block/BlockQuarry.java index 268f91d175..7aebe23012 100644 --- a/common/buildcraft/builders/block/BlockQuarry.java +++ b/common/buildcraft/builders/block/BlockQuarry.java @@ -61,7 +61,7 @@ public TileEntity createNewTileEntity(World world, int meta) { } @Override - public boolean canBeRotated(World world, BlockPos pos, IBlockState state, EnumFacing sideWrenched) { + public boolean canBeRotated(World world, BlockPos pos, IBlockState state) { return false; } diff --git a/common/buildcraft/lib/block/BlockBCBase_Neptune.java b/common/buildcraft/lib/block/BlockBCBase_Neptune.java index 26a4e77bcb..631aa491e1 100644 --- a/common/buildcraft/lib/block/BlockBCBase_Neptune.java +++ b/common/buildcraft/lib/block/BlockBCBase_Neptune.java @@ -16,6 +16,7 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.Item; +import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.Mirror; @@ -147,6 +148,16 @@ public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing fa return state; } + @Override + public boolean rotateBlock(World world, BlockPos pos, EnumFacing axis) { + if (this instanceof IBlockWithFacing) { + if (!((IBlockWithFacing) this).canBeRotated(world, pos, world.getBlockState(pos))) { + return false; + } + } + return super.rotateBlock(world, pos, axis); + } + public static B register(B block) { return register(block, false, ItemBlockBC_Neptune::new); } diff --git a/common/buildcraft/lib/block/IBlockWithFacing.java b/common/buildcraft/lib/block/IBlockWithFacing.java index ad1bdccae6..0f0377bb2e 100644 --- a/common/buildcraft/lib/block/IBlockWithFacing.java +++ b/common/buildcraft/lib/block/IBlockWithFacing.java @@ -28,13 +28,13 @@ default IProperty getFacingProperty() { return this.canPlacedVertical() ? BlockBCBase_Neptune.BLOCK_FACING_6 : BlockBCBase_Neptune.PROP_FACING; } - default boolean canBeRotated(World world, BlockPos pos, IBlockState state, EnumFacing sideWrenched) { + default boolean canBeRotated(World world, BlockPos pos, IBlockState state) { return true; } @Override default EnumActionResult attemptRotation(World world, BlockPos pos, IBlockState state, EnumFacing sideWrenched) { - if (!canBeRotated(world, pos, state, sideWrenched)) { + if (!canBeRotated(world, pos, state)) { return EnumActionResult.FAIL; } EnumFacing currentFacing = state.getValue(getFacingProperty()); From 7b622710c95665377fa759c682fe27c57c27c235 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Sun, 25 Jun 2017 19:34:18 +0300 Subject: [PATCH 25/89] Circle type --- .../buildcraft/builders/filling/Filling.java | 143 ++++++++++++++---- common/buildcraft/lib/misc/DrawingUtil.java | 62 ++++++++ 2 files changed, 174 insertions(+), 31 deletions(-) create mode 100644 common/buildcraft/lib/misc/DrawingUtil.java diff --git a/common/buildcraft/builders/filling/Filling.java b/common/buildcraft/builders/filling/Filling.java index f3b8c8ac09..ebf689b87a 100644 --- a/common/buildcraft/builders/filling/Filling.java +++ b/common/buildcraft/builders/filling/Filling.java @@ -9,6 +9,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.StreamSupport; @@ -22,6 +23,8 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; +import buildcraft.lib.misc.DrawingUtil; + public enum Filling { INSTANCE; @@ -29,19 +32,19 @@ public enum Filling { Filling() { StreamSupport.stream(Item.REGISTRY.spliterator(), false) - .filter(item -> item instanceof ItemBlock || item instanceof ItemBlockSpecial) - .forEach(this::addItemBlock); + .filter(item -> item instanceof ItemBlock || item instanceof ItemBlockSpecial) + .forEach(this::addItemBlock); addItemBlock( - Items.BED, - Items.OAK_DOOR, - Items.SPRUCE_DOOR, - Items.BIRCH_DOOR, - Items.JUNGLE_DOOR, - Items.ACACIA_DOOR, - Items.DARK_OAK_DOOR, - Items.IRON_DOOR, - Items.SKULL, - Items.SIGN + Items.BED, + Items.OAK_DOOR, + Items.SPRUCE_DOOR, + Items.BIRCH_DOOR, + Items.JUNGLE_DOOR, + Items.ACACIA_DOOR, + Items.DARK_OAK_DOOR, + Items.IRON_DOOR, + Items.SKULL, + Items.SIGN ); } @@ -90,7 +93,8 @@ public Class getNextParameterClass(List parame return null; } - public boolean[][][] generateFillingPlanByFunction(BlockPos size, Function function) { + public boolean[][][] generateFillingPlanByFunction(BlockPos size, + Function function) { boolean[][][] fillingPlan = new boolean[size.getX()][size.getY()][size.getZ()]; for (int z = 0; z < size.getZ(); z++) { for (int y = 0; y < size.getY(); y++) { @@ -102,25 +106,59 @@ public boolean[][][] generateFillingPlanByFunction(BlockPos size, Function function) { + public boolean[][][] generateFillingPlanByFunctionInAxis(BlockPos size, + EnumFacing.Axis axis, + BiFunction function) { switch (axis) { case X: return generateFillingPlanByFunction(size, pos -> function.apply( - new Point2i(pos.getY(), pos.getZ()), - new Point2i(size.getY(), size.getZ()) + new Point2i(pos.getY(), pos.getZ()), + new Point2i(size.getY(), size.getZ()) )); case Y: return generateFillingPlanByFunction(size, pos -> function.apply( - new Point2i(pos.getX(), pos.getZ()), - new Point2i(size.getX(), size.getZ()) + new Point2i(pos.getX(), pos.getZ()), + new Point2i(size.getX(), size.getZ()) )); case Z: return generateFillingPlanByFunction(size, pos -> function.apply( - new Point2i(pos.getX(), pos.getY()), - new Point2i(size.getX(), size.getY()) + new Point2i(pos.getX(), pos.getY()), + new Point2i(size.getX(), size.getY()) )); + default: + throw new UnsupportedOperationException(); + } + } + + public boolean[][][] generateFillingPlanByFunctionInAxis(BlockPos size, + EnumFacing.Axis axis, + BiConsumer function) { + Point2i flatSize; + switch (axis) { + case X: + flatSize = new Point2i(size.getY(), size.getZ()); + break; + case Y: + flatSize = new Point2i(size.getX(), size.getZ()); + break; + case Z: + flatSize = new Point2i(size.getX(), size.getY()); + break; + default: + throw new UnsupportedOperationException(); + } + boolean[][] flatFillingPlan = new boolean[flatSize.x][flatSize.y]; + function.accept(flatSize, flatFillingPlan); + switch (axis) { + case X: + return generateFillingPlanByFunction(size, pos -> flatFillingPlan[pos.getY()][pos.getZ()]); + case Y: + return generateFillingPlanByFunction(size, pos -> flatFillingPlan[pos.getX()][pos.getZ()]); + case Z: + return generateFillingPlanByFunction(size, pos -> flatFillingPlan[pos.getX()][pos.getY()]); + default: + throw new UnsupportedOperationException(); } - return generateFillingPlanByFunction(size, pos -> false); } public boolean[][][] getFillingPlan(BlockPos size, List parameters) { @@ -129,13 +167,13 @@ public boolean[][][] getFillingPlan(BlockPos size, List parameters) if (parameterPattern == EnumParameterPattern.FRAME) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); return generateFillingPlanByFunction(size, pos -> - parameterType == EnumParameterType.FILLED ? - pos.getX() == 0 || pos.getX() == sizeS.getX() || - pos.getY() == 0 || pos.getY() == sizeS.getY() || - pos.getZ() == 0 || pos.getZ() == sizeS.getZ() : - ((pos.getX() == 0 || pos.getX() == sizeS.getX()) && (pos.getY() == 0 || pos.getY() == sizeS.getY())) || - ((pos.getY() == 0 || pos.getY() == sizeS.getY()) && (pos.getZ() == 0 || pos.getZ() == sizeS.getZ())) || - ((pos.getZ() == 0 || pos.getZ() == sizeS.getZ()) && (pos.getX() == 0 || pos.getX() == sizeS.getX())) + parameterType == EnumParameterType.FILLED ? + pos.getX() == 0 || pos.getX() == sizeS.getX() || + pos.getY() == 0 || pos.getY() == sizeS.getY() || + pos.getZ() == 0 || pos.getZ() == sizeS.getZ() : + ((pos.getX() == 0 || pos.getX() == sizeS.getX()) && (pos.getY() == 0 || pos.getY() == sizeS.getY())) || + ((pos.getY() == 0 || pos.getY() == sizeS.getY()) && (pos.getZ() == 0 || pos.getZ() == sizeS.getZ())) || + ((pos.getZ() == 0 || pos.getZ() == sizeS.getZ()) && (pos.getX() == 0 || pos.getX() == sizeS.getX())) ); } if (parameterPattern == EnumParameterPattern.SQUARE) { @@ -144,12 +182,55 @@ public boolean[][][] getFillingPlan(BlockPos size, List parameters) return generateFillingPlanByFunction(size, pos -> true); } else { EnumParameterAxis parameterAxis = (EnumParameterAxis) parameters.get(2); - return generateFillingPlanByFunctionInAxis(size, parameterAxis.axis, (pos, sizeA) -> - pos.getX() == 0 || pos.getX() == sizeA.getX() - 1 || - pos.getY() == 0 || pos.getY() == sizeA.getY() - 1 + return generateFillingPlanByFunctionInAxis(size, parameterAxis.axis, (pos, flatSize) -> + pos.getX() == 0 || pos.getX() == flatSize.getX() - 1 || + pos.getY() == 0 || pos.getY() == flatSize.getY() - 1 ); } } + if (parameterPattern == EnumParameterPattern.CIRCLE) { + EnumParameterType parameterType = (EnumParameterType) parameters.get(1); + EnumParameterAxis parameterAxis = (EnumParameterAxis) parameters.get(2); + return generateFillingPlanByFunctionInAxis(size, parameterAxis.axis, (flatSize, flatFillingPlan) -> { + DrawingUtil.drawEllipse( + flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, + flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, + flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, + flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, + parameterType == EnumParameterType.FILLED, + (x, y) -> { + List positions = new ArrayList<>(); + positions.add( + new Point2i( + flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, + flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y + ) + ); + if (flatSize.x % 2 == 0 && x == flatSize.x / 2) { + positions.add( + new Point2i( + x + 1, + flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y + ) + ); + } + if (flatSize.y % 2 == 0 && y == flatSize.y / 2) { + positions.add( + new Point2i( + flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, + y + 1 + ) + ); + } + for (Point2i p : positions) { + if (p.x >= 0 && p.y >= 0 && p.x < flatSize.x && p.y < flatSize.y) { + flatFillingPlan[p.x][p.y] = true; + } + } + } + ); + }); + } return generateFillingPlanByFunction(size, pos -> false); } diff --git a/common/buildcraft/lib/misc/DrawingUtil.java b/common/buildcraft/lib/misc/DrawingUtil.java new file mode 100644 index 0000000000..df79a2ee1b --- /dev/null +++ b/common/buildcraft/lib/misc/DrawingUtil.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.lib.misc; + +import java.util.function.BiConsumer; + +public class DrawingUtil { + @SuppressWarnings("Duplicates") + public static void drawEllipse(int cx, + int cy, + int width, + int height, + boolean filled, + BiConsumer drawPixel) { + int a2 = width * width; + int b2 = height * height; + int fa2 = 4 * a2, fb2 = 4 * b2; + int x, y, sigma; + + for (x = 0, y = height, sigma = 2 * b2 + a2 * (1 - 2 * height); b2 * x <= a2 * y; x++) { + if (filled) { + for (int i = -x; i <= x; i++) { + drawPixel.accept(cx + i, cy + y); + drawPixel.accept(cx + i, cy - y); + } + } else { + drawPixel.accept(cx + x, cy + y); + drawPixel.accept(cx - x, cy + y); + drawPixel.accept(cx + x, cy - y); + drawPixel.accept(cx - x, cy - y); + } + if (sigma >= 0) { + sigma += fa2 * (1 - y); + y--; + } + sigma += b2 * ((4 * x) + 6); + } + + for (x = width, y = 0, sigma = 2 * a2 + b2 * (1 - 2 * width); a2 * y <= b2 * x; y++) { + if (filled) { + for (int i = -x; i <= x; i++) { + drawPixel.accept(cx + i, cy + y); + drawPixel.accept(cx + i, cy - y); + } + } else { + drawPixel.accept(cx + x, cy + y); + drawPixel.accept(cx - x, cy + y); + drawPixel.accept(cx + x, cy - y); + drawPixel.accept(cx - x, cy - y); + } + if (sigma >= 0) { + sigma += fb2 * (1 - x); + x--; + } + sigma += a2 * ((4 * y) + 6); + } + } +} From 22d3c8a8b0db802a6f0fcbd76df1622c594e41f5 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Sun, 25 Jun 2017 21:51:44 +0300 Subject: [PATCH 26/89] Filler fixes --- .../builders/snapshot/BlueprintBuilder.java | 8 +- .../builders/snapshot/SnapshotBuilder.java | 150 ++++++++++++------ .../builders/snapshot/TemplateBuilder.java | 1 + .../buildcraft/builders/tile/TileFiller.java | 1 + common/buildcraft/lib/misc/BlockUtil.java | 17 ++ 5 files changed, 126 insertions(+), 51 deletions(-) diff --git a/common/buildcraft/builders/snapshot/BlueprintBuilder.java b/common/buildcraft/builders/snapshot/BlueprintBuilder.java index b9837fb1a1..c55e40db62 100644 --- a/common/buildcraft/builders/snapshot/BlueprintBuilder.java +++ b/common/buildcraft/builders/snapshot/BlueprintBuilder.java @@ -127,7 +127,7 @@ protected boolean canPlace(BlockPos blockPos) { .map(blockPos::add) .allMatch(pos -> getBuildingInfo().toPlace.containsKey(pos) - ? checkResults.get(pos) == CheckResult.CORRECT + ? checkResults.get(CheckResult.CORRECT).contains(pos) : !getToBreak().contains(pos) || tile.getWorldBC().isAirBlock(pos) ) && !getBuildingInfo().toPlace.get(blockPos).isAir() && @@ -146,6 +146,7 @@ protected List getToPlaceItems(BlockPos blockPos) { @Override protected void cancelPlaceTask(PlaceTask placeTask) { + super.cancelPlaceTask(placeTask); // noinspection ConstantConditions placeTask.items.stream() .filter(stack -> !stack.hasTagCompound() || !stack.getTagCompound().hasKey("BuilderFluidStack")) @@ -209,10 +210,7 @@ public boolean tick() { remainingDisplayRequired.addAll(StackUtil.mergeSameItems( Stream.concat( getToPlace().stream() - .filter(blockPos -> - checkResults.get(blockPos) != CheckResult.UNKNOWN && - checkResults.get(blockPos) != CheckResult.CORRECT - ) + .filter(blockPos -> !checkResults.get(CheckResult.CORRECT).contains(blockPos)) .flatMap(blockPos -> getDisplayRequired( buildingInfo.toPlaceRequiredItems.get(blockPos), diff --git a/common/buildcraft/builders/snapshot/SnapshotBuilder.java b/common/buildcraft/builders/snapshot/SnapshotBuilder.java index 965fe0e367..f10683c74b 100644 --- a/common/buildcraft/builders/snapshot/SnapshotBuilder.java +++ b/common/buildcraft/builders/snapshot/SnapshotBuilder.java @@ -8,22 +8,25 @@ import java.io.IOException; import java.util.ArrayDeque; -import java.util.Collections; +import java.util.ArrayList; import java.util.Comparator; -import java.util.Deque; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; +import java.util.Set; +import java.util.TreeSet; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; -import java.util.stream.Stream; import javax.annotation.Nullable; +import com.google.common.collect.ImmutableMap; + import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; @@ -43,7 +46,6 @@ import buildcraft.api.mj.MjAPI; import buildcraft.lib.misc.BlockUtil; -import buildcraft.lib.misc.FakePlayerProvider; import buildcraft.lib.misc.MessageUtil; import buildcraft.lib.misc.data.Box; import buildcraft.lib.net.PacketBufferBC; @@ -139,7 +141,7 @@ public void sendBlockBreakProgress(int breakerId, BlockPos pos, int progress) { public final Queue clientPlaceTasks = new ArrayDeque<>(); public final Queue prevClientPlaceTasks = new ArrayDeque<>(); private final LinkedList toCheck = new LinkedList<>(); - protected final Map checkResults = new HashMap<>(); + protected final Map> checkResults; public Vec3d robotPos = null; public Vec3d prevRobotPos = null; public int leftToBreak = 0; @@ -147,6 +149,33 @@ public void sendBlockBreakProgress(int breakerId, BlockPos pos, int progress) { protected SnapshotBuilder(T tile) { this.tile = tile; + checkResults = + new ImmutableMap.Builder>() + .put( + CheckResult.CORRECT, + new TreeSet<>(BlockUtil.uniqueBlockPosComparator(Comparator.comparingDouble(blockPos -> + Math.pow(blockPos.getX() - getBox().center().getX(), 2) + + Math.pow(blockPos.getY() - getBox().center().getY(), 2) + + Math.pow(blockPos.getZ() - getBox().center().getZ(), 2) + ))) + ) + .put( + CheckResult.TO_BREAK, + new TreeSet<>(BlockUtil.uniqueBlockPosComparator(Comparator.comparingDouble(blockPos -> + Math.pow(blockPos.getX() - getBox().center().getX(), 2) + + Math.pow(blockPos.getZ() - getBox().center().getZ(), 2) + + 100_000 - Math.abs(blockPos.getY() - tile.getBuilderPos().getY()) * 100_000 + ))) + ) + .put( + CheckResult.TO_PLACE, + new TreeSet<>(BlockUtil.uniqueBlockPosComparator(Comparator.comparingDouble(blockPos -> + 100_000 - (Math.pow(blockPos.getX() - tile.getBuilderPos().getX(), 2) + + Math.pow(blockPos.getZ() - tile.getBuilderPos().getZ(), 2)) + + Math.abs(blockPos.getY() - tile.getBuilderPos().getY()) * 100_000 + ))) + ) + .build(); } public void validate() { @@ -177,10 +206,25 @@ public void invalidate() { */ protected abstract boolean doPlaceTask(PlaceTask placeTask); + /** + * Executed if break task failed + */ + private void cancelBreakTask(BreakTask breakTask) { + tile.getBattery().addPower( + Math.min(breakTask.power, tile.getBattery().getCapacity() - tile.getBattery().getStored()), + false + ); + } + /** * Executed if {@link #doPlaceTask} failed */ - protected abstract void cancelPlaceTask(PlaceTask placeTask); + protected void cancelPlaceTask(PlaceTask placeTask) { + tile.getBattery().addPower( + Math.min(placeTask.power, tile.getBattery().getCapacity() - tile.getBattery().getStored()), + false + ); + } /** * @return true if block in wold is correct (is not to break) according to snapshot, false otherwise @@ -202,14 +246,15 @@ public Vec3d getPlaceTaskItemPos(PlaceTask placeTask) { } public void updateSnapshot() { + tile.getWorldBC().profiler.startSection("init"); toCheck.addAll(getToBreak()); toCheck.addAll(getToPlace()); - toCheck.sort(Comparator.comparing(blockPos -> + toCheck.sort(BlockUtil.uniqueBlockPosComparator(Comparator.comparingDouble(blockPos -> Math.pow(blockPos.getX() - getBox().center().getX(), 2) + Math.pow(blockPos.getY() - getBox().center().getY(), 2) + Math.pow(blockPos.getZ() - getBox().center().getZ(), 2) - )); - toCheck.forEach(blockPos -> checkResults.put(blockPos, CheckResult.UNKNOWN)); + ))); + tile.getWorldBC().profiler.endSection(); } public void cancel() { @@ -280,25 +325,38 @@ public boolean tick() { return false; } + tile.getWorldBC().profiler.startSection("scan"); for (int i = 0; i < 10; i++) { BlockPos blockPos = toCheck.pollFirst(); check(blockPos); toCheck.addLast(blockPos); } - - breakTasks.removeIf(breakTask -> checkResults.get(breakTask.pos) == CheckResult.CORRECT); - placeTasks.removeIf(placeTask -> checkResults.get(placeTask.pos) == CheckResult.CORRECT); + tile.getWorldBC().profiler.endSection(); + + tile.getWorldBC().profiler.startSection("remove tasks"); + for (Iterator iterator = breakTasks.iterator(); iterator.hasNext(); ) { + BreakTask breakTask = iterator.next(); + if (checkResults.get(CheckResult.CORRECT).contains(breakTask.pos)) { + iterator.remove(); + cancelBreakTask(breakTask); + } + } + for (Iterator iterator = placeTasks.iterator(); iterator.hasNext(); ) { + PlaceTask placeTask = iterator.next(); + if (checkResults.get(CheckResult.CORRECT).contains(placeTask.pos)) { + iterator.remove(); + cancelPlaceTask(placeTask); + } + } + breakTasks.removeIf(breakTask -> checkResults.get(CheckResult.CORRECT).contains(breakTask.pos)); + placeTasks.removeIf(placeTask -> checkResults.get(CheckResult.CORRECT).contains(placeTask.pos)); + tile.getWorldBC().profiler.endSection(); boolean isDone = true; + tile.getWorldBC().profiler.startSection("add tasks"); if (tile.canExcavate()) { - List blocks = checkResults.keySet().stream() - .sorted(Comparator.comparing(blockPos -> - Math.pow(blockPos.getX() - getBox().center().getX(), 2) + - Math.pow(blockPos.getZ() - getBox().center().getZ(), 2) + - 100_000 - Math.abs(blockPos.getY() - tile.getBuilderPos().getY()) * 100_000 - )) - .filter(blockPos -> checkResults.get(blockPos) == CheckResult.TO_BREAK) + List blocks = checkResults.get(CheckResult.TO_BREAK).stream() .filter(blockPos -> breakTasks.stream() .map(breakTask -> breakTask.pos) @@ -320,15 +378,8 @@ public boolean tick() { .limit(MAX_QUEUE_SIZE - breakTasks.size()) .forEach(breakTasks::add); } - { - List blocks = checkResults.keySet().stream() - .sorted(Comparator.comparing(blockPos -> - 100_000 - (Math.pow(blockPos.getX() - tile.getBuilderPos().getX(), 2) + - Math.pow(blockPos.getZ() - tile.getBuilderPos().getZ(), 2)) + - Math.abs(blockPos.getY() - tile.getBuilderPos().getY()) * 100_000 - )) - .filter(blockPos -> checkResults.get(blockPos) == CheckResult.TO_PLACE) + List blocks = checkResults.get(CheckResult.TO_PLACE).stream() .filter(blockPos -> placeTasks.stream() .map(placeTask -> placeTask.pos) @@ -355,14 +406,22 @@ public boolean tick() { .forEach(placeTasks::add); } } + tile.getWorldBC().profiler.endSection(); + tile.getWorldBC().profiler.startSection("do tasks"); if (!breakTasks.isEmpty()) { for (Iterator iterator = breakTasks.iterator(); iterator.hasNext(); ) { BreakTask breakTask = iterator.next(); long target = breakTask.getTarget(); breakTask.power += tile.getBattery().extractPower( 0, - Math.min(target - breakTask.power, tile.getBattery().getStored() / breakTasks.size()) + Math.min( + Math.min( + target - breakTask.power, + tile.getBattery().getStored() / breakTasks.size() + ), + MjAPI.MJ / 10 + ) ); if (breakTask.power >= target) { BlockEvent.BreakEvent breakEvent = new BlockEvent.BreakEvent( @@ -384,10 +443,7 @@ public boolean tick() { ); tile.getWorldBC().destroyBlock(breakTask.pos, false); } else { - tile.getBattery().addPower( - Math.min(target, tile.getBattery().getCapacity() - tile.getBattery().getStored()), - false - ); + cancelBreakTask(breakTask); } check(breakTask.pos); iterator.remove(); @@ -400,21 +456,22 @@ public boolean tick() { } } } - if (!placeTasks.isEmpty()) { for (Iterator iterator = placeTasks.iterator(); iterator.hasNext(); ) { PlaceTask placeTask = iterator.next(); long target = placeTask.getTarget(); placeTask.power += tile.getBattery().extractPower( 0, - Math.min(target - placeTask.power, tile.getBattery().getStored() / placeTasks.size()) + Math.min( + Math.min( + target - placeTask.power, + tile.getBattery().getStored() / placeTasks.size() + ), + MjAPI.MJ / 10 + ) ); if (placeTask.power >= target) { if (!doPlaceTask(placeTask)) { - tile.getBattery().addPower( - Math.min(target, tile.getBattery().getCapacity() - tile.getBattery().getStored()), - false - ); cancelPlaceTask(placeTask); } check(placeTask.pos); @@ -422,25 +479,27 @@ public boolean tick() { } } } + tile.getWorldBC().profiler.endSection(); return isDone; } protected void check(BlockPos blockPos) { + checkResults.values().forEach(set -> set.removeIf(Predicate.isEqual(blockPos))); if (getToBreak().contains(blockPos)) { if (tile.getWorldBC().isAirBlock(blockPos)) { - checkResults.put(blockPos, CheckResult.CORRECT); + checkResults.get(CheckResult.CORRECT).add(blockPos); } else { - checkResults.put(blockPos, CheckResult.TO_BREAK); + checkResults.get(CheckResult.TO_BREAK).add(blockPos); } } if (getToPlace().contains(blockPos)) { if (isBlockCorrect(blockPos)) { - checkResults.put(blockPos, CheckResult.CORRECT); + checkResults.get(CheckResult.CORRECT).add(blockPos); } else if (tile.getWorldBC().isAirBlock(blockPos)) { - checkResults.put(blockPos, CheckResult.TO_PLACE); + checkResults.get(CheckResult.TO_PLACE).add(blockPos); } else { - checkResults.put(blockPos, CheckResult.TO_BREAK); + checkResults.get(CheckResult.TO_BREAK).add(blockPos); } } } @@ -511,7 +570,7 @@ public PlaceTask(PacketBufferBC buffer) { } public long getTarget() { - return (long) (Math.sqrt(pos.distanceSq(tile.getBuilderPos())) * 10 * MjAPI.MJ); + return (long) (Math.min(10, Math.sqrt(pos.distanceSq(tile.getBuilderPos()))) * MjAPI.MJ); } public void writePayload(PacketBufferBC buffer) { @@ -523,9 +582,8 @@ public void writePayload(PacketBufferBC buffer) { } protected enum CheckResult { - UNKNOWN, CORRECT, TO_BREAK, - TO_PLACE; + TO_PLACE } } diff --git a/common/buildcraft/builders/snapshot/TemplateBuilder.java b/common/buildcraft/builders/snapshot/TemplateBuilder.java index b7d41076f0..c0ba8a48eb 100644 --- a/common/buildcraft/builders/snapshot/TemplateBuilder.java +++ b/common/buildcraft/builders/snapshot/TemplateBuilder.java @@ -72,6 +72,7 @@ protected boolean doPlaceTask(PlaceTask placeTask) { @Override protected void cancelPlaceTask(PlaceTask placeTask) { + super.cancelPlaceTask(placeTask); tile.getInvResources().insert(placeTask.items.get(0), false, false); } diff --git a/common/buildcraft/builders/tile/TileFiller.java b/common/buildcraft/builders/tile/TileFiller.java index 4e27b6e0e9..28eb875fcc 100644 --- a/common/buildcraft/builders/tile/TileFiller.java +++ b/common/buildcraft/builders/tile/TileFiller.java @@ -110,6 +110,7 @@ public void onPlacedBy(EntityLivingBase placer, ItemStack stack) { volumeBoxes.markDirty(); } } + builder.updateSnapshot(); } @Override diff --git a/common/buildcraft/lib/misc/BlockUtil.java b/common/buildcraft/lib/misc/BlockUtil.java index 1559106354..ef106e25d4 100644 --- a/common/buildcraft/lib/misc/BlockUtil.java +++ b/common/buildcraft/lib/misc/BlockUtil.java @@ -447,4 +447,21 @@ public static TileEntity getTileEntityForGetActualState(IBlockAccess world, Bloc ? ((ChunkCache) world).getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK) : world.getTileEntity(pos); } + + public static Comparator uniqueBlockPosComparator(Comparator parent) { + return (a, b) -> { + int parentValue = parent.compare(a, b); + if (parentValue != 0) { + return parentValue; + } else if (a.getX() != b.getX()) { + return Integer.compare(a.getX(), b.getX()); + } else if (a.getY() != b.getY()) { + return Integer.compare(a.getY(), b.getY()); + } else if (a.getZ() != b.getZ()) { + return Integer.compare(a.getZ(), b.getZ()); + } else { + return 0; + } + }; + } } From 53cb5a81aeb500d050964cb9f8a0b858c236de96 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Sun, 25 Jun 2017 22:10:39 +0300 Subject: [PATCH 27/89] Remvoe iterations --- common/buildcraft/builders/snapshot/Blueprint.java | 6 ++++-- .../builders/snapshot/BlueprintBuilder.java | 14 ++++++-------- .../builders/snapshot/SnapshotBuilder.java | 9 +++------ common/buildcraft/builders/snapshot/Template.java | 8 ++++---- .../builders/snapshot/TemplateBuilder.java | 9 +++++---- 5 files changed, 22 insertions(+), 24 deletions(-) diff --git a/common/buildcraft/builders/snapshot/Blueprint.java b/common/buildcraft/builders/snapshot/Blueprint.java index 8e3a237a45..7a8648d2d6 100644 --- a/common/buildcraft/builders/snapshot/Blueprint.java +++ b/common/buildcraft/builders/snapshot/Blueprint.java @@ -9,8 +9,10 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -129,11 +131,11 @@ public class BuildingInfo { public final BlockPos basePos; public final Rotation rotation; private final Box box; - public final List toBreak = new ArrayList<>(); + public final Set toBreak = new HashSet<>(); public final Map> toPlace = new HashMap<>(); public final Map> toPlaceRequiredItems = new HashMap<>(); public final Map> toPlaceRequiredFluids = new HashMap<>(); - public final List> entities = new ArrayList<>(); + public final Set> entities = new HashSet<>(); public final Map, List> entitiesRequiredItems = new HashMap<>(); public final Map, List> entitiesRequiredFluids = new HashMap<>(); diff --git a/common/buildcraft/builders/snapshot/BlueprintBuilder.java b/common/buildcraft/builders/snapshot/BlueprintBuilder.java index c55e40db62..27f74fe574 100644 --- a/common/buildcraft/builders/snapshot/BlueprintBuilder.java +++ b/common/buildcraft/builders/snapshot/BlueprintBuilder.java @@ -10,9 +10,9 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; @@ -106,19 +106,17 @@ private List tryExtractRequired(List requiredItems, List getToBreak() { + protected Set getToBreak() { return Optional.ofNullable(getBuildingInfo()) .map(buildingInfo -> buildingInfo.toBreak) - .orElse(Collections.emptyList()); + .orElse(Collections.emptySet()); } @Override - protected List getToPlace() { + protected Set getToPlace() { return Optional.ofNullable(getBuildingInfo()) - .map(buildingInfo -> getBuildingInfo().toPlace) - .map(Map::keySet) - .>map(ArrayList::new) - .orElse(Collections.emptyList()); + .map(buildingInfo -> getBuildingInfo().toPlace.keySet()) + .orElse(Collections.emptySet()); } @Override diff --git a/common/buildcraft/builders/snapshot/SnapshotBuilder.java b/common/buildcraft/builders/snapshot/SnapshotBuilder.java index f10683c74b..7b097a5954 100644 --- a/common/buildcraft/builders/snapshot/SnapshotBuilder.java +++ b/common/buildcraft/builders/snapshot/SnapshotBuilder.java @@ -8,10 +8,7 @@ import java.io.IOException; import java.util.ArrayDeque; -import java.util.ArrayList; import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -190,9 +187,9 @@ public void invalidate() { } } - protected abstract List getToBreak(); + protected abstract Set getToBreak(); - protected abstract List getToPlace(); + protected abstract Set getToPlace(); protected abstract boolean canPlace(BlockPos blockPos); @@ -485,7 +482,7 @@ public boolean tick() { } protected void check(BlockPos blockPos) { - checkResults.values().forEach(set -> set.removeIf(Predicate.isEqual(blockPos))); + checkResults.values().forEach(set -> set.remove(blockPos)); if (getToBreak().contains(blockPos)) { if (tile.getWorldBC().isAirBlock(blockPos)) { checkResults.get(CheckResult.CORRECT).add(blockPos); diff --git a/common/buildcraft/builders/snapshot/Template.java b/common/buildcraft/builders/snapshot/Template.java index 65ad064f04..6b14b78b33 100644 --- a/common/buildcraft/builders/snapshot/Template.java +++ b/common/buildcraft/builders/snapshot/Template.java @@ -6,8 +6,8 @@ package buildcraft.builders.snapshot; -import java.util.ArrayList; -import java.util.List; +import java.util.HashSet; +import java.util.Set; import java.util.stream.Stream; import net.minecraft.nbt.NBTTagCompound; @@ -85,8 +85,8 @@ public class BuildingInfo { public final BlockPos basePos; public final Rotation rotation; public final Box box; - public final List toBreak = new ArrayList<>(); - public final List toPlace = new ArrayList<>(); + public final Set toBreak = new HashSet<>(); + public final Set toPlace = new HashSet<>(); public BuildingInfo(BlockPos basePos, Rotation rotation) { this.basePos = basePos; diff --git a/common/buildcraft/builders/snapshot/TemplateBuilder.java b/common/buildcraft/builders/snapshot/TemplateBuilder.java index c0ba8a48eb..55177f0c09 100644 --- a/common/buildcraft/builders/snapshot/TemplateBuilder.java +++ b/common/buildcraft/builders/snapshot/TemplateBuilder.java @@ -9,6 +9,7 @@ import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.Set; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; @@ -31,17 +32,17 @@ private Template.BuildingInfo getBuildingInfo() { } @Override - protected List getToBreak() { + protected Set getToBreak() { return Optional.ofNullable(getBuildingInfo()) .map(buildingInfo -> buildingInfo.toBreak) - .orElse(Collections.emptyList()); + .orElse(Collections.emptySet()); } @Override - protected List getToPlace() { + protected Set getToPlace() { return Optional.ofNullable(getBuildingInfo()) .map(buildingInfo -> buildingInfo.toPlace) - .orElse(Collections.emptyList()); + .orElse(Collections.emptySet()); } @Override From dabb84f357b198176d90813cc3253459b59107e8 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Mon, 26 Jun 2017 10:59:18 +0300 Subject: [PATCH 28/89] Fix limitions and rendering --- .../builders/client/render/RenderSnapshotBuilder.java | 4 ++-- common/buildcraft/builders/snapshot/SnapshotBuilder.java | 6 +++--- common/buildcraft/builders/tile/TileFiller.java | 3 +-- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/common/buildcraft/builders/client/render/RenderSnapshotBuilder.java b/common/buildcraft/builders/client/render/RenderSnapshotBuilder.java index 8aa3885bee..ad5287e604 100644 --- a/common/buildcraft/builders/client/render/RenderSnapshotBuilder.java +++ b/common/buildcraft/builders/client/render/RenderSnapshotBuilder.java @@ -51,7 +51,7 @@ public static void render( y - tilePos.getY() + pos.yCoord, z - tilePos.getZ() + pos.zCoord, item, - world.getCombinedLight(tilePos, 0), + world.getCombinedLight(new BlockPos(pos), 0), EnumFacing.SOUTH, vb ); @@ -87,7 +87,7 @@ public static void render( 1D ) * (BuildCraftLaserManager.POWERS.length - 1) )], - robotPos, + robotPos.subtract(new Vec3d(0, 0.4, 0)), new Vec3d(breakTask.pos).add(VecUtil.VEC_HALF), 1 / 16D ), diff --git a/common/buildcraft/builders/snapshot/SnapshotBuilder.java b/common/buildcraft/builders/snapshot/SnapshotBuilder.java index 7b097a5954..45b227e471 100644 --- a/common/buildcraft/builders/snapshot/SnapshotBuilder.java +++ b/common/buildcraft/builders/snapshot/SnapshotBuilder.java @@ -417,7 +417,7 @@ public boolean tick() { target - breakTask.power, tile.getBattery().getStored() / breakTasks.size() ), - MjAPI.MJ / 10 + 10 * MjAPI.MJ ) ); if (breakTask.power >= target) { @@ -464,7 +464,7 @@ public boolean tick() { target - placeTask.power, tile.getBattery().getStored() / placeTasks.size() ), - MjAPI.MJ / 10 + 10 * MjAPI.MJ ) ); if (placeTask.power >= target) { @@ -567,7 +567,7 @@ public PlaceTask(PacketBufferBC buffer) { } public long getTarget() { - return (long) (Math.min(10, Math.sqrt(pos.distanceSq(tile.getBuilderPos()))) * MjAPI.MJ); + return (long) (Math.sqrt(pos.distanceSq(tile.getBuilderPos())) * 10 * MjAPI.MJ); } public void writePayload(PacketBufferBC buffer) { diff --git a/common/buildcraft/builders/tile/TileFiller.java b/common/buildcraft/builders/tile/TileFiller.java index 28eb875fcc..dc19ab0b45 100644 --- a/common/buildcraft/builders/tile/TileFiller.java +++ b/common/buildcraft/builders/tile/TileFiller.java @@ -33,7 +33,6 @@ import buildcraft.api.tiles.IDebuggable; import buildcraft.lib.block.BlockBCBase_Neptune; -import buildcraft.lib.misc.BoundingBoxUtil; import buildcraft.lib.misc.NBTUtilBC; import buildcraft.lib.misc.data.IdAllocator; import buildcraft.lib.mj.MjBatteryReciver; @@ -212,7 +211,7 @@ public boolean hasFastRenderer() { @Nonnull @SideOnly(Side.CLIENT) public AxisAlignedBB getRenderBoundingBox() { - return addon == null ? super.getRenderBoundingBox() : BoundingBoxUtil.makeFrom(pos, addon.box.box); + return INFINITE_EXTENT_AABB; } @Override From 95e6773d44b6193ae037fcc7c080f9a146ee95a9 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Mon, 26 Jun 2017 11:08:57 +0300 Subject: [PATCH 29/89] Fix air check --- .../buildcraft/builders/tile/TileQuarry.java | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/common/buildcraft/builders/tile/TileQuarry.java b/common/buildcraft/builders/tile/TileQuarry.java index 9622e24eed..fe47559418 100644 --- a/common/buildcraft/builders/tile/TileQuarry.java +++ b/common/buildcraft/builders/tile/TileQuarry.java @@ -316,10 +316,13 @@ public void update() { boolean shouldBeFrame = ((x == min.getX() || x == max.getX()) && (y == min.getY() || y == max.getY())) || ((y == min.getY() || y == max.getY()) && (z == min.getZ() || z == max.getZ())) || ((z == min.getZ() || z == max.getZ()) && (x == min.getX() || x == max.getX())); - Block block = world.getBlockState(framePos).getBlock(); - if (((block != Blocks.AIR && !shouldBeFrame) || - (block != BCBuildersBlocks.frame && block != Blocks.AIR && shouldBeFrame)) && !canSkip(framePos)) { - breakPoses.add(framePos); + boolean isAir = world.isAirBlock(framePos); + if (shouldBeFrame + ? !isAir && world.getBlockState(framePos).getBlock() != BCBuildersBlocks.frame + : !isAir) { + if (!canSkip(framePos)) { + breakPoses.add(framePos); + } } } } @@ -347,8 +350,7 @@ public void update() { } for (BlockPos framePos : getFramePositions()) { - Block block = world.getBlockState(framePos).getBlock(); - if (block == Blocks.AIR) { + if (world.isAirBlock(framePos)) { drillPos = null; currentTask = new TaskAddFrame(framePos); sendNetworkUpdate(NET_RENDER_DATA); @@ -359,9 +361,9 @@ public void update() { if ((boxIterator == null || drillPos == null) && miningBox.isInitialized()) { boxIterator = new BoxIterator(miningBox, AxisOrder.getFor(EnumAxisOrder.XZY, AxisOrder.Inversion.NNN), true); while (world.isAirBlock(boxIterator.getCurrent()) || canSkip(boxIterator.getCurrent())) { - if (boxIterator.advance() == null) { - break; - } + if (boxIterator.advance() == null) { + break; + } } drillPos = new Vec3d(miningBox.closestInsideTo(pos)); } From 73693b85ed0c42a624c983c88486a7f42512f9e9 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Mon, 26 Jun 2017 11:45:58 +0300 Subject: [PATCH 30/89] Remove unneeded --- common/buildcraft/builders/snapshot/SnapshotBuilder.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/common/buildcraft/builders/snapshot/SnapshotBuilder.java b/common/buildcraft/builders/snapshot/SnapshotBuilder.java index 45b227e471..9fcd1960b2 100644 --- a/common/buildcraft/builders/snapshot/SnapshotBuilder.java +++ b/common/buildcraft/builders/snapshot/SnapshotBuilder.java @@ -345,8 +345,6 @@ public boolean tick() { cancelPlaceTask(placeTask); } } - breakTasks.removeIf(breakTask -> checkResults.get(CheckResult.CORRECT).contains(breakTask.pos)); - placeTasks.removeIf(placeTask -> checkResults.get(CheckResult.CORRECT).contains(placeTask.pos)); tile.getWorldBC().profiler.endSection(); boolean isDone = true; From e621552acac5494e77e2ab92c2f75074cb753278 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Mon, 26 Jun 2017 18:17:29 +0300 Subject: [PATCH 31/89] Additional shapes --- .../builders/addon/AddonFillingPlanner.java | 19 +- .../builders/container/ContainerFiller.java | 2 +- .../filling/EnumParameterPattern.java | 10 +- .../buildcraft/builders/filling/Filling.java | 182 ++++++++++-------- .../builders/filling/FillingCircle.java | 62 ++++++ .../builders/filling/FillingFrame.java | 25 +++ .../builders/filling/FillingPolygon.java | 50 +++++ .../builders/filling/FillingSquare.java | 24 +++ .../builders/gui/GuiFillingPlanner.java | 2 +- .../builders/snapshot/SnapshotBuilder.java | 2 +- .../buildcraft/builders/tile/TileFiller.java | 2 +- .../core/item/ItemMarkerConnector.java | 8 +- .../buildcraft/core/marker/volume/Addon.java | 3 + .../core/marker/volume/VolumeBox.java | 1 + common/buildcraft/lib/misc/DrawingUtil.java | 76 ++++++-- 15 files changed, 363 insertions(+), 105 deletions(-) create mode 100644 common/buildcraft/builders/filling/FillingCircle.java create mode 100644 common/buildcraft/builders/filling/FillingFrame.java create mode 100644 common/buildcraft/builders/filling/FillingPolygon.java create mode 100644 common/buildcraft/builders/filling/FillingSquare.java diff --git a/common/buildcraft/builders/addon/AddonFillingPlanner.java b/common/buildcraft/builders/addon/AddonFillingPlanner.java index d6df22cc70..6d007cc05d 100644 --- a/common/buildcraft/builders/addon/AddonFillingPlanner.java +++ b/common/buildcraft/builders/addon/AddonFillingPlanner.java @@ -38,14 +38,14 @@ public class AddonFillingPlanner extends Addon implements ISingleAddon { public boolean[][][] getFillingPlan() { BlockPos size = box.box.size(); - boolean[][][] fillingPlan = Filling.INSTANCE.getFillingPlan(size, parameters); + boolean[][][] fillingPlan = Filling.getFillingPlan(size, parameters); if (inverted) { - fillingPlan = Filling.INSTANCE.invertFillingPlan(size, fillingPlan); + fillingPlan = Filling.invertFillingPlan(size, fillingPlan); } return fillingPlan; } - public void markDirty() { + public void updateBuildingInfo() { Template template = new Template(); template.size = box.box.size(); template.offset = BlockPos.ORIGIN; @@ -53,6 +53,11 @@ public void markDirty() { buildingInfo = template.new BuildingInfo(box.box.min(), Rotation.NONE); } + @Override + public void onBoxSizeChange() { + updateBuildingInfo(); + } + @Override public IFastAddonRenderer getRenderer() { return new AddonDefaultRenderer(BCBuildersSprites.FILLING_PLANNER.getSprite()) @@ -62,7 +67,7 @@ public IFastAddonRenderer getRenderer() { @Override public void onAdded() { while (true) { - Class nextParameterClass = Filling.INSTANCE.getNextParameterClass(parameters); + Class nextParameterClass = Filling.getNextParameterClass(parameters); if (nextParameterClass != null) { // noinspection ConstantConditions parameters.add(nextParameterClass.getEnumConstants()[0]); @@ -70,7 +75,7 @@ public void onAdded() { break; } } - markDirty(); + updateBuildingInfo(); } @Override @@ -100,7 +105,7 @@ public void readFromNBT(NBTTagCompound nbt) { ) .map(IParameter::readFromNBT) .forEach(parameters::add); - markDirty(); + updateBuildingInfo(); } @Override @@ -115,6 +120,6 @@ public void fromBytes(ByteBuf buf) { parameters.clear(); IntStream.range(0, buf.readInt()).mapToObj(i -> IParameter.fromBytes(buf)).forEach(parameters::add); inverted = buf.readBoolean(); - markDirty(); + updateBuildingInfo(); } } diff --git a/common/buildcraft/builders/container/ContainerFiller.java b/common/buildcraft/builders/container/ContainerFiller.java index ffc534b4bb..1a5a33e373 100644 --- a/common/buildcraft/builders/container/ContainerFiller.java +++ b/common/buildcraft/builders/container/ContainerFiller.java @@ -28,7 +28,7 @@ public ContainerFiller(EntityPlayer player, TileFiller tile) { addSlotToContainer(new SlotBase(tile.invResources, sx + sy * 9, 8 + sx * 18, 85 + sy * 18) { @Override public boolean isItemValid(@Nonnull ItemStack stack) { - return Filling.INSTANCE.getItemBlocks().contains(stack.getItem()); + return Filling.getItemBlocks().contains(stack.getItem()); } }); } diff --git a/common/buildcraft/builders/filling/EnumParameterPattern.java b/common/buildcraft/builders/filling/EnumParameterPattern.java index 25ff38ede5..34ca4e3f73 100644 --- a/common/buildcraft/builders/filling/EnumParameterPattern.java +++ b/common/buildcraft/builders/filling/EnumParameterPattern.java @@ -7,10 +7,14 @@ package buildcraft.builders.filling; public enum EnumParameterPattern implements IParameter { - FRAME, + TRIANGLE, SQUARE, - SPHERE, - CIRCLE + PENTAGON, + HEXAGON, + OCTAGON, + CIRCLE, + FRAME, + SPHERE // TODO: TILT // TODO?: FLATTEN } diff --git a/common/buildcraft/builders/filling/Filling.java b/common/buildcraft/builders/filling/Filling.java index ebf689b87a..8bf5e1d066 100644 --- a/common/buildcraft/builders/filling/Filling.java +++ b/common/buildcraft/builders/filling/Filling.java @@ -14,6 +14,7 @@ import java.util.function.Function; import java.util.stream.StreamSupport; +import javax.vecmath.Point2d; import javax.vecmath.Point2i; import net.minecraft.init.Items; @@ -23,17 +24,44 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; -import buildcraft.lib.misc.DrawingUtil; +@SuppressWarnings("WeakerAccess") +public class Filling { + private static List itemBlocks = new ArrayList<>(); + private static final List TRIANGLE_POINTS = Arrays.asList( + new Point2d(1, 0.5), + new Point2d(0.2500000000000001, 0.9330127018922194), + new Point2d(0.24999999999999978, 0.06698729810778076) + ); + private static final List PENTAGON_POINTS = Arrays.asList( + new Point2d(1, 0.5), + new Point2d(0.6545084971874737, 0.9755282581475768), + new Point2d(0.09549150281252633, 0.7938926261462367), + new Point2d(0.09549150281252627, 0.2061073738537635), + new Point2d(0.6545084971874736, 0.02447174185242318) + ); + private static final List HEXAGON_POINTS = Arrays.asList( + new Point2d(1, 0.5), + new Point2d(0.75, 0.9330127018922193), + new Point2d(0.2500000000000001, 0.9330127018922194), + new Point2d(0, 0.5000000000000001), + new Point2d(0.24999999999999978, 0.06698729810778076), + new Point2d(0.7499999999999997, 0.06698729810778048) + ); + private static final List OCTAGON_POINTS = Arrays.asList( + new Point2d(1, 0.5), + new Point2d(0.8535533905932737, 0.8535533905932737), + new Point2d(0.5, 1), + new Point2d(0.14644660940672627, 0.8535533905932737), + new Point2d(0, 0.5), + new Point2d(0.14644660940672616, 0.14644660940672627), + new Point2d(0.5, 0), + new Point2d(0.8535533905932737, 0.14644660940672616) + ); -public enum Filling { - INSTANCE; - - private List itemBlocks = new ArrayList<>(); - - Filling() { + static { StreamSupport.stream(Item.REGISTRY.spliterator(), false) .filter(item -> item instanceof ItemBlock || item instanceof ItemBlockSpecial) - .forEach(this::addItemBlock); + .forEach(Filling::addItemBlock); addItemBlock( Items.BED, Items.OAK_DOOR, @@ -48,23 +76,26 @@ public enum Filling { ); } - public void addItemBlock(Item... items) { + public static void addItemBlock(Item... items) { itemBlocks.addAll(Arrays.asList(items)); } - public List getItemBlocks() { + public static List getItemBlocks() { return new ArrayList<>(itemBlocks); } - public Class getNextParameterClass(List parameters) { + public static Class getNextParameterClass(List parameters) { if (parameters.size() == 0) { return EnumParameterPattern.class; } EnumParameterPattern parameterPattern = (EnumParameterPattern) parameters.get(0); - if (parameterPattern == EnumParameterPattern.FRAME) { + if (parameterPattern == EnumParameterPattern.TRIANGLE) { if (parameters.size() == 1) { return EnumParameterType.class; } + if (parameters.size() == 2) { + return EnumParameterAxis.class; + } } if (parameterPattern == EnumParameterPattern.SQUARE) { if (parameters.size() == 1) { @@ -77,10 +108,29 @@ public Class getNextParameterClass(List parame } } } - if (parameterPattern == EnumParameterPattern.SPHERE) { + if (parameterPattern == EnumParameterPattern.PENTAGON) { if (parameters.size() == 1) { return EnumParameterType.class; } + if (parameters.size() == 2) { + return EnumParameterAxis.class; + } + } + if (parameterPattern == EnumParameterPattern.HEXAGON) { + if (parameters.size() == 1) { + return EnumParameterType.class; + } + if (parameters.size() == 2) { + return EnumParameterAxis.class; + } + } + if (parameterPattern == EnumParameterPattern.OCTAGON) { + if (parameters.size() == 1) { + return EnumParameterType.class; + } + if (parameters.size() == 2) { + return EnumParameterAxis.class; + } } if (parameterPattern == EnumParameterPattern.CIRCLE) { if (parameters.size() == 1) { @@ -90,10 +140,20 @@ public Class getNextParameterClass(List parame return EnumParameterAxis.class; } } + if (parameterPattern == EnumParameterPattern.FRAME) { + if (parameters.size() == 1) { + return EnumParameterType.class; + } + } + if (parameterPattern == EnumParameterPattern.SPHERE) { + if (parameters.size() == 1) { + return EnumParameterType.class; + } + } return null; } - public boolean[][][] generateFillingPlanByFunction(BlockPos size, + public static boolean[][][] generateFillingPlanByFunction(BlockPos size, Function function) { boolean[][][] fillingPlan = new boolean[size.getX()][size.getY()][size.getZ()]; for (int z = 0; z < size.getZ(); z++) { @@ -106,7 +166,7 @@ public boolean[][][] generateFillingPlanByFunction(BlockPos size, return fillingPlan; } - public boolean[][][] generateFillingPlanByFunctionInAxis(BlockPos size, + public static boolean[][][] generateFillingPlanByFunctionInAxis(BlockPos size, EnumFacing.Axis axis, BiFunction function) { switch (axis) { @@ -130,7 +190,7 @@ public boolean[][][] generateFillingPlanByFunctionInAxis(BlockPos size, } } - public boolean[][][] generateFillingPlanByFunctionInAxis(BlockPos size, + public static boolean[][][] generateFillingPlanByFunctionInAxis(BlockPos size, EnumFacing.Axis axis, BiConsumer function) { Point2i flatSize; @@ -161,80 +221,48 @@ public boolean[][][] generateFillingPlanByFunctionInAxis(BlockPos size, } } - public boolean[][][] getFillingPlan(BlockPos size, List parameters) { + public static boolean[][][] getFillingPlan(BlockPos size, List parameters) { EnumParameterPattern parameterPattern = (EnumParameterPattern) parameters.get(0); - BlockPos sizeS = size.add(-1, -1, -1); - if (parameterPattern == EnumParameterPattern.FRAME) { + if (parameterPattern == EnumParameterPattern.TRIANGLE) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); - return generateFillingPlanByFunction(size, pos -> - parameterType == EnumParameterType.FILLED ? - pos.getX() == 0 || pos.getX() == sizeS.getX() || - pos.getY() == 0 || pos.getY() == sizeS.getY() || - pos.getZ() == 0 || pos.getZ() == sizeS.getZ() : - ((pos.getX() == 0 || pos.getX() == sizeS.getX()) && (pos.getY() == 0 || pos.getY() == sizeS.getY())) || - ((pos.getY() == 0 || pos.getY() == sizeS.getY()) && (pos.getZ() == 0 || pos.getZ() == sizeS.getZ())) || - ((pos.getZ() == 0 || pos.getZ() == sizeS.getZ()) && (pos.getX() == 0 || pos.getX() == sizeS.getX())) - ); + EnumParameterAxis parameterAxis = (EnumParameterAxis) parameters.get(2); + return FillingPolygon.get(size, parameterType, parameterAxis, TRIANGLE_POINTS); } if (parameterPattern == EnumParameterPattern.SQUARE) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); - if (parameterType == EnumParameterType.FILLED) { - return generateFillingPlanByFunction(size, pos -> true); - } else { - EnumParameterAxis parameterAxis = (EnumParameterAxis) parameters.get(2); - return generateFillingPlanByFunctionInAxis(size, parameterAxis.axis, (pos, flatSize) -> - pos.getX() == 0 || pos.getX() == flatSize.getX() - 1 || - pos.getY() == 0 || pos.getY() == flatSize.getY() - 1 - ); - } + EnumParameterAxis parameterAxis = parameterType == EnumParameterType.EMPTY + ? (EnumParameterAxis) parameters.get(2) + : null; + return FillingSquare.get(size, parameterType, parameterAxis); + } + if (parameterPattern == EnumParameterPattern.PENTAGON) { + EnumParameterType parameterType = (EnumParameterType) parameters.get(1); + EnumParameterAxis parameterAxis = (EnumParameterAxis) parameters.get(2); + return FillingPolygon.get(size, parameterType, parameterAxis, PENTAGON_POINTS); + } + if (parameterPattern == EnumParameterPattern.HEXAGON) { + EnumParameterType parameterType = (EnumParameterType) parameters.get(1); + EnumParameterAxis parameterAxis = (EnumParameterAxis) parameters.get(2); + return FillingPolygon.get(size, parameterType, parameterAxis, HEXAGON_POINTS); + } + if (parameterPattern == EnumParameterPattern.OCTAGON) { + EnumParameterType parameterType = (EnumParameterType) parameters.get(1); + EnumParameterAxis parameterAxis = (EnumParameterAxis) parameters.get(2); + return FillingPolygon.get(size, parameterType, parameterAxis, OCTAGON_POINTS); } if (parameterPattern == EnumParameterPattern.CIRCLE) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); EnumParameterAxis parameterAxis = (EnumParameterAxis) parameters.get(2); - return generateFillingPlanByFunctionInAxis(size, parameterAxis.axis, (flatSize, flatFillingPlan) -> { - DrawingUtil.drawEllipse( - flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, - flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, - flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, - flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, - parameterType == EnumParameterType.FILLED, - (x, y) -> { - List positions = new ArrayList<>(); - positions.add( - new Point2i( - flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, - flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y - ) - ); - if (flatSize.x % 2 == 0 && x == flatSize.x / 2) { - positions.add( - new Point2i( - x + 1, - flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y - ) - ); - } - if (flatSize.y % 2 == 0 && y == flatSize.y / 2) { - positions.add( - new Point2i( - flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, - y + 1 - ) - ); - } - for (Point2i p : positions) { - if (p.x >= 0 && p.y >= 0 && p.x < flatSize.x && p.y < flatSize.y) { - flatFillingPlan[p.x][p.y] = true; - } - } - } - ); - }); + return FillingCircle.get(size, parameterType, parameterAxis); + } + if (parameterPattern == EnumParameterPattern.FRAME) { + EnumParameterType parameterType = (EnumParameterType) parameters.get(1); + return FillingFrame.get(size, parameterType); } return generateFillingPlanByFunction(size, pos -> false); } - public boolean[][][] invertFillingPlan(BlockPos size, boolean[][][] fillingPlan) { + public static boolean[][][] invertFillingPlan(BlockPos size, boolean[][][] fillingPlan) { return generateFillingPlanByFunction(size, pos -> !fillingPlan[pos.getX()][pos.getY()][pos.getZ()]); } } diff --git a/common/buildcraft/builders/filling/FillingCircle.java b/common/buildcraft/builders/filling/FillingCircle.java new file mode 100644 index 0000000000..bda7387258 --- /dev/null +++ b/common/buildcraft/builders/filling/FillingCircle.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.builders.filling; + +import java.util.ArrayList; +import java.util.List; + +import javax.vecmath.Point2i; + +import net.minecraft.util.math.BlockPos; + +import buildcraft.lib.misc.DrawingUtil; + +public class FillingCircle { + public static boolean[][][] get(BlockPos size, + EnumParameterType parameterType, + EnumParameterAxis parameterAxis) { + return Filling.generateFillingPlanByFunctionInAxis(size, parameterAxis.axis, (flatSize, flatFillingPlan) -> { + DrawingUtil.drawEllipse( + flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, + flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, + flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, + flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, + parameterType == EnumParameterType.FILLED, + (x, y) -> { + List positions = new ArrayList<>(); + positions.add( + new Point2i( + flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, + flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y + ) + ); + if (flatSize.x % 2 == 0 && x == flatSize.x / 2) { + positions.add( + new Point2i( + x + 1, + flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y + ) + ); + } + if (flatSize.y % 2 == 0 && y == flatSize.y / 2) { + positions.add( + new Point2i( + flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, + y + 1 + ) + ); + } + for (Point2i p : positions) { + if (p.x >= 0 && p.y >= 0 && p.x < flatSize.x && p.y < flatSize.y) { + flatFillingPlan[p.x][p.y] = true; + } + } + } + ); + }); + } +} diff --git a/common/buildcraft/builders/filling/FillingFrame.java b/common/buildcraft/builders/filling/FillingFrame.java new file mode 100644 index 0000000000..5a44c18eee --- /dev/null +++ b/common/buildcraft/builders/filling/FillingFrame.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.builders.filling; + +import net.minecraft.util.math.BlockPos; + +public class FillingFrame { + public static boolean[][][] get(BlockPos size, + EnumParameterType parameterType) { + BlockPos sizeS = size.add(-1, -1, -1); + return Filling.generateFillingPlanByFunction(size, pos -> + parameterType == EnumParameterType.FILLED ? + pos.getX() == 0 || pos.getX() == sizeS.getX() || + pos.getY() == 0 || pos.getY() == sizeS.getY() || + pos.getZ() == 0 || pos.getZ() == sizeS.getZ() : + ((pos.getX() == 0 || pos.getX() == sizeS.getX()) && (pos.getY() == 0 || pos.getY() == sizeS.getY())) || + ((pos.getY() == 0 || pos.getY() == sizeS.getY()) && (pos.getZ() == 0 || pos.getZ() == sizeS.getZ())) || + ((pos.getZ() == 0 || pos.getZ() == sizeS.getZ()) && (pos.getX() == 0 || pos.getX() == sizeS.getX())) + ); + } +} diff --git a/common/buildcraft/builders/filling/FillingPolygon.java b/common/buildcraft/builders/filling/FillingPolygon.java new file mode 100644 index 0000000000..b6e2b7f483 --- /dev/null +++ b/common/buildcraft/builders/filling/FillingPolygon.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.builders.filling; + +import java.util.List; + +import javax.vecmath.Point2d; + +import net.minecraft.util.math.BlockPos; + +import buildcraft.lib.misc.DrawingUtil; +import buildcraft.lib.misc.MathUtil; + +public class FillingPolygon { + public static boolean[][][] get(BlockPos size, + EnumParameterType parameterType, + EnumParameterAxis parameterAxis, + List points) { + return Filling.generateFillingPlanByFunctionInAxis(size, parameterAxis.axis, (flatSize, flatFillingPlan) -> { + for (int i = 0; i < points.size(); i++) { + Point2d point1 = points.get(i % points.size()); + Point2d point2 = points.get((i + 1) % points.size()); + DrawingUtil.drawLine( + (int) Math.round(point1.x * (flatSize.x - 1)), + (int) Math.round(point1.y * (flatSize.y - 1)), + (int) Math.round(point2.x * (flatSize.x - 1)), + (int) Math.round(point2.y * (flatSize.y - 1)), + (x, y) -> + flatFillingPlan + [MathUtil.clamp(x, 0, flatSize.x - 1)] + [MathUtil.clamp(y, 0, flatSize.y - 1)] + = true + ); + } + if (parameterType == EnumParameterType.FILLED) { + DrawingUtil.fill( + flatFillingPlan, + flatSize.x / 2, + flatSize.y / 2, + flatSize.x, + flatSize.y + ); + } + }); + } +} diff --git a/common/buildcraft/builders/filling/FillingSquare.java b/common/buildcraft/builders/filling/FillingSquare.java new file mode 100644 index 0000000000..d41f501dbb --- /dev/null +++ b/common/buildcraft/builders/filling/FillingSquare.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.builders.filling; + +import net.minecraft.util.math.BlockPos; + +public class FillingSquare { + public static boolean[][][] get(BlockPos size, + EnumParameterType parameterType, + EnumParameterAxis parameterAxis) { + if (parameterType == EnumParameterType.FILLED) { + return Filling.generateFillingPlanByFunction(size, pos -> true); + } else { + return Filling.generateFillingPlanByFunctionInAxis(size, parameterAxis.axis, (pos, flatSize) -> + pos.getX() == 0 || pos.getX() == flatSize.getX() - 1 || + pos.getY() == 0 || pos.getY() == flatSize.getY() - 1 + ); + } + } +} diff --git a/common/buildcraft/builders/gui/GuiFillingPlanner.java b/common/buildcraft/builders/gui/GuiFillingPlanner.java index d13e5b0919..ee1c2761f4 100644 --- a/common/buildcraft/builders/gui/GuiFillingPlanner.java +++ b/common/buildcraft/builders/gui/GuiFillingPlanner.java @@ -99,7 +99,7 @@ protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOEx container.parameters.set(i, values[(parameter.getOrdinal() + values.length + (mouseButton == 1 ? -1 : 1)) % values.length]); int j = i + 1; while (true) { - Class nextParameterClass = Filling.INSTANCE.getNextParameterClass(container.parameters.subList(0, Math.min(j, container.parameters.size()))); + Class nextParameterClass = Filling.getNextParameterClass(container.parameters.subList(0, Math.min(j, container.parameters.size()))); if (j < container.parameters.size()) { if (container.parameters.get(j).getClass().equals(nextParameterClass)) { j++; diff --git a/common/buildcraft/builders/snapshot/SnapshotBuilder.java b/common/buildcraft/builders/snapshot/SnapshotBuilder.java index 9fcd1960b2..4253107f4f 100644 --- a/common/buildcraft/builders/snapshot/SnapshotBuilder.java +++ b/common/buildcraft/builders/snapshot/SnapshotBuilder.java @@ -238,7 +238,7 @@ public Vec3d getPlaceTaskItemPos(PlaceTask placeTask) { double progress = placeTask.power * 1D / placeTask.getTarget(); return new Vec3d(tile.getBuilderPos()) .add(height.scale(progress)) - .add(new Vec3d(0, Math.sin(progress * Math.PI) * (height.yCoord + 1), 0)) + .add(new Vec3d(0, Math.sin(progress * Math.PI) * (Math.abs(height.yCoord) + 1), 0)) .add(new Vec3d(0.5, 1, 0.5)); } diff --git a/common/buildcraft/builders/tile/TileFiller.java b/common/buildcraft/builders/tile/TileFiller.java index dc19ab0b45..6db60dd4af 100644 --- a/common/buildcraft/builders/tile/TileFiller.java +++ b/common/buildcraft/builders/tile/TileFiller.java @@ -63,7 +63,7 @@ public class TileFiller extends TileBC_Neptune implements ITickable, IDebuggable "resources", new ItemHandlerSimple( 27, - (slot, stack) -> Filling.INSTANCE.getItemBlocks().contains(stack.getItem()), + (slot, stack) -> Filling.getItemBlocks().contains(stack.getItem()), StackInsertionFunction.getDefaultInserter(), this::onSlotChange ), diff --git a/common/buildcraft/core/item/ItemMarkerConnector.java b/common/buildcraft/core/item/ItemMarkerConnector.java index d7889ed7c8..8b627f3caf 100644 --- a/common/buildcraft/core/item/ItemMarkerConnector.java +++ b/common/buildcraft/core/item/ItemMarkerConnector.java @@ -209,8 +209,12 @@ private ActionResult newVolumeCacheStuff_onItemRightClick(ItemStack s if (editing.getZ() == min.getZ()) { held = VecUtil.replaceValue(held, EnumFacing.Axis.Z, max.getZ()); } - bestBox.setHeldDistOldMinOldMax(held, Math.max(1.5, bestDist + 0.5), bestBox.box.min(), bestBox.box - .max()); + bestBox.setHeldDistOldMinOldMax( + held, + Math.max(1.5, bestDist + 0.5), + bestBox.box.min(), + bestBox.box.max() + ); volumeBoxes.markDirty(); return new ActionResult<>(EnumActionResult.SUCCESS, stack); } diff --git a/common/buildcraft/core/marker/volume/Addon.java b/common/buildcraft/core/marker/volume/Addon.java index f772a3fd30..6cdfcddda4 100644 --- a/common/buildcraft/core/marker/volume/Addon.java +++ b/common/buildcraft/core/marker/volume/Addon.java @@ -39,6 +39,9 @@ public void onAdded() { public void onRemoved() { } + public void onBoxSizeChange() { + } + public void onPlayerRightClick(EntityPlayer player) { } diff --git a/common/buildcraft/core/marker/volume/VolumeBox.java b/common/buildcraft/core/marker/volume/VolumeBox.java index 9cfd14ebb5..a8c9d04387 100644 --- a/common/buildcraft/core/marker/volume/VolumeBox.java +++ b/common/buildcraft/core/marker/volume/VolumeBox.java @@ -110,6 +110,7 @@ public void cancelEditing() { public void confirmEditing() { player = null; resetEditing(); + addons.values().forEach(Addon::onBoxSizeChange); } public void pauseEditing() { diff --git a/common/buildcraft/lib/misc/DrawingUtil.java b/common/buildcraft/lib/misc/DrawingUtil.java index df79a2ee1b..fd2a33aedf 100644 --- a/common/buildcraft/lib/misc/DrawingUtil.java +++ b/common/buildcraft/lib/misc/DrawingUtil.java @@ -6,27 +6,33 @@ package buildcraft.lib.misc; +import java.util.ArrayDeque; +import java.util.Queue; import java.util.function.BiConsumer; +import javax.vecmath.Point2i; + public class DrawingUtil { @SuppressWarnings("Duplicates") public static void drawEllipse(int cx, int cy, - int width, - int height, + int rx, + int ry, boolean filled, BiConsumer drawPixel) { - int a2 = width * width; - int b2 = height * height; - int fa2 = 4 * a2, fb2 = 4 * b2; - int x, y, sigma; + int rx2 = rx * rx; + int ry2 = ry * ry; - for (x = 0, y = height, sigma = 2 * b2 + a2 * (1 - 2 * height); b2 * x <= a2 * y; x++) { + for (int x = 0, y = ry, sigma = 2 * ry2 + rx2 * (1 - 2 * ry); ry2 * x <= rx2 * y; x++) { if (filled) { for (int i = -x; i <= x; i++) { drawPixel.accept(cx + i, cy + y); drawPixel.accept(cx + i, cy - y); } + for (int i = -y; i <= y; i++) { + drawPixel.accept(cx + x, cx + i); + drawPixel.accept(cx - x, cx + i); + } } else { drawPixel.accept(cx + x, cy + y); drawPixel.accept(cx - x, cy + y); @@ -34,18 +40,22 @@ public static void drawEllipse(int cx, drawPixel.accept(cx - x, cy - y); } if (sigma >= 0) { - sigma += fa2 * (1 - y); + sigma += 4 * rx2 * (1 - y); y--; } - sigma += b2 * ((4 * x) + 6); + sigma += ry2 * ((4 * x) + 6); } - for (x = width, y = 0, sigma = 2 * a2 + b2 * (1 - 2 * width); a2 * y <= b2 * x; y++) { + for (int x = rx, y = 0, sigma = 2 * rx2 + ry2 * (1 - 2 * rx); rx2 * y <= ry2 * x; y++) { if (filled) { for (int i = -x; i <= x; i++) { drawPixel.accept(cx + i, cy + y); drawPixel.accept(cx + i, cy - y); } + for (int i = -y; i <= y; i++) { + drawPixel.accept(cx + x, cx + i); + drawPixel.accept(cx - x, cx + i); + } } else { drawPixel.accept(cx + x, cy + y); drawPixel.accept(cx - x, cy + y); @@ -53,10 +63,52 @@ public static void drawEllipse(int cx, drawPixel.accept(cx - x, cy - y); } if (sigma >= 0) { - sigma += fb2 * (1 - x); + sigma += 4 * ry2 * (1 - x); x--; } - sigma += a2 * ((4 * y) + 6); + sigma += rx2 * ((4 * y) + 6); + } + } + + public static void drawLine(int x1, int y1, int x2, int y2, BiConsumer drawPixel) { + int currentX = x1; + int currentY = y1; + int dx = Math.abs(x2 - x1); + int dy = Math.abs(y2 - y1); + int error = (dx > dy ? dx : -dy) / 2; + + while (true) { + drawPixel.accept(currentX, currentY); + if (currentX == x2 && currentY == y2) { + break; + } + if (error * 2 > -dx) { + error -= dy; + currentX += x1 < x2 ? 1 : -1; + } + if (error * 2 < dy) { + error += dx; + currentY += y1 < y2 ? 1 : -1; + } + } + } + + public static void fill(boolean[][] data, int startX, int startY, int width, int height) { + Queue queue = new ArrayDeque<>(); + queue.add(new Point2i(startX, startY)); + while (!queue.isEmpty()) { + Point2i point = queue.poll(); + if (point.x < 0 || point.y < 0 || point.x >= width || point.y >= height) { + continue; + } + if (data[point.x][point.y]) { + continue; + } + data[point.x][point.y] = true; + queue.add(new Point2i(point.x - 1, point.y)); + queue.add(new Point2i(point.x + 1, point.y)); + queue.add(new Point2i(point.x, point.y - 1)); + queue.add(new Point2i(point.x, point.y + 1)); } } } From d30dc54c304dfe34524ec966785593f4083f0c36 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Mon, 26 Jun 2017 18:19:51 +0300 Subject: [PATCH 32/89] Fix numbers --- common/buildcraft/builders/filling/Filling.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/common/buildcraft/builders/filling/Filling.java b/common/buildcraft/builders/filling/Filling.java index 8bf5e1d066..c690aeff62 100644 --- a/common/buildcraft/builders/filling/Filling.java +++ b/common/buildcraft/builders/filling/Filling.java @@ -29,8 +29,8 @@ public class Filling { private static List itemBlocks = new ArrayList<>(); private static final List TRIANGLE_POINTS = Arrays.asList( new Point2d(1, 0.5), - new Point2d(0.2500000000000001, 0.9330127018922194), - new Point2d(0.24999999999999978, 0.06698729810778076) + new Point2d(0.25, 0.9330127018922194), + new Point2d(0.25, 0.06698729810778076) ); private static final List PENTAGON_POINTS = Arrays.asList( new Point2d(1, 0.5), @@ -42,10 +42,10 @@ public class Filling { private static final List HEXAGON_POINTS = Arrays.asList( new Point2d(1, 0.5), new Point2d(0.75, 0.9330127018922193), - new Point2d(0.2500000000000001, 0.9330127018922194), - new Point2d(0, 0.5000000000000001), - new Point2d(0.24999999999999978, 0.06698729810778076), - new Point2d(0.7499999999999997, 0.06698729810778048) + new Point2d(0.25, 0.9330127018922194), + new Point2d(0, 0.5), + new Point2d(0.25, 0.06698729810778076), + new Point2d(0.75, 0.06698729810778048) ); private static final List OCTAGON_POINTS = Arrays.asList( new Point2d(1, 0.5), From fc4d98a3e7c6b3a6391fb8726ad57f7a97cad89b Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Mon, 26 Jun 2017 19:10:15 +0300 Subject: [PATCH 33/89] Fix ItemSnapshot#getSubItems --- common/buildcraft/builders/item/ItemSnapshot.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/common/buildcraft/builders/item/ItemSnapshot.java b/common/buildcraft/builders/item/ItemSnapshot.java index 2693eca625..2f0896d684 100644 --- a/common/buildcraft/builders/item/ItemSnapshot.java +++ b/common/buildcraft/builders/item/ItemSnapshot.java @@ -72,8 +72,8 @@ public int getItemStackLimit(ItemStack stack) { @Override public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { - subItems.add(new ItemStack(item, 1, 2));// clean blueprint - subItems.add(new ItemStack(item, 1));// clean template + subItems.add(getClean(EnumSnapshotType.TEMPLATE)); + subItems.add(getClean(EnumSnapshotType.BLUEPRINT)); } @Override From aecfa180df14f31136943ef267ced7e39d600c14 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Mon, 26 Jun 2017 23:53:34 +0100 Subject: [PATCH 34/89] Fix build -- @afdw is this the right method to call? --- .../buildcraft/builders/container/ContainerFillingPlanner.java | 2 +- common/buildcraft/builders/gui/GuiFillingPlanner.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/common/buildcraft/builders/container/ContainerFillingPlanner.java b/common/buildcraft/builders/container/ContainerFillingPlanner.java index 740baeaf3f..5e772a9e7a 100644 --- a/common/buildcraft/builders/container/ContainerFillingPlanner.java +++ b/common/buildcraft/builders/container/ContainerFillingPlanner.java @@ -70,7 +70,7 @@ public void readMessage(int id, PacketBufferBC buffer, Side side, MessageContext inverted = buffer.readBoolean(); addon.parameters = parameters; addon.inverted = inverted; - addon.markDirty(); + addon.updateBuildingInfo(); WorldSavedDataVolumeBoxes.get(player.world).markDirty(); } } diff --git a/common/buildcraft/builders/gui/GuiFillingPlanner.java b/common/buildcraft/builders/gui/GuiFillingPlanner.java index ee1c2761f4..620184ed6a 100644 --- a/common/buildcraft/builders/gui/GuiFillingPlanner.java +++ b/common/buildcraft/builders/gui/GuiFillingPlanner.java @@ -119,7 +119,7 @@ protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOEx found.set(true); } }); - container.addon.markDirty(); + container.addon.updateBuildingInfo(); if (!found.get()) { super.mouseClicked(mouseX, mouseY, mouseButton); } From 4a6853ca7e54bc03bfdccb19500ac79e3528e8c7 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Mon, 26 Jun 2017 23:56:26 +0100 Subject: [PATCH 35/89] Allow the pump to pump up non-default fluids. Fixes some bug that I cant find. --- common/buildcraft/lib/misc/BlockUtil.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/common/buildcraft/lib/misc/BlockUtil.java b/common/buildcraft/lib/misc/BlockUtil.java index ef106e25d4..6b5cf1a414 100644 --- a/common/buildcraft/lib/misc/BlockUtil.java +++ b/common/buildcraft/lib/misc/BlockUtil.java @@ -252,10 +252,13 @@ public static Fluid getFluidWithFlowing(World world, BlockPos pos) { if (block == Blocks.FLOWING_LAVA) { return FluidRegistry.LAVA; } - return FluidRegistry.lookupFluidForBlock(block); + return getFluid(block); } public static Fluid getFluid(Block block) { + if (block instanceof IFluidBlock) { + return FluidRegistry.getFluid(((IFluidBlock) block).getFluid().getName()); + } return FluidRegistry.lookupFluidForBlock(block); } From eeb6fa726f29bf04246fdac10ebe3e089527dfb7 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 27 Jun 2017 00:19:59 +0100 Subject: [PATCH 36/89] Make the libs directory decidable by auto-builders --- build.gradle | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index bae2382f56..0203bf0e3d 100644 --- a/build.gradle +++ b/build.gradle @@ -178,6 +178,11 @@ def parseConfig(File config) { } } +def libsDir = new File(file(System.getenv("LIBS_DIR") ?: "build/libs/"), version) +def modulesDir = new File(libsDir, "modules") +def modulesDirSrc = new File(modulesDir, "src") +System.out.println(libsDir) + // add a source jar //task sourceJar(type: Jar) { // from sourceSets.main.allSource @@ -192,22 +197,21 @@ javadoc { // add a javadoc jar task javadocJar(type: Jar, dependsOn: javadoc) { + destinationDir = libsDir classifier = 'javadoc' from 'build/docs/javadoc' } // because the normal output has been made to be obfuscated task deobfJar(type: Jar) { + destinationDir = libsDir from sourceSets.main.output from sourceSets.api.output classifier = 'dev' } -def modulesDir = file("build/libs/modules") -def modulesDirSrc = new File(modulesDir, "src") - task apiJar(type: Jar, dependsOn: reobfJar) { - destinationDir = modulesDir + destinationDir = libsDir appendix = "api" doFirst { @@ -343,7 +347,7 @@ task roboticsJar(type: Jar, dependsOn: reobfJar) { } task allJar(type: Jar, dependsOn:reobfJar) { - destinationDir = modulesDir + destinationDir = libsDir doFirst { from(project.ext.jarFile) { @@ -353,7 +357,7 @@ task allJar(type: Jar, dependsOn:reobfJar) { } task allSrcJar(type: Jar, dependsOn:reobfJar) { - destinationDir = modulesDir + destinationDir = libsDir classifier = "sources" doFirst { From be69cd32b152928282d09a4b0c1d9bccc6552c69 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 27 Jun 2017 00:21:53 +0100 Subject: [PATCH 37/89] Bump version for release. --- build.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.properties b/build.properties index 1dbef2852b..3978d65c8d 100644 --- a/build.properties +++ b/build.properties @@ -1,4 +1,4 @@ mc_version=1.11.2 forge_version=13.20.0.2296 mappings_version=snapshot_20170304 -mod_version=7.99.4 +mod_version=7.99.5 From 126e08bc453a395b278deb1130f941bb2ea1130c Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 27 Jun 2017 00:57:43 +0100 Subject: [PATCH 38/89] Fix #3675 properly. --- .../generation/GenLayerBiomeReplacer.java | 5 --- common/buildcraft/lib/BCLib.java | 1 - common/buildcraft/lib/BCLibProxy.java | 1 + common/buildcraft/lib/list/ListHandler.java | 2 +- .../lib/list/ListMatchHandlerFluid.java | 33 ++++++++++++++----- 5 files changed, 26 insertions(+), 16 deletions(-) diff --git a/common/buildcraft/energy/generation/GenLayerBiomeReplacer.java b/common/buildcraft/energy/generation/GenLayerBiomeReplacer.java index 2eca674658..f8f775db94 100644 --- a/common/buildcraft/energy/generation/GenLayerBiomeReplacer.java +++ b/common/buildcraft/energy/generation/GenLayerBiomeReplacer.java @@ -18,8 +18,6 @@ @SuppressWarnings("Duplicates") public abstract class GenLayerBiomeReplacer extends GenLayer { - public static final boolean DEBUG = BCDebugging.shouldDebugLog("energy.generation"); - public static final int OFFSET_RANGE = 500000; protected final double xOffset; protected final double zOffset; @@ -71,9 +69,6 @@ public int[] getInts(final int x, final int z, final int width, final int length (zIter + z + zOffset) * noiseScale ) > noiseThreshold) { outputBiomeIDs[xIter + zIter * width] = newBiomeId; - if (DEBUG) { - BCLog.logger.info("Replaced Biome at " + (xIter + x) + ", " + (zIter + z)); - } } else { outputBiomeIDs[xIter + zIter * width] = currentBiomeId; } diff --git a/common/buildcraft/lib/BCLib.java b/common/buildcraft/lib/BCLib.java index 4b367bf2a5..f24a2dc835 100644 --- a/common/buildcraft/lib/BCLib.java +++ b/common/buildcraft/lib/BCLib.java @@ -107,7 +107,6 @@ public static void postInit(FMLPostInitializationEvent evt) { MessageManager.fmlPostInit(); VanillaListHandlers.fmlPostInit(); MarkerCache.postInit(); - ListMatchHandlerFluid.fmlPostInit(); } @Mod.EventHandler diff --git a/common/buildcraft/lib/BCLibProxy.java b/common/buildcraft/lib/BCLibProxy.java index 4cbe53d8d1..ee3f921ba9 100644 --- a/common/buildcraft/lib/BCLibProxy.java +++ b/common/buildcraft/lib/BCLibProxy.java @@ -39,6 +39,7 @@ import buildcraft.lib.fluid.FluidManager; import buildcraft.lib.item.IItemBuildCraft; import buildcraft.lib.item.ItemManager; +import buildcraft.lib.list.ListMatchHandlerFluid; public abstract class BCLibProxy implements IGuiHandler { @SidedProxy(modId = BCLib.MODID) diff --git a/common/buildcraft/lib/list/ListHandler.java b/common/buildcraft/lib/list/ListHandler.java index e7a792f9e3..bddba5f7e8 100644 --- a/common/buildcraft/lib/list/ListHandler.java +++ b/common/buildcraft/lib/list/ListHandler.java @@ -198,7 +198,7 @@ public NonNullList getExamples() { } } } - Collections.shuffle(stackList); +// Collections.shuffle(stackList); return stackList; } } diff --git a/common/buildcraft/lib/list/ListMatchHandlerFluid.java b/common/buildcraft/lib/list/ListMatchHandlerFluid.java index 2e8f54a8d9..2e3f018dc8 100644 --- a/common/buildcraft/lib/list/ListMatchHandlerFluid.java +++ b/common/buildcraft/lib/list/ListMatchHandlerFluid.java @@ -11,27 +11,40 @@ import javax.annotation.Nonnull; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; +import net.minecraftforge.common.ForgeModContainer; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; +import net.minecraftforge.fluids.UniversalBucket; import net.minecraftforge.fluids.capability.IFluidHandlerItem; +import buildcraft.api.core.BCLog; import buildcraft.api.lists.ListMatchHandler; import buildcraft.lib.misc.StackUtil; public class ListMatchHandlerFluid extends ListMatchHandler { - private static final List fluidHoldingItems = new ArrayList<>(); + private static final List clientExampleHolders = new ArrayList<>(); + private static boolean isBuilt = false; - public static void fmlPostInit() { + private static void buildClientExampleList() { + if (isBuilt) { + return; + } + isBuilt = true; for (Item item : Item.REGISTRY) { - ItemStack toTry = new ItemStack(item); - IFluidHandlerItem fluidHandler = FluidUtil.getFluidHandler(toTry); - if (fluidHandler != null && fluidHandler.drain(1, false) == null) { - fluidHoldingItems.add(toTry); + NonNullList stacks = NonNullList.create(); + item.getSubItems(item, CreativeTabs.SEARCH, stacks); + for (ItemStack toTry : stacks) { + IFluidHandlerItem fluidHandler = FluidUtil.getFluidHandler(toTry); + if (fluidHandler != null && fluidHandler.drain(1, false) == null) { + clientExampleHolders.add(toTry); + } } } } @@ -74,15 +87,17 @@ public boolean isValidSource(Type type, @Nonnull ItemStack stack) { @Override public NonNullList getClientExamples(Type type, @Nonnull ItemStack stack) { + buildClientExampleList(); if (type == Type.MATERIAL) { FluidStack fStack = FluidUtil.getFluidContained(stack); if (fStack != null) { NonNullList examples = NonNullList.create(); - for (ItemStack potentialHolder : fluidHoldingItems) { + for (ItemStack potentialHolder : clientExampleHolders) { potentialHolder = potentialHolder.copy(); IFluidHandlerItem fluidHandler = FluidUtil.getFluidHandler(potentialHolder); - if (fluidHandler != null && (fluidHandler.fill(fStack, true) > 0 || fluidHandler.drain(fStack, false) != null)) { + if (fluidHandler != null + && (fluidHandler.fill(fStack, true) > 0 || fluidHandler.drain(fStack, false) != null)) { examples.add(fluidHandler.getContainer()); } } @@ -97,7 +112,7 @@ public NonNullList getClientExamples(Type type, @Nonnull ItemStack st FluidStack contained = fluidHandler.drain(Integer.MAX_VALUE, true); if (contained != null) { examples.add(fluidHandler.getContainer()); - for (ItemStack potential : fluidHoldingItems) { + for (ItemStack potential : clientExampleHolders) { IFluidHandlerItem potentialHolder = FluidUtil.getFluidHandler(potential); if (potentialHolder.fill(contained, true) > 0) { examples.add(potentialHolder.getContainer()); From 6e75007dff29a7f527491d2bd38069ddb03ad72d Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Tue, 27 Jun 2017 14:32:01 +0300 Subject: [PATCH 39/89] Sphere --- .../buildcraft/builders/filling/Filling.java | 16 ++- .../builders/filling/FillingCircle.java | 111 ++++++++++++------ .../builders/filling/FillingFrame.java | 1 + .../builders/filling/FillingPolygon.java | 1 + .../builders/filling/FillingSquare.java | 1 + common/buildcraft/lib/misc/DrawingUtil.java | 2 + 6 files changed, 92 insertions(+), 40 deletions(-) diff --git a/common/buildcraft/builders/filling/Filling.java b/common/buildcraft/builders/filling/Filling.java index c690aeff62..14e982b89e 100644 --- a/common/buildcraft/builders/filling/Filling.java +++ b/common/buildcraft/builders/filling/Filling.java @@ -154,7 +154,7 @@ public static Class getNextParameterClass(List } public static boolean[][][] generateFillingPlanByFunction(BlockPos size, - Function function) { + Function function) { boolean[][][] fillingPlan = new boolean[size.getX()][size.getY()][size.getZ()]; for (int z = 0; z < size.getZ(); z++) { for (int y = 0; y < size.getY(); y++) { @@ -167,8 +167,8 @@ public static boolean[][][] generateFillingPlanByFunction(BlockPos size, } public static boolean[][][] generateFillingPlanByFunctionInAxis(BlockPos size, - EnumFacing.Axis axis, - BiFunction function) { + EnumFacing.Axis axis, + BiFunction function) { switch (axis) { case X: return generateFillingPlanByFunction(size, pos -> function.apply( @@ -191,8 +191,8 @@ public static boolean[][][] generateFillingPlanByFunctionInAxis(BlockPos size, } public static boolean[][][] generateFillingPlanByFunctionInAxis(BlockPos size, - EnumFacing.Axis axis, - BiConsumer function) { + EnumFacing.Axis axis, + BiConsumer function) { Point2i flatSize; switch (axis) { case X: @@ -253,12 +253,16 @@ public static boolean[][][] getFillingPlan(BlockPos size, List param if (parameterPattern == EnumParameterPattern.CIRCLE) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); EnumParameterAxis parameterAxis = (EnumParameterAxis) parameters.get(2); - return FillingCircle.get(size, parameterType, parameterAxis); + return FillingCircle.getCircle(size, parameterType, parameterAxis); } if (parameterPattern == EnumParameterPattern.FRAME) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); return FillingFrame.get(size, parameterType); } + if (parameterPattern == EnumParameterPattern.SPHERE) { + EnumParameterType parameterType = (EnumParameterType) parameters.get(1); + return FillingCircle.getSphere(size, parameterType); + } return generateFillingPlanByFunction(size, pos -> false); } diff --git a/common/buildcraft/builders/filling/FillingCircle.java b/common/buildcraft/builders/filling/FillingCircle.java index bda7387258..e16e43a0e4 100644 --- a/common/buildcraft/builders/filling/FillingCircle.java +++ b/common/buildcraft/builders/filling/FillingCircle.java @@ -14,49 +14,92 @@ import net.minecraft.util.math.BlockPos; import buildcraft.lib.misc.DrawingUtil; +import buildcraft.lib.misc.MathUtil; +@SuppressWarnings("WeakerAccess") public class FillingCircle { - public static boolean[][][] get(BlockPos size, - EnumParameterType parameterType, - EnumParameterAxis parameterAxis) { - return Filling.generateFillingPlanByFunctionInAxis(size, parameterAxis.axis, (flatSize, flatFillingPlan) -> { - DrawingUtil.drawEllipse( - flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, - flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, - flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, - flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, - parameterType == EnumParameterType.FILLED, - (x, y) -> { - List positions = new ArrayList<>(); + private static void draw(EnumParameterType parameterType, Point2i flatSize, boolean[][] flatFillingPlan) { + DrawingUtil.drawEllipse( + flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, + flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, + flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, + flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, + parameterType == EnumParameterType.FILLED, + (x, y) -> { + List positions = new ArrayList<>(); + positions.add( + new Point2i( + flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, + flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y + ) + ); + if (flatSize.x % 2 == 0 && x == flatSize.x / 2) { positions.add( new Point2i( - flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, + x + 1, flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y ) ); - if (flatSize.x % 2 == 0 && x == flatSize.x / 2) { - positions.add( - new Point2i( - x + 1, - flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y - ) - ); - } - if (flatSize.y % 2 == 0 && y == flatSize.y / 2) { - positions.add( - new Point2i( - flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, - y + 1 - ) - ); - } - for (Point2i p : positions) { - if (p.x >= 0 && p.y >= 0 && p.x < flatSize.x && p.y < flatSize.y) { - flatFillingPlan[p.x][p.y] = true; - } + } + if (flatSize.y % 2 == 0 && y == flatSize.y / 2) { + positions.add( + new Point2i( + flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, + y + 1 + ) + ); + } + for (Point2i p : positions) { + if (p.x >= 0 && p.y >= 0 && p.x < flatSize.x && p.y < flatSize.y) { + flatFillingPlan[p.x][p.y] = true; } } - ); + } + ); + } + + public static boolean[][][] getCircle(BlockPos size, + EnumParameterType parameterType, + EnumParameterAxis parameterAxis) { + return Filling.generateFillingPlanByFunctionInAxis(size, parameterAxis.axis, (flatSize, flatFillingPlan) -> { + draw(parameterType, flatSize, flatFillingPlan); }); } + + public static boolean[][][] getSphere(BlockPos size, + EnumParameterType parameterType) { + boolean[][][] flatFillingPlans = new boolean[size.getY()][size.getX()][size.getZ()]; + Point2i flatSize = new Point2i(size.getX(), size.getZ()); + int levelsCount = size.getY(); + for (int level = 0; level < levelsCount; level++) { + double position = (level + 0.5) / levelsCount; + if (position > 0.5) { + position = 1 - position; + } + Point2i resizedSize = new Point2i( + MathUtil.clamp( + (int) Math.round(Math.sqrt(position * (1 - position)) * 2 * flatSize.x), + 1, + flatSize.x - 1 + ), + MathUtil.clamp( + (int) Math.round(Math.sqrt(position * (1 - position)) * 2 * flatSize.y), + 1, + flatSize.y - 1 + ) + ); + boolean[][] resizedFillingPlan = new boolean[resizedSize.x][resizedSize.y]; + draw(parameterType, resizedSize, resizedFillingPlan); + for (int y = 0; y < resizedSize.y; y++) { + for (int x = 0; x < resizedSize.x; x++) { + flatFillingPlans + [level] + [x + (flatSize.x - resizedSize.x) / 2] + [y + (flatSize.y - resizedSize.y) / 2] + = resizedFillingPlan[x][y]; + } + } + } + return Filling.generateFillingPlanByFunction(size, pos -> flatFillingPlans[pos.getY()][pos.getX()][pos.getZ()]); + } } diff --git a/common/buildcraft/builders/filling/FillingFrame.java b/common/buildcraft/builders/filling/FillingFrame.java index 5a44c18eee..243a1fce7b 100644 --- a/common/buildcraft/builders/filling/FillingFrame.java +++ b/common/buildcraft/builders/filling/FillingFrame.java @@ -8,6 +8,7 @@ import net.minecraft.util.math.BlockPos; +@SuppressWarnings("WeakerAccess") public class FillingFrame { public static boolean[][][] get(BlockPos size, EnumParameterType parameterType) { diff --git a/common/buildcraft/builders/filling/FillingPolygon.java b/common/buildcraft/builders/filling/FillingPolygon.java index b6e2b7f483..d001bf670c 100644 --- a/common/buildcraft/builders/filling/FillingPolygon.java +++ b/common/buildcraft/builders/filling/FillingPolygon.java @@ -15,6 +15,7 @@ import buildcraft.lib.misc.DrawingUtil; import buildcraft.lib.misc.MathUtil; +@SuppressWarnings("WeakerAccess") public class FillingPolygon { public static boolean[][][] get(BlockPos size, EnumParameterType parameterType, diff --git a/common/buildcraft/builders/filling/FillingSquare.java b/common/buildcraft/builders/filling/FillingSquare.java index d41f501dbb..efb335e16a 100644 --- a/common/buildcraft/builders/filling/FillingSquare.java +++ b/common/buildcraft/builders/filling/FillingSquare.java @@ -8,6 +8,7 @@ import net.minecraft.util.math.BlockPos; +@SuppressWarnings("WeakerAccess") public class FillingSquare { public static boolean[][][] get(BlockPos size, EnumParameterType parameterType, diff --git a/common/buildcraft/lib/misc/DrawingUtil.java b/common/buildcraft/lib/misc/DrawingUtil.java index fd2a33aedf..e2c8d0f96a 100644 --- a/common/buildcraft/lib/misc/DrawingUtil.java +++ b/common/buildcraft/lib/misc/DrawingUtil.java @@ -20,6 +20,8 @@ public static void drawEllipse(int cx, int ry, boolean filled, BiConsumer drawPixel) { + rx = Math.max(1, rx); + ry = Math.max(1, ry); int rx2 = rx * rx; int ry2 = ry * ry; From 697695218e723afab75a561c06737597bcebeb27 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Tue, 27 Jun 2017 21:16:29 +0300 Subject: [PATCH 40/89] Fix fluid comparing --- common/buildcraft/factory/tile/TilePump.java | 8 +++++--- .../lib/client/render/fluid/FluidRenderer.java | 14 +++++++------- common/buildcraft/lib/fluid/CoolantRegistry.java | 9 ++++++--- common/buildcraft/lib/fluid/FuelRegistry.java | 9 ++++++--- common/buildcraft/lib/fluid/SingleUseTank.java | 4 +++- .../buildcraft/factory/tile/TileFloodGate.java | 3 ++- 6 files changed, 29 insertions(+), 18 deletions(-) diff --git a/common/buildcraft/factory/tile/TilePump.java b/common/buildcraft/factory/tile/TilePump.java index 7014cdfb38..3380586215 100644 --- a/common/buildcraft/factory/tile/TilePump.java +++ b/common/buildcraft/factory/tile/TilePump.java @@ -14,6 +14,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; @@ -126,7 +127,7 @@ private void buildQueue() { private boolean canDrain(BlockPos blockPos) { Fluid fluid = BlockUtil.getFluid(world, blockPos); - return tank.isEmpty() ? fluid != null : fluid == tank.getFluidType(); + return fluid != null && (tank.isEmpty() || Objects.equals(fluid.getName(), tank.getFluidType().getName())); } private void nextPos() { @@ -180,11 +181,12 @@ public void mine() { tank.fillInternal(drain, true); progress = 0; int count = 0; - if (drain.getFluid() == FluidRegistry.WATER) { + if (Objects.equals(drain.getFluid().getName(), FluidRegistry.WATER.getName())) { for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { BlockPos waterPos = currentPos.add(new BlockPos(x, 0, z)); - if (BlockUtil.getFluid(world, waterPos) == FluidRegistry.WATER) { + Fluid fluid = BlockUtil.getFluid(world, waterPos); + if (fluid != null && Objects.equals(fluid.getName(), FluidRegistry.WATER.getName())) { count++; } } diff --git a/common/buildcraft/lib/client/render/fluid/FluidRenderer.java b/common/buildcraft/lib/client/render/fluid/FluidRenderer.java index 340c20c046..09e8cd01bf 100644 --- a/common/buildcraft/lib/client/render/fluid/FluidRenderer.java +++ b/common/buildcraft/lib/client/render/fluid/FluidRenderer.java @@ -43,7 +43,7 @@ // TODO: thread safety (per thread context?) public class FluidRenderer { - private static final EnumMap> fluidSprites = new EnumMap<>(FluidSpriteType.class); + private static final EnumMap> fluidSprites = new EnumMap<>(FluidSpriteType.class); public static final MutableVertex vertex = new MutableVertex(); private static final boolean[] DEFAULT_FACES = { true, true, true, true, true, true }; @@ -70,22 +70,22 @@ public static void onTextureStitchPre(TextureMap map) { for (Fluid fluid : FluidRegistry.getRegisteredFluids().values()) { ResourceLocation still = fluid.getStill(); if (spritesStitched.containsKey(still)) { - fluidSprites.get(FluidSpriteType.FROZEN).put(fluid, spritesStitched.get(still)); + fluidSprites.get(FluidSpriteType.FROZEN).put(fluid.getName(), spritesStitched.get(still)); } else { SpriteFluidFrozen spriteFrozen = new SpriteFluidFrozen(still); spritesStitched.put(still, spriteFrozen); if (!map.setTextureEntry(spriteFrozen)) { throw new IllegalStateException("Failed to set the frozen variant of " + still + "!"); } - fluidSprites.get(FluidSpriteType.FROZEN).put(fluid, spriteFrozen); + fluidSprites.get(FluidSpriteType.FROZEN).put(fluid.getName(), spriteFrozen); } } } public static void onTextureStitchPost(TextureMap map) { for (Fluid fluid : FluidRegistry.getRegisteredFluids().values()) { - fluidSprites.get(FluidSpriteType.STILL).put(fluid, map.registerSprite(fluid.getStill())); - fluidSprites.get(FluidSpriteType.FLOWING).put(fluid, map.registerSprite(fluid.getFlowing())); + fluidSprites.get(FluidSpriteType.STILL).put(fluid.getName(), map.registerSprite(fluid.getStill())); + fluidSprites.get(FluidSpriteType.FLOWING).put(fluid.getName(), map.registerSprite(fluid.getFlowing())); } } @@ -156,7 +156,7 @@ public static void renderFluid(FluidSpriteType type, FluidStack fluid, double am if (type == null) { type = FluidSpriteType.STILL; } - sprite = fluidSprites.get(type).get(fluid.getFluid()); + sprite = fluidSprites.get(type).get(fluid.getFluid().getName()); if (sprite == null) { sprite = Minecraft.getMinecraft().getTextureMapBlocks().getMissingSprite(); } @@ -263,7 +263,7 @@ private static void vertex(double x, double y, double z) { * {@link GuiUtil}'s fluid drawing methods in preference to this. */ public static void drawFluidForGui(FluidStack fluid, int startX, int startY, int endX, int endY) { - sprite = FluidRenderer.fluidSprites.get(FluidSpriteType.STILL).get(fluid.getFluid()); + sprite = FluidRenderer.fluidSprites.get(FluidSpriteType.STILL).get(fluid.getFluid().getName()); if (sprite == null) { sprite = Minecraft.getMinecraft().getTextureMapBlocks().getMissingSprite(); } diff --git a/common/buildcraft/lib/fluid/CoolantRegistry.java b/common/buildcraft/lib/fluid/CoolantRegistry.java index 17838ca800..ccb54e3c72 100644 --- a/common/buildcraft/lib/fluid/CoolantRegistry.java +++ b/common/buildcraft/lib/fluid/CoolantRegistry.java @@ -9,6 +9,7 @@ import java.util.Collection; import java.util.LinkedList; import java.util.List; +import java.util.Objects; import net.minecraft.item.ItemStack; @@ -59,9 +60,11 @@ public Collection getSolidCoolants() { @Override public ICoolant getCoolant(Fluid fluid) { - for (ICoolant coolant : coolants) { - if (coolant.getFluid() == fluid) { - return coolant; + if (fluid != null) { + for (ICoolant coolant : coolants) { + if (Objects.equals(coolant.getFluid().getName(), fluid.getName())) { + return coolant; + } } } return null; diff --git a/common/buildcraft/lib/fluid/FuelRegistry.java b/common/buildcraft/lib/fluid/FuelRegistry.java index 51b6d2113c..ad22fd8789 100644 --- a/common/buildcraft/lib/fluid/FuelRegistry.java +++ b/common/buildcraft/lib/fluid/FuelRegistry.java @@ -9,6 +9,7 @@ import java.util.Collection; import java.util.LinkedList; import java.util.List; +import java.util.Objects; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; @@ -46,9 +47,11 @@ public Collection getFuels() { @Override public IFuel getFuel(Fluid fluid) { - for (IFuel fuel : fuels) { - if (fuel.getFluid() == fluid) { - return fuel; + if (fluid != null) { + for (IFuel fuel : fuels) { + if (Objects.equals(fuel.getFluid().getName(), fluid.getName())) { + return fuel; + } } } return null; diff --git a/common/buildcraft/lib/fluid/SingleUseTank.java b/common/buildcraft/lib/fluid/SingleUseTank.java index 820f97f7aa..d1ab1d1e52 100644 --- a/common/buildcraft/lib/fluid/SingleUseTank.java +++ b/common/buildcraft/lib/fluid/SingleUseTank.java @@ -4,6 +4,8 @@ * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package buildcraft.lib.fluid; +import java.util.Objects; + import javax.annotation.Nonnull; import net.minecraft.nbt.NBTTagCompound; @@ -31,7 +33,7 @@ public int fill(FluidStack resource, boolean doFill) { acceptedFluid = resource.getFluid(); } - if (acceptedFluid == null || acceptedFluid == resource.getFluid()) { + if (acceptedFluid == null || Objects.equals(acceptedFluid.getName(), resource.getFluid().getName())) { return super.fill(resource, doFill); } diff --git a/common_old_license/buildcraft/factory/tile/TileFloodGate.java b/common_old_license/buildcraft/factory/tile/TileFloodGate.java index 1fd7848003..e09b2cc9e1 100644 --- a/common_old_license/buildcraft/factory/tile/TileFloodGate.java +++ b/common_old_license/buildcraft/factory/tile/TileFloodGate.java @@ -8,6 +8,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; +import java.util.Objects; import java.util.Set; import java.util.TreeMap; @@ -115,7 +116,7 @@ private void tryAddToQueue(BlockPos blockPos, Set visitedBlocks, Deque Block block = blockState.getBlock(); Fluid fluid = BlockUtil.getFluidWithFlowing(block); - boolean isCurrentFluid = this.tank.getFluidType() != null && this.tank.getFluidType() == fluid; + boolean isCurrentFluid = this.tank.getFluidType() != null && fluid != null && Objects.equals(this.tank.getFluidType().getName(), fluid.getName()); if (world.isAirBlock(currentPos) || block instanceof BlockFloodGate || isCurrentFluid) { blocksFound.add(currentPos); From d7ca753bc058763e7d6dc2fa9c515a1ce206d914 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Tue, 27 Jun 2017 21:26:57 +0300 Subject: [PATCH 41/89] Fix comparing in pump --- common/buildcraft/factory/tile/TilePump.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/common/buildcraft/factory/tile/TilePump.java b/common/buildcraft/factory/tile/TilePump.java index 3380586215..af1af003bb 100644 --- a/common/buildcraft/factory/tile/TilePump.java +++ b/common/buildcraft/factory/tile/TilePump.java @@ -107,7 +107,10 @@ private void buildQueue() { continue; } if (!checked.contains(offsetPos)) { - if (BlockUtil.getFluidWithFlowing(world, offsetPos) == fluid) { + Fluid drain = BlockUtil.getFluidWithFlowing(world, offsetPos); + if (drain != null && + fluid != null && + Objects.equals(drain.getName(), fluid.getName())) { ImmutableList.Builder pathBuilder = new ImmutableList.Builder<>(); pathBuilder.addAll(paths.get(posToCheck)); pathBuilder.add(offsetPos); From e45d69d530e4bf244cc0bad55eaad3190f36bf60 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 27 Jun 2017 21:02:11 +0100 Subject: [PATCH 42/89] Use FluidStack rather than Fluid in a few more places. --- BuildCraftAPI | 2 +- .../energy/tile/TileEngineIron_BC8.java | 35 ++++++---------- .../factory/tile/TileDistiller_BC8.java | 8 +++- .../buildcraft/lib/fluid/CoolantRegistry.java | 41 ++++++++++++++----- common/buildcraft/lib/fluid/FuelRegistry.java | 26 ++++++------ .../buildcraft/lib/fluid/SingleUseTank.java | 40 ++++++++++++++---- common/buildcraft/lib/list/ListHandler.java | 2 +- .../lib/list/ListMatchHandlerFluid.java | 4 -- common/buildcraft/lib/misc/FluidUtilBC.java | 8 ++++ 9 files changed, 104 insertions(+), 62 deletions(-) diff --git a/BuildCraftAPI b/BuildCraftAPI index b3f9692622..b396bc79d7 160000 --- a/BuildCraftAPI +++ b/BuildCraftAPI @@ -1 +1 @@ -Subproject commit b3f969262229f2f127ab95f9d55af245571336f3 +Subproject commit b396bc79d72c6f2cc2876cbd9a780407fa536d09 diff --git a/common/buildcraft/energy/tile/TileEngineIron_BC8.java b/common/buildcraft/energy/tile/TileEngineIron_BC8.java index 28ab201f7f..fcfe8b9887 100644 --- a/common/buildcraft/energy/tile/TileEngineIron_BC8.java +++ b/common/buildcraft/energy/tile/TileEngineIron_BC8.java @@ -27,7 +27,6 @@ import buildcraft.api.core.IFluidFilter; import buildcraft.api.core.IFluidHandlerAdv; import buildcraft.api.fuels.BuildcraftFuelRegistry; -import buildcraft.api.fuels.ICoolant; import buildcraft.api.fuels.IFuel; import buildcraft.api.fuels.IFuelManager.IDirtyFuel; import buildcraft.api.fuels.ISolidCoolant; @@ -81,12 +80,15 @@ protected FluidGetResult map(ItemStack stack, int space) { public TileEngineIron_BC8() { // TODO: Auto list of example fuels! - tankFuel.helpInfo = new ElementHelpInfo(tankFuel.helpInfo.title, 0xFF_FF_33_33, Tank.DEFAULT_HELP_KEY, null, "buildcraft.help.tank.fuel"); + tankFuel.helpInfo = new ElementHelpInfo(tankFuel.helpInfo.title, 0xFF_FF_33_33, Tank.DEFAULT_HELP_KEY, null, + "buildcraft.help.tank.fuel"); // TODO: Auto list of example coolants! - tankCoolant.helpInfo = new ElementHelpInfo(tankCoolant.helpInfo.title, 0xFF_55_55_FF, Tank.DEFAULT_HELP_KEY, null, "buildcraft.help.tank.coolant"); + tankCoolant.helpInfo = new ElementHelpInfo(tankCoolant.helpInfo.title, 0xFF_55_55_FF, Tank.DEFAULT_HELP_KEY, + null, "buildcraft.help.tank.coolant"); - tankResidue.helpInfo = new ElementHelpInfo(tankResidue.helpInfo.title, 0xFF_AA_33_AA, Tank.DEFAULT_HELP_KEY, null, "buildcraft.help.tank.residue"); + tankResidue.helpInfo = new ElementHelpInfo(tankResidue.helpInfo.title, 0xFF_AA_33_AA, Tank.DEFAULT_HELP_KEY, + null, "buildcraft.help.tank.residue"); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, fluidHandler, EnumPipePart.VALUES); } @@ -143,13 +145,7 @@ public boolean onActivated(EntityPlayer player, EnumHand hand, EnumFacing side, return false; } if (!world.isRemote) { - if (FluidUtil.interactWithFluidHandler( - player, - hand, - world, - pos, - side - )) { + if (FluidUtil.interactWithFluidHandler(player, hand, world, pos, side)) { return true; } } @@ -192,11 +188,7 @@ public boolean isBurning() { protected void burn() { FluidStack fuel = this.tankFuel.getFluid(); if (currentFuel == null) { - if (fuel == null) { - currentFuel = null; - } else { - currentFuel = BuildcraftFuelRegistry.fuel.getFuel(fuel.getFluid()); - } + currentFuel = BuildcraftFuelRegistry.fuel.getFuel(fuel); } if (currentFuel == null) { @@ -269,10 +261,9 @@ public void updateHeatLevel() { // fillCoolingBuffer(); { if (tankCoolant.getFluidAmount() > 0) { - ICoolant coolant = BuildcraftFuelRegistry.coolant.getCoolant(tankCoolant.getFluidType()); - if (coolant != null) { - float coolPerMb = coolant.getDegreesCoolingPerMB((float) heat); - + float coolPerMb = + BuildcraftFuelRegistry.coolant.getDegreesPerMb(tankCoolant.getFluid(), (float) heat); + if (coolPerMb > 0) { int coolantAmount = Math.min(MAX_COOLANT_PER_TICK, tankCoolant.getFluidAmount()); float cooling = coolPerMb; // cooling /= getBiomeTempScalar(); @@ -343,11 +334,11 @@ public long getCurrentOutput() { // Fluid related private boolean isValidFuel(FluidStack fluid) { - return BuildcraftFuelRegistry.fuel.getFuel(fluid.getFluid()) != null; + return BuildcraftFuelRegistry.fuel.getFuel(fluid) != null; } private boolean isValidCoolant(FluidStack fluid) { - return BuildcraftFuelRegistry.coolant.getCoolant(fluid.getFluid()) != null; + return BuildcraftFuelRegistry.coolant.getCoolant(fluid) != null; } private boolean isResidue(FluidStack fluid) { diff --git a/common/buildcraft/factory/tile/TileDistiller_BC8.java b/common/buildcraft/factory/tile/TileDistiller_BC8.java index 3064cfaa9d..6cd3781841 100644 --- a/common/buildcraft/factory/tile/TileDistiller_BC8.java +++ b/common/buildcraft/factory/tile/TileDistiller_BC8.java @@ -27,6 +27,7 @@ import buildcraft.api.mj.MjBattery; import buildcraft.api.mj.MjCapabilityHelper; import buildcraft.api.recipes.BuildcraftRecipeRegistry; +import buildcraft.api.recipes.IRefineryRecipeManager; import buildcraft.api.recipes.IRefineryRecipeManager.IDistillationRecipe; import buildcraft.api.tiles.IDebuggable; @@ -67,7 +68,7 @@ public class TileDistiller_BC8 extends TileBC_Neptune implements ITickable, IDeb public static final long MAX_MJ_PER_TICK = 6 * MjAPI.MJ; public final Tank tankIn = new Tank("in", 4 * Fluid.BUCKET_VOLUME, this); - public final Tank tankOutGas = new Tank("out_gas", 4 * Fluid.BUCKET_VOLUME, this); + public final Tank tankOutGas = new Tank("out_gas", 4 * Fluid.BUCKET_VOLUME, this, this::isDistillable); public final Tank tankOutLiquid = new Tank("out_liquid", 4 * Fluid.BUCKET_VOLUME, this); public final TankManager tankManager = new TankManager<>(tankIn, tankOutGas, tankOutLiquid); @@ -142,6 +143,11 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext } } + private boolean isDistillable(FluidStack fluid) { + IRefineryRecipeManager manager = BuildcraftRecipeRegistry.refineryRecipes; + return manager.getDistilationRegistry().getRecipeForInput(fluid) != null; + } + public static void setClientModelVariablesForItem() { DefaultContexts.RENDER_PARTIAL_TICKS.value = 1; MODEL_ACTIVE.value = false; diff --git a/common/buildcraft/lib/fluid/CoolantRegistry.java b/common/buildcraft/lib/fluid/CoolantRegistry.java index 17838ca800..2111dd2664 100644 --- a/common/buildcraft/lib/fluid/CoolantRegistry.java +++ b/common/buildcraft/lib/fluid/CoolantRegistry.java @@ -12,7 +12,6 @@ import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import buildcraft.api.fuels.ICoolant; @@ -38,7 +37,7 @@ public ISolidCoolant addSolidCoolant(ISolidCoolant solidCoolant) { } @Override - public ICoolant addCoolant(Fluid fluid, float degreesCoolingPerMB) { + public ICoolant addCoolant(FluidStack fluid, float degreesCoolingPerMB) { return addCoolant(new Coolant(fluid, degreesCoolingPerMB)); } @@ -58,15 +57,32 @@ public Collection getSolidCoolants() { } @Override - public ICoolant getCoolant(Fluid fluid) { + public ICoolant getCoolant(FluidStack fluid) { + if (fluid == null || fluid.amount == 0) { + return null; + } for (ICoolant coolant : coolants) { - if (coolant.getFluid() == fluid) { + if (coolant.matchesFluid(fluid)) { return coolant; } } return null; } + @Override + public float getDegreesPerMb(FluidStack fluid, float heat) { + if (fluid == null || fluid.amount == 0) { + return 0; + } + for (ICoolant coolant : coolants) { + float degrees = coolant.getDegreesCoolingPerMB(fluid, heat); + if (degrees > 0) { + return degrees; + } + } + return 0; + } + @Override public ISolidCoolant getSolidCoolant(ItemStack solid) { for (ISolidCoolant coolant : solidCoolants) { @@ -77,23 +93,26 @@ public ISolidCoolant getSolidCoolant(ItemStack solid) { return null; } - private static class Coolant implements ICoolant { - private final Fluid fluid; + public static class Coolant implements ICoolant { + private final FluidStack fluid; private final float degreesCoolingPerMB; - public Coolant(Fluid fluid, float degreesCoolingPerMB) { + public Coolant(FluidStack fluid, float degreesCoolingPerMB) { this.fluid = fluid; this.degreesCoolingPerMB = degreesCoolingPerMB; } @Override - public Fluid getFluid() { - return fluid; + public boolean matchesFluid(FluidStack stack) { + return fluid.isFluidEqual(stack); } @Override - public float getDegreesCoolingPerMB(float heat) { - return degreesCoolingPerMB; + public float getDegreesCoolingPerMB(FluidStack stack, float heat) { + if (matchesFluid(stack)) { + return degreesCoolingPerMB; + } + return 0; } } diff --git a/common/buildcraft/lib/fluid/FuelRegistry.java b/common/buildcraft/lib/fluid/FuelRegistry.java index 51b6d2113c..a1afef09fd 100644 --- a/common/buildcraft/lib/fluid/FuelRegistry.java +++ b/common/buildcraft/lib/fluid/FuelRegistry.java @@ -10,7 +10,6 @@ import java.util.LinkedList; import java.util.List; -import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import buildcraft.api.fuels.IFuel; @@ -22,21 +21,19 @@ public enum FuelRegistry implements IFuelManager { private final List fuels = new LinkedList<>(); @Override - public IFuel addFuel(IFuel fuel) { + public F addFuel(F fuel) { fuels.add(fuel); return fuel; } @Override - public IFuel addFuel(Fluid fluid, long powerPerCycle, int totalBurningTime) { + public IFuel addFuel(FluidStack fluid, long powerPerCycle, int totalBurningTime) { return addFuel(new Fuel(fluid, powerPerCycle, totalBurningTime)); } @Override - public IDirtyFuel addDirtyFuel(Fluid fuel, long powerPerCycle, int totalBurningTime, FluidStack residue) { - IDirtyFuel dirty = new DirtyFuel(fuel, powerPerCycle, totalBurningTime, residue); - addFuel(dirty); - return dirty; + public IDirtyFuel addDirtyFuel(FluidStack fuel, long powerPerCycle, int totalBurningTime, FluidStack residue) { + return addFuel(new DirtyFuel(fuel, powerPerCycle, totalBurningTime, residue)); } @Override @@ -45,9 +42,12 @@ public Collection getFuels() { } @Override - public IFuel getFuel(Fluid fluid) { + public IFuel getFuel(FluidStack fluid) { + if (fluid == null) { + return null; + } for (IFuel fuel : fuels) { - if (fuel.getFluid() == fluid) { + if (fuel.getFluid().isFluidEqual(fluid)) { return fuel; } } @@ -55,18 +55,18 @@ public IFuel getFuel(Fluid fluid) { } public static class Fuel implements IFuel { - private final Fluid fluid; + private final FluidStack fluid; private final long powerPerCycle; private final int totalBurningTime; - public Fuel(Fluid fluid, long powerPerCycle, int totalBurningTime) { + public Fuel(FluidStack fluid, long powerPerCycle, int totalBurningTime) { this.fluid = fluid; this.powerPerCycle = powerPerCycle; this.totalBurningTime = totalBurningTime; } @Override - public Fluid getFluid() { + public FluidStack getFluid() { return fluid; } @@ -85,7 +85,7 @@ public static class DirtyFuel extends Fuel implements IDirtyFuel { private final FluidStack residue; - public DirtyFuel(Fluid fluid, long powerPerCycle, int totalBurningTime, FluidStack residue) { + public DirtyFuel(FluidStack fluid, long powerPerCycle, int totalBurningTime, FluidStack residue) { super(fluid, powerPerCycle, totalBurningTime); this.residue = residue; } diff --git a/common/buildcraft/lib/fluid/SingleUseTank.java b/common/buildcraft/lib/fluid/SingleUseTank.java index 820f97f7aa..7f99d371d5 100644 --- a/common/buildcraft/lib/fluid/SingleUseTank.java +++ b/common/buildcraft/lib/fluid/SingleUseTank.java @@ -1,7 +1,9 @@ -/* Copyright (c) 2016 SpaceToad and the BuildCraft team +/* + * Copyright (c) 2016 SpaceToad and the BuildCraft team * * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not - * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ package buildcraft.lib.fluid; import javax.annotation.Nonnull; @@ -9,13 +11,16 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.Constants; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; public class SingleUseTank extends Tank { - private Fluid acceptedFluid; + private static final String NBT_ACCEPTED_FLUID = "acceptedFluid"; + + private FluidStack acceptedFluid; public SingleUseTank(@Nonnull String name, int capacity, TileEntity tile) { super(name, capacity, tile); @@ -28,10 +33,11 @@ public int fill(FluidStack resource, boolean doFill) { } if (doFill && acceptedFluid == null) { - acceptedFluid = resource.getFluid(); + acceptedFluid = resource.copy(); + acceptedFluid.amount = 1; } - if (acceptedFluid == null || acceptedFluid == resource.getFluid()) { + if (acceptedFluid == null || acceptedFluid.isFluidEqual(resource)) { return super.fill(resource, doFill); } @@ -43,10 +49,22 @@ public void reset() { } public void setAcceptedFluid(Fluid fluid) { - this.acceptedFluid = fluid; + if (fluid == null) { + this.acceptedFluid = null; + } else { + this.acceptedFluid = new FluidStack(fluid, 1); + } + } + + public void setAcceptedFluid(FluidStack fluid) { + if (fluid == null) { + this.acceptedFluid = null; + } else { + this.acceptedFluid = new FluidStack(fluid, 1); + } } - public Fluid getAcceptedFluid() { + public FluidStack getAcceptedFluid() { return acceptedFluid; } @@ -54,13 +72,17 @@ public Fluid getAcceptedFluid() { public void writeTankToNBT(NBTTagCompound nbt) { super.writeTankToNBT(nbt); if (acceptedFluid != null) { - nbt.setString("acceptedFluid", acceptedFluid.getName()); + nbt.setTag(NBT_ACCEPTED_FLUID, acceptedFluid.writeToNBT(new NBTTagCompound())); } } @Override public void readTankFromNBT(NBTTagCompound nbt) { super.readTankFromNBT(nbt); - acceptedFluid = FluidRegistry.getFluid(nbt.getString("acceptedFluid")); + if (nbt.hasKey(NBT_ACCEPTED_FLUID, Constants.NBT.TAG_STRING)) { + setAcceptedFluid(FluidRegistry.getFluid(nbt.getString(NBT_ACCEPTED_FLUID))); + } else { + acceptedFluid = FluidStack.loadFluidStackFromNBT(nbt.getCompoundTag(NBT_ACCEPTED_FLUID)); + } } } diff --git a/common/buildcraft/lib/list/ListHandler.java b/common/buildcraft/lib/list/ListHandler.java index bddba5f7e8..e7a792f9e3 100644 --- a/common/buildcraft/lib/list/ListHandler.java +++ b/common/buildcraft/lib/list/ListHandler.java @@ -198,7 +198,7 @@ public NonNullList getExamples() { } } } -// Collections.shuffle(stackList); + Collections.shuffle(stackList); return stackList; } } diff --git a/common/buildcraft/lib/list/ListMatchHandlerFluid.java b/common/buildcraft/lib/list/ListMatchHandlerFluid.java index 2e3f018dc8..b301aa3421 100644 --- a/common/buildcraft/lib/list/ListMatchHandlerFluid.java +++ b/common/buildcraft/lib/list/ListMatchHandlerFluid.java @@ -12,18 +12,14 @@ import javax.annotation.Nonnull; import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; -import net.minecraftforge.common.ForgeModContainer; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.UniversalBucket; import net.minecraftforge.fluids.capability.IFluidHandlerItem; -import buildcraft.api.core.BCLog; import buildcraft.api.lists.ListMatchHandler; import buildcraft.lib.misc.StackUtil; diff --git a/common/buildcraft/lib/misc/FluidUtilBC.java b/common/buildcraft/lib/misc/FluidUtilBC.java index a51b50725a..e82d81b631 100644 --- a/common/buildcraft/lib/misc/FluidUtilBC.java +++ b/common/buildcraft/lib/misc/FluidUtilBC.java @@ -14,6 +14,7 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; +import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.IFluidHandler; @@ -121,4 +122,11 @@ public static List mergeSameFluids(List fluids) { public static boolean areFluidStackEqual(FluidStack a, FluidStack b) { return (a == null && b == null) || (a != null && a.isFluidEqual(b) && a.amount == b.amount); } + + public static boolean areFluidsEqual(Fluid a, Fluid b) { + if (a == null || b == null) { + return a == b; + } + return a.getName().equals(b.getName()); + } } From fb2d1f2380a3d990fdfddcda1c903d4c59bd8e9a Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 27 Jun 2017 21:06:30 +0100 Subject: [PATCH 43/89] Minor build.gradle fix --- build.gradle | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 0203bf0e3d..72d2f361a7 100644 --- a/build.gradle +++ b/build.gradle @@ -178,10 +178,9 @@ def parseConfig(File config) { } } -def libsDir = new File(file(System.getenv("LIBS_DIR") ?: "build/libs/"), version) +def libsDir = new File(System.getenv("LIBS_DIR") ?: "build/libs/", version) def modulesDir = new File(libsDir, "modules") def modulesDirSrc = new File(modulesDir, "src") -System.out.println(libsDir) // add a source jar //task sourceJar(type: Jar) { From 7800bf799b2ac4abb58121b4e0c713e90b5afeca Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 27 Jun 2017 21:24:09 +0100 Subject: [PATCH 44/89] Fix mj locales not working --- common/buildcraft/lib/misc/LocaleUtil.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/buildcraft/lib/misc/LocaleUtil.java b/common/buildcraft/lib/misc/LocaleUtil.java index f7ed32ad30..cdac3ae0eb 100644 --- a/common/buildcraft/lib/misc/LocaleUtil.java +++ b/common/buildcraft/lib/misc/LocaleUtil.java @@ -56,7 +56,7 @@ public static void onConfigChanged() { localeKeyFluidStaticEmpty = "buildcraft.fluid.empty." + (bucketFlow ? "bucket." : "milli.") + longName; localeKeyFluidStaticFull = "buildcraft.fluid.full." + (bucketFlow ? "bucket." : "milli.") + longName; localeKeyMjStatic = "buildcraft.mj.static." + longName; - localeKeyFluidFlow = "buildcraft.mj.flow." + timeGap + longName; + localeKeyMjFlow = "buildcraft.mj.flow." + timeGap + longName; } /** Localizes the give key to the current locale. From ee1531115087eb9ac7b1c836763c21a8aedae8cf Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 27 Jun 2017 21:29:09 +0100 Subject: [PATCH 45/89] Fix the builder redrawing itself every tick. --- .../buildcraft/builders/tile/TileBuilder.java | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/common/buildcraft/builders/tile/TileBuilder.java b/common/buildcraft/builders/tile/TileBuilder.java index 2386938749..91e91058de 100644 --- a/common/buildcraft/builders/tile/TileBuilder.java +++ b/common/buildcraft/builders/tile/TileBuilder.java @@ -1,7 +1,9 @@ -/* Copyright (c) 2016 SpaceToad and the BuildCraft team +/* + * Copyright (c) 2016 SpaceToad and the BuildCraft team * * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not - * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ package buildcraft.builders.tile; import java.io.IOException; @@ -73,13 +75,16 @@ import buildcraft.builders.snapshot.Template; import buildcraft.builders.snapshot.TemplateBuilder; -public class TileBuilder extends TileBC_Neptune implements ITickable, IDebuggable, ITileForTemplateBuilder, ITileForBlueprintBuilder { +public class TileBuilder extends TileBC_Neptune + implements ITickable, IDebuggable, ITileForTemplateBuilder, ITileForBlueprintBuilder { public static final IdAllocator IDS = TileBC_Neptune.IDS.makeChild("builder"); public static final int NET_CAN_EXCAVATE = IDS.allocId("CAN_EXCAVATE"); public static final int NET_SNAPSHOT_TYPE = IDS.allocId("SNAPSHOT_TYPE"); - public final ItemHandlerSimple invSnapshot = itemManager.addInvHandler("snapshot", 1, EnumAccess.BOTH, EnumPipePart.VALUES); - public final ItemHandlerSimple invResources = itemManager.addInvHandler("resources", 27, EnumAccess.BOTH, EnumPipePart.VALUES); + public final ItemHandlerSimple invSnapshot = + itemManager.addInvHandler("snapshot", 1, EnumAccess.BOTH, EnumPipePart.VALUES); + public final ItemHandlerSimple invResources = + itemManager.addInvHandler("resources", 27, EnumAccess.BOTH, EnumPipePart.VALUES); private final TankManager tankManager = new TankManager<>(); private final MjBattery battery = new MjBattery(1000 * MjAPI.MJ); @@ -114,7 +119,8 @@ public IdAllocator getIdAllocator() { } @Override - protected void onSlotChange(IItemHandlerModifiable itemHandler, int slot, @Nonnull ItemStack before, @Nonnull ItemStack after) { + protected void onSlotChange(IItemHandlerModifiable itemHandler, int slot, @Nonnull ItemStack before, + @Nonnull ItemStack after) { if (itemHandler == invSnapshot) { currentBasePosIndex = 0; snapshot = null; @@ -154,7 +160,8 @@ private void updateSnapshot() { if (snapshot != null && getCurrentBasePos() != null) { snapshotType = snapshot.getType(); EnumFacing facing = world.getBlockState(pos).getValue(BlockBCBase_Neptune.PROP_FACING); - Rotation rotation = Arrays.stream(Rotation.values()).filter(r -> r.rotate(snapshot.facing) == facing).findFirst().orElse(null); + Rotation rotation = Arrays.stream(Rotation.values()).filter(r -> r.rotate(snapshot.facing) == facing) + .findFirst().orElse(null); if (snapshot.getType() == EnumSnapshotType.TEMPLATE) { templateBuildingInfo = ((Template) snapshot).new BuildingInfo(getCurrentBasePos(), rotation); } @@ -267,7 +274,7 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext path = new ArrayList<>(); int pathSize = buffer.readInt(); if (pathSize != 0) { - for (int i =0; i < pathSize; i++) { + for (int i = 0; i < pathSize; i++) { path.add(MessageUtil.readBlockPos(buffer)); } } else { @@ -276,7 +283,6 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext updateBasePoses(); if (buffer.readBoolean()) { snapshotType = buffer.readEnumValue(EnumSnapshotType.class); - // noinspection ConstantConditions getBuilder().readFromByteBuf(buffer); } else { snapshotType = null; @@ -292,8 +298,11 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext canExcavate = buffer.readBoolean(); } if (id == NET_SNAPSHOT_TYPE) { + EnumSnapshotType old = snapshotType; snapshotType = buffer.readEnumValue(EnumOptionalSnapshotType.class).type; - world.notifyBlockUpdate(pos, world.getBlockState(pos), world.getBlockState(pos), 0); + if (old != snapshotType) { + redrawBlock(); + } } } if (side == Side.SERVER) { @@ -325,9 +334,11 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); if (nbt.hasKey("path")) { - path = NBTUtilBC.readCompoundList(nbt.getTagList("path", Constants.NBT.TAG_COMPOUND)).map(NBTUtil::getPosFromTag).collect(Collectors.toList()); + path = NBTUtilBC.readCompoundList(nbt.getTagList("path", Constants.NBT.TAG_COMPOUND)) + .map(NBTUtil::getPosFromTag).collect(Collectors.toList()); } - basePoses = NBTUtilBC.readCompoundList(nbt.getTagList("basePoses", Constants.NBT.TAG_COMPOUND)).map(NBTUtil::getPosFromTag).collect(Collectors.toList()); + basePoses = NBTUtilBC.readCompoundList(nbt.getTagList("basePoses", Constants.NBT.TAG_COMPOUND)) + .map(NBTUtil::getPosFromTag).collect(Collectors.toList()); canExcavate = nbt.getBoolean("canExcavate"); } From 3d69561966b717fdb414a558539efffde49c0bc5 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Tue, 27 Jun 2017 23:49:18 +0300 Subject: [PATCH 46/89] Fix cancel crash --- .../builders/snapshot/SnapshotBuilder.java | 3 +- .../buildcraft/builders/tile/TileBuilder.java | 36 +++++++++++++------ 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/common/buildcraft/builders/snapshot/SnapshotBuilder.java b/common/buildcraft/builders/snapshot/SnapshotBuilder.java index 4253107f4f..912a8a4449 100644 --- a/common/buildcraft/builders/snapshot/SnapshotBuilder.java +++ b/common/buildcraft/builders/snapshot/SnapshotBuilder.java @@ -8,6 +8,7 @@ import java.io.IOException; import java.util.ArrayDeque; +import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; @@ -274,7 +275,7 @@ public void cancel() { clientPlaceTasks.clear(); prevClientPlaceTasks.clear(); toCheck.clear(); - checkResults.clear(); + checkResults.values().forEach(Collection::clear); robotPos = null; prevRobotPos = null; leftToBreak = 0; diff --git a/common/buildcraft/builders/tile/TileBuilder.java b/common/buildcraft/builders/tile/TileBuilder.java index 91e91058de..c01635759e 100644 --- a/common/buildcraft/builders/tile/TileBuilder.java +++ b/common/buildcraft/builders/tile/TileBuilder.java @@ -81,18 +81,30 @@ public class TileBuilder extends TileBC_Neptune public static final int NET_CAN_EXCAVATE = IDS.allocId("CAN_EXCAVATE"); public static final int NET_SNAPSHOT_TYPE = IDS.allocId("SNAPSHOT_TYPE"); - public final ItemHandlerSimple invSnapshot = - itemManager.addInvHandler("snapshot", 1, EnumAccess.BOTH, EnumPipePart.VALUES); - public final ItemHandlerSimple invResources = - itemManager.addInvHandler("resources", 27, EnumAccess.BOTH, EnumPipePart.VALUES); + public final ItemHandlerSimple invSnapshot = itemManager.addInvHandler( + "snapshot", + 1, + EnumAccess.BOTH, + EnumPipePart.VALUES + ); + public final ItemHandlerSimple invResources = itemManager.addInvHandler( + "resources", + 27, + EnumAccess.BOTH, + EnumPipePart.VALUES + ); private final TankManager tankManager = new TankManager<>(); private final MjBattery battery = new MjBattery(1000 * MjAPI.MJ); private boolean canExcavate = true; - /** Stores the real path - just a few block positions. */ + /** + * Stores the real path - just a few block positions. + */ public List path = null; - /** Stores the real path plus all possible block positions inbetween. */ + /** + * Stores the real path plus all possible block positions inbetween. + */ private List basePoses = new ArrayList<>(); private int currentBasePosIndex = 0; private Snapshot snapshot = null; @@ -119,8 +131,10 @@ public IdAllocator getIdAllocator() { } @Override - protected void onSlotChange(IItemHandlerModifiable itemHandler, int slot, @Nonnull ItemStack before, - @Nonnull ItemStack after) { + protected void onSlotChange(IItemHandlerModifiable itemHandler, + int slot, + @Nonnull ItemStack before, + @Nonnull ItemStack after) { if (itemHandler == invSnapshot) { currentBasePosIndex = 0; snapshot = null; @@ -335,10 +349,12 @@ public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); if (nbt.hasKey("path")) { path = NBTUtilBC.readCompoundList(nbt.getTagList("path", Constants.NBT.TAG_COMPOUND)) - .map(NBTUtil::getPosFromTag).collect(Collectors.toList()); + .map(NBTUtil::getPosFromTag) + .collect(Collectors.toList()); } basePoses = NBTUtilBC.readCompoundList(nbt.getTagList("basePoses", Constants.NBT.TAG_COMPOUND)) - .map(NBTUtil::getPosFromTag).collect(Collectors.toList()); + .map(NBTUtil::getPosFromTag) + .collect(Collectors.toList()); canExcavate = nbt.getBoolean("canExcavate"); } From 76678615df00ab339787c48acafc421f8de6660d Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 27 Jun 2017 21:58:20 +0100 Subject: [PATCH 47/89] Fix shift-clicking on slots not updatign the callback. Fix the builder not updating the visual snapshot type properly. --- .../buildcraft/builders/tile/TileBuilder.java | 22 +++++++++---------- common/buildcraft/lib/gui/slot/SlotBase.java | 9 ++++++++ .../lib/tile/item/ItemHandlerSimple.java | 7 +++++- 3 files changed, 26 insertions(+), 12 deletions(-) diff --git a/common/buildcraft/builders/tile/TileBuilder.java b/common/buildcraft/builders/tile/TileBuilder.java index 91e91058de..c674b38aea 100644 --- a/common/buildcraft/builders/tile/TileBuilder.java +++ b/common/buildcraft/builders/tile/TileBuilder.java @@ -122,19 +122,19 @@ public IdAllocator getIdAllocator() { protected void onSlotChange(IItemHandlerModifiable itemHandler, int slot, @Nonnull ItemStack before, @Nonnull ItemStack after) { if (itemHandler == invSnapshot) { - currentBasePosIndex = 0; - snapshot = null; - if (after.getItem() instanceof ItemSnapshot) { - Snapshot.Header header = BCBuildersItems.snapshot.getHeader(after); - if (header != null) { - Snapshot newSnapshot = GlobalSavedDataSnapshots.get(world).getSnapshotByHeader(header); - if (newSnapshot != null) { - snapshot = newSnapshot; + if (!world.isRemote) { + currentBasePosIndex = 0; + snapshot = null; + if (after.getItem() instanceof ItemSnapshot) { + Snapshot.Header header = BCBuildersItems.snapshot.getHeader(after); + if (header != null) { + Snapshot newSnapshot = GlobalSavedDataSnapshots.get(world).getSnapshotByHeader(header); + if (newSnapshot != null) { + snapshot = newSnapshot; + } } } - } - updateSnapshot(); - if (!world.isRemote) { + updateSnapshot(); sendNetworkUpdate(NET_SNAPSHOT_TYPE); } } diff --git a/common/buildcraft/lib/gui/slot/SlotBase.java b/common/buildcraft/lib/gui/slot/SlotBase.java index c2b1109478..c6b7915faf 100644 --- a/common/buildcraft/lib/gui/slot/SlotBase.java +++ b/common/buildcraft/lib/gui/slot/SlotBase.java @@ -12,6 +12,7 @@ import net.minecraftforge.items.SlotItemHandler; import buildcraft.lib.tile.item.IItemHandlerAdv; +import buildcraft.lib.tile.item.ItemHandlerSimple; public class SlotBase extends SlotItemHandler { public final int handlerIndex; @@ -38,4 +39,12 @@ public boolean isItemValid(@Nonnull ItemStack stack) { public ItemStack insert(ItemStack stack, boolean simulate) { return getItemHandler().insertItem(handlerIndex, stack, simulate); } + + @Override + public void onSlotChanged() { + super.onSlotChanged(); + if (itemHandler instanceof ItemHandlerSimple) { + ((ItemHandlerSimple) itemHandler).setStackInSlot(handlerIndex, getStack()); + } + } } diff --git a/common/buildcraft/lib/tile/item/ItemHandlerSimple.java b/common/buildcraft/lib/tile/item/ItemHandlerSimple.java index e39cb212e8..246070f15c 100644 --- a/common/buildcraft/lib/tile/item/ItemHandlerSimple.java +++ b/common/buildcraft/lib/tile/item/ItemHandlerSimple.java @@ -209,7 +209,12 @@ public final boolean canSet(int slot, @Nonnull ItemStack stack) { private void setStackInternal(int slot, @Nonnull ItemStack stack) { ItemStack before = stacks.get(slot); - if (!ItemStack.areItemStacksEqual(before, stack)) { + if (ItemStack.areItemStacksEqual(before, stack)) { + // Called by some things for the callback -- it may have changed previously + if (callback != null) { + callback.onStackChange(this, slot, before, asValid(stack)); + } + } else { stacks.set(slot, asValid(stack)); // Transactor calc if (stack.isEmpty() && firstUsed == slot) { From b311fab563ff0f81f6c26c0ef422ed391f065126 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 27 Jun 2017 22:06:05 +0100 Subject: [PATCH 48/89] Remove unecessary check. --- .../lib/tile/item/ItemHandlerSimple.java | 43 ++++++++----------- 1 file changed, 17 insertions(+), 26 deletions(-) diff --git a/common/buildcraft/lib/tile/item/ItemHandlerSimple.java b/common/buildcraft/lib/tile/item/ItemHandlerSimple.java index 246070f15c..a34a616d99 100644 --- a/common/buildcraft/lib/tile/item/ItemHandlerSimple.java +++ b/common/buildcraft/lib/tile/item/ItemHandlerSimple.java @@ -113,7 +113,8 @@ public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate InsertionResult result = insertor.modifyForInsertion(slot, asValid(current.copy()), asValid(stack.copy())); if (!canSet(slot, result.toSet)) { // We have a bad inserter or checker, as they should not be conflicting - CrashReport report = new CrashReport("Inserting an item (buildcraft:ItemHandlerSimple)", new IllegalStateException("Confilicting Insertion!")); + CrashReport report = new CrashReport("Inserting an item (buildcraft:ItemHandlerSimple)", + new IllegalStateException("Confilicting Insertion!")); CrashReportCategory cat = report.makeCategory("Inventory details"); cat.addCrashSection("Existing Item", current); cat.addCrashSection("Inserting Item", stack); @@ -209,31 +210,24 @@ public final boolean canSet(int slot, @Nonnull ItemStack stack) { private void setStackInternal(int slot, @Nonnull ItemStack stack) { ItemStack before = stacks.get(slot); - if (ItemStack.areItemStacksEqual(before, stack)) { - // Called by some things for the callback -- it may have changed previously - if (callback != null) { - callback.onStackChange(this, slot, before, asValid(stack)); - } - } else { - stacks.set(slot, asValid(stack)); - // Transactor calc - if (stack.isEmpty() && firstUsed == slot) { - for (int s = firstUsed; s < getSlots(); s++) { - if (!stacks.get(s).isEmpty()) { - firstUsed = s; - break; - } - } - if (firstUsed == slot) { - firstUsed = Integer.MAX_VALUE; + stacks.set(slot, asValid(stack)); + // Transactor calc + if (stack.isEmpty() && firstUsed == slot) { + for (int s = firstUsed; s < getSlots(); s++) { + if (!stacks.get(s).isEmpty()) { + firstUsed = s; + break; } - } else if (!stack.isEmpty() && firstUsed > slot) { - firstUsed = slot; } - - if (callback != null) { - callback.onStackChange(this, slot, before, asValid(stack)); + if (firstUsed == slot) { + firstUsed = Integer.MAX_VALUE; } + } else if (!stack.isEmpty() && firstUsed > slot) { + firstUsed = slot; + } + + if (callback != null) { + callback.onStackChange(this, slot, before, asValid(stack)); } } @@ -241,7 +235,4 @@ private void setStackInternal(int slot, @Nonnull ItemStack stack) { public int getSlotLimit(int slot) { return 64; } - - - } From 3b85aea72320c44fc8d0584993f4a98efa0e8755 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Wed, 28 Jun 2017 01:00:29 +0100 Subject: [PATCH 49/89] Make the heat exhcnager functional --- common/buildcraft/energy/BCEnergyRecipes.java | 40 ++++- .../factory/tile/TileHeatExchangeEnd.java | 18 ++- .../factory/tile/TileHeatExchangeStart.java | 149 +++++++++++++++++- common/buildcraft/lib/misc/FluidUtilBC.java | 43 ++++- common/buildcraft/lib/misc/MathUtil.java | 4 + 5 files changed, 233 insertions(+), 21 deletions(-) diff --git a/common/buildcraft/energy/BCEnergyRecipes.java b/common/buildcraft/energy/BCEnergyRecipes.java index 17bf09738b..738f047dc8 100644 --- a/common/buildcraft/energy/BCEnergyRecipes.java +++ b/common/buildcraft/energy/BCEnergyRecipes.java @@ -20,6 +20,7 @@ import buildcraft.api.recipes.BuildcraftRecipeRegistry; import buildcraft.api.recipes.IRefineryRecipeManager.IDistillationRecipe; +import buildcraft.lib.fluid.BCFluid; import buildcraft.lib.recipe.OredictionaryNames; import buildcraft.lib.recipe.RecipeBuilderShaped; @@ -51,8 +52,10 @@ public static void init() { } BuildcraftFuelRegistry.coolant.addCoolant(FluidRegistry.WATER, 0.0023f); - BuildcraftFuelRegistry.coolant.addSolidCoolant(new ItemStack(Blocks.ICE), new FluidStack(FluidRegistry.WATER, 1000), 1.5f); - BuildcraftFuelRegistry.coolant.addSolidCoolant(new ItemStack(Blocks.PACKED_ICE), new FluidStack(FluidRegistry.WATER, 1000), 2f); + BuildcraftFuelRegistry.coolant.addSolidCoolant(new ItemStack(Blocks.ICE), + new FluidStack(FluidRegistry.WATER, 1000), 1.5f); + BuildcraftFuelRegistry.coolant.addSolidCoolant(new ItemStack(Blocks.PACKED_ICE), + new FluidStack(FluidRegistry.WATER, 1000), 2f); // Relative amounts of the fluid -- the amount of oil used in refining will return X amount of fluid @@ -112,6 +115,17 @@ public static void init() { addDistillation(light_dense, light, dense, 1, 16 * MjAPI.MJ); addDistillation(dense_residue, dense, residue, 2, 12 * MjAPI.MJ); + + addHeatExchange(BCEnergyFluids.crudeOil, 3); + addHeatExchange(BCEnergyFluids.oilDistilled, 2); + addHeatExchange(BCEnergyFluids.oilHeavy, 3); + addHeatExchange(BCEnergyFluids.fuelMixedLight, 2); + addHeatExchange(BCEnergyFluids.fuelMixedHeavy, 2); + addHeatExchange(BCEnergyFluids.oilDense, 3); + addHeatExchange(BCEnergyFluids.fuelGaseous, 1); + addHeatExchange(BCEnergyFluids.fuelLight, 1); + addHeatExchange(BCEnergyFluids.fuelDense, 2); + addHeatExchange(BCEnergyFluids.oilResidue, 6); } } @@ -153,18 +167,34 @@ private static void addDirtyFuel(Fluid[] in, int amountDiff, int multiplier) { if (residue == null) {// residue might have been disabled BuildcraftFuelRegistry.fuel.addFuel(fuel, powerPerCycle, totalTime); } else { - BuildcraftFuelRegistry.fuel.addDirtyFuel(fuel, powerPerCycle, totalTime, new FluidStack(residue, 1000 / amountDiff)); + BuildcraftFuelRegistry.fuel.addDirtyFuel(fuel, powerPerCycle, totalTime, + new FluidStack(residue, 1000 / amountDiff)); } } - private static void addDistillation(FluidStack[] in, FluidStack[] outGas, FluidStack[] outLiquid, int heat, long mjCost) { + private static void addDistillation(FluidStack[] in, FluidStack[] outGas, FluidStack[] outLiquid, int heat, + long mjCost) { FluidStack _in = in[heat]; FluidStack _outGas = outGas[heat]; FluidStack _outLiquid = outLiquid[heat]; - IDistillationRecipe existing = BuildcraftRecipeRegistry.refineryRecipes.getDistilationRegistry().getRecipeForInput(_in); + IDistillationRecipe existing = + BuildcraftRecipeRegistry.refineryRecipes.getDistilationRegistry().getRecipeForInput(_in); if (existing != null) { throw new IllegalStateException("Already added distillation recipe for " + _in.getFluid().getName()); } BuildcraftRecipeRegistry.refineryRecipes.addDistillationRecipe(_in, _outGas, _outLiquid, mjCost); } + + private static void addHeatExchange(BCFluid[] fluid, int ticks) { + for (int i = 0; i < fluid.length - 1; i++) { + BCFluid cool = fluid[i]; + BCFluid hot = fluid[i + 1]; + FluidStack cool_f = new FluidStack(cool, 10); + FluidStack hot_f = new FluidStack(hot, 10); + int ch = cool.getHeatValue(); + int hh = hot.getHeatValue(); + BuildcraftRecipeRegistry.refineryRecipes.addHeatableRecipe(cool_f, hot_f, ch, hh, ticks); + BuildcraftRecipeRegistry.refineryRecipes.addCoolableRecipe(hot_f, cool_f, hh, ch, ticks); + } + } } diff --git a/common/buildcraft/factory/tile/TileHeatExchangeEnd.java b/common/buildcraft/factory/tile/TileHeatExchangeEnd.java index f21eb01f18..703bb1effb 100644 --- a/common/buildcraft/factory/tile/TileHeatExchangeEnd.java +++ b/common/buildcraft/factory/tile/TileHeatExchangeEnd.java @@ -17,12 +17,14 @@ import net.minecraft.util.EnumFacing; import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import buildcraft.api.core.EnumPipePart; +import buildcraft.api.recipes.BuildcraftRecipeRegistry; import buildcraft.api.tiles.IDebuggable; import buildcraft.lib.block.BlockBCBase_Neptune; @@ -36,12 +38,17 @@ public class TileHeatExchangeEnd extends TileBC_Neptune implements IDebuggable { public final Tank tankHeatableOut = new Tank("heatable_out", 2 * Fluid.BUCKET_VOLUME, this); - public final Tank tankCoolableIn = new Tank("coolable_in", 2 * Fluid.BUCKET_VOLUME, this); + public final Tank tankCoolableIn = new Tank("coolable_in", 2 * Fluid.BUCKET_VOLUME, this, this::isCoolant); private final TankManager tankManager = new TankManager<>(tankHeatableOut, tankCoolableIn); public TileHeatExchangeEnd() { caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankHeatableOut, EnumPipePart.UP); caps.addCapability(CapUtil.CAP_FLUIDS, this::getTankForSide, EnumPipePart.HORIZONTALS); + tankHeatableOut.setCanFill(false); + } + + private boolean isCoolant(FluidStack fluid) { + return BuildcraftRecipeRegistry.refineryRecipes.getCoolableRegistry().getRecipeForInput(fluid) != null; } private IFluidHandler getTankForSide(EnumFacing side) { @@ -98,15 +105,10 @@ public void getDebugInfo(List left, List right, EnumFacing side) @Nullable public IFluidHandler getFluidAutoOutputTarget() { - IBlockState state = getCurrentStateForBlock(BCFactoryBlocks.heatExchangeEnd); - if (state == null) { - return null; - } - EnumFacing facing = state.getValue(BlockBCBase_Neptune.PROP_FACING); - TileEntity tile = getNeighbourTile(facing.getOpposite()); + TileEntity tile = getNeighbourTile(EnumFacing.UP); if (tile == null) { return null; } - return tile.getCapability(CapUtil.CAP_FLUIDS, facing); + return tile.getCapability(CapUtil.CAP_FLUIDS, EnumFacing.DOWN); } } diff --git a/common/buildcraft/factory/tile/TileHeatExchangeStart.java b/common/buildcraft/factory/tile/TileHeatExchangeStart.java index a807eb05fa..d2602bb1ac 100644 --- a/common/buildcraft/factory/tile/TileHeatExchangeStart.java +++ b/common/buildcraft/factory/tile/TileHeatExchangeStart.java @@ -9,6 +9,8 @@ import java.io.IOException; import java.util.List; +import javax.annotation.Nullable; + import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; @@ -17,18 +19,26 @@ import net.minecraft.util.math.BlockPos; import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import buildcraft.api.core.BCLog; import buildcraft.api.core.EnumPipePart; +import buildcraft.api.recipes.BuildcraftRecipeRegistry; +import buildcraft.api.recipes.IRefineryRecipeManager; +import buildcraft.api.recipes.IRefineryRecipeManager.ICoolableRecipe; +import buildcraft.api.recipes.IRefineryRecipeManager.IHeatableRecipe; import buildcraft.api.tiles.IDebuggable; import buildcraft.lib.block.BlockBCBase_Neptune; import buildcraft.lib.fluid.Tank; import buildcraft.lib.fluid.TankManager; import buildcraft.lib.misc.CapUtil; +import buildcraft.lib.misc.FluidUtilBC; +import buildcraft.lib.misc.MathUtil; import buildcraft.lib.net.PacketBufferBC; import buildcraft.lib.tile.TileBC_Neptune; @@ -36,19 +46,25 @@ import buildcraft.factory.block.BlockHeatExchange; public class TileHeatExchangeStart extends TileBC_Neptune implements ITickable, IDebuggable { - public final Tank tankHeatableIn = new Tank("heatable_in", 2 * Fluid.BUCKET_VOLUME, this); + public final Tank tankHeatableIn = new Tank("heatable_in", 2 * Fluid.BUCKET_VOLUME, this, this::isHeatant); public final Tank tankCoolableOut = new Tank("coolable_out", 2 * Fluid.BUCKET_VOLUME, this); private final TankManager tankManager = new TankManager<>(tankHeatableIn, tankCoolableOut); private TileHeatExchangeEnd tileEnd; + private int progress = 0; public TileHeatExchangeStart() { caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankHeatableIn, EnumPipePart.DOWN); caps.addCapability(CapUtil.CAP_FLUIDS, this::getTankForSide, EnumPipePart.HORIZONTALS); + tankCoolableOut.setCanFill(false); + } + + private boolean isHeatant(FluidStack fluid) { + return BuildcraftRecipeRegistry.refineryRecipes.getHeatableRegistry().getRecipeForInput(fluid) != null; } private IFluidHandler getTankForSide(EnumFacing side) { - IBlockState state = getCurrentStateForBlock(BCFactoryBlocks.heatExchangeEnd); + IBlockState state = getCurrentStateForBlock(BCFactoryBlocks.heatExchangeStart); if (state == null) { return null; } @@ -98,10 +114,20 @@ public void update() { // TODO: Client stuffs return; } + tileEnd = null; + findEnd(); + if (tileEnd != null) { + craft(); + } + output(); + } + + private void findEnd() { // TODO (AlexIIL): Make this check passive, not active. tileEnd = null; IBlockState state = getCurrentStateForBlock(BCFactoryBlocks.heatExchangeStart); if (state == null) { + // BCLog.logger.warn("Null state"); return; } BlockHeatExchange block = (BlockHeatExchange) state.getBlock(); @@ -112,30 +138,142 @@ public void update() { search = search.offset(facing); state = getLocalState(search); if (state.getBlock() != BCFactoryBlocks.heatExchangeMiddle) { + // BCLog.logger.warn("Not middle @ " + search + " (" + i + ")"); break; } block = BCFactoryBlocks.heatExchangeMiddle; if (block.part.getAxis(state) != facing.getAxis()) { + // BCLog.logger.warn("Wrong axis!"); return; } middles++; } if (middles == 0) { + // BCLog.logger.warn("No middles!"); return; } - search = search.offset(facing); - state = getLocalState(search); if (state.getBlock() != BCFactoryBlocks.heatExchangeEnd) { + // BCLog.logger.warn("Not end @ " + search); return; } if (state.getValue(BlockBCBase_Neptune.PROP_FACING) != facing.getOpposite()) { + // BCLog.logger.warn("Wrong EnumFacing"); return; } TileEntity tile = getLocalTile(search); if (tile instanceof TileHeatExchangeEnd) { tileEnd = (TileHeatExchangeEnd) tile; + } else { + // BCLog.logger.warn("Not end tile!"); + } + } + + private void craft() { + Tank c_in = tileEnd.tankCoolableIn; + Tank c_out = tankCoolableOut; + Tank h_in = tankHeatableIn; + Tank h_out = tileEnd.tankHeatableOut; + IRefineryRecipeManager reg = BuildcraftRecipeRegistry.refineryRecipes; + ICoolableRecipe c_recipe = reg.getCoolableRegistry().getRecipeForInput(c_in.getFluid()); + IHeatableRecipe h_recipe = reg.getHeatableRegistry().getRecipeForInput(h_in.getFluid()); + if (h_recipe == null || c_recipe == null) { + BCLog.logger.warn("A recipe was null"); + return; + } + if (c_recipe.heatFrom() <= h_recipe.heatFrom()) { + BCLog.logger.warn("Invalid heat values!"); + return; + } + int c_diff = c_recipe.heatFrom() - c_recipe.heatTo(); + int h_diff = h_recipe.heatTo() - h_recipe.heatFrom(); + if (h_diff < 1 || c_diff < 1) { + throw new IllegalStateException("Invalid recipe " + c_recipe + ", " + h_recipe); + } + int c_mult = 1; + int h_mult = 1; + if (h_diff != c_diff) { + int lcm = MathUtil.findLowestCommonMultiple(c_diff, h_diff); + c_mult = lcm / c_diff; + h_mult = lcm / h_diff; + } + FluidStack c_in_f = mult(c_recipe.in(), c_mult); + FluidStack c_out_f = mult(c_recipe.out(), c_mult); + FluidStack h_in_f = mult(h_recipe.in(), h_mult); + FluidStack h_out_f = mult(h_recipe.out(), h_mult); + if (canFill(c_out, c_out_f) && canFill(h_out, h_out_f) && canDrain(c_in, c_in_f) && canDrain(h_in, h_in_f)) { + progress++; + int lag = Math.max(c_recipe.ticks(), h_recipe.ticks()); + if (progress >= lag) { + fill(c_out, c_out_f); + fill(h_out, h_out_f); + drain(c_in, c_in_f); + drain(h_in, h_in_f); + progress = lag; + // TODO: Add particles if its water or lava + } + } + } + + private void output() { + IFluidHandler thisOut = getFluidAutoOutputTarget(); + FluidUtilBC.move(tankCoolableOut, thisOut, 1000); + + if (tileEnd != null) { + IFluidHandler endOut = tileEnd.getFluidAutoOutputTarget(); + FluidUtilBC.move(tileEnd.tankHeatableOut, endOut, 1000); + } + } + + private static FluidStack mult(FluidStack fluid, int mult) { + if (fluid == null) { + return null; + } + switch (mult) { + case 0: + case 1: + return fluid; + default: + return new FluidStack(fluid, fluid.amount * mult); + } + } + + private static boolean canFill(Tank t, FluidStack fluid) { + return t.fillInternal(fluid, false) == fluid.amount; + } + + private static boolean canDrain(Tank t, FluidStack fluid) { + FluidStack f2 = t.drainInternal(fluid, false); + return f2 != null && f2.amount == fluid.amount; + } + + private static void fill(Tank t, FluidStack fluid) { + int a = t.fillInternal(fluid, true); + if (a != fluid.amount) { + String err = "Buggy transation! Failed to fill " + fluid.getFluid(); + throw new IllegalStateException(err + " x " + fluid.amount + " into " + t); + } + } + + private static void drain(Tank t, FluidStack fluid) { + FluidStack f2 = t.drainInternal(fluid, true); + if (f2 == null || f2.amount != fluid.amount) { + String err = "Buggy transation! Failed to drain " + fluid.getFluid(); + throw new IllegalStateException(err + " x " + fluid.amount + " from " + t); + } + } + + @Nullable + private IFluidHandler getFluidAutoOutputTarget() { + IBlockState state = getCurrentStateForBlock(BCFactoryBlocks.heatExchangeStart); + if (state == null) { + return null; + } + EnumFacing facing = state.getValue(BlockBCBase_Neptune.PROP_FACING); + TileEntity tile = getNeighbourTile(facing.getOpposite()); + if (tile == null) { + return null; } - // TODO: Ticks! + return tile.getCapability(CapUtil.CAP_FLUIDS, facing); } @Override @@ -143,5 +281,6 @@ public void update() { public void getDebugInfo(List left, List right, EnumFacing side) { left.add("heatable_in = " + tankHeatableIn.getDebugString()); left.add("coolable_out = " + tankCoolableOut.getDebugString()); + left.add("progress = " + progress); } } diff --git a/common/buildcraft/lib/misc/FluidUtilBC.java b/common/buildcraft/lib/misc/FluidUtilBC.java index e82d81b631..6f05e50fdb 100644 --- a/common/buildcraft/lib/misc/FluidUtilBC.java +++ b/common/buildcraft/lib/misc/FluidUtilBC.java @@ -18,6 +18,9 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.IFluidHandler; +import buildcraft.api.core.IFluidFilter; +import buildcraft.api.core.IFluidHandlerAdv; + import buildcraft.lib.fluid.Tank; public class FluidUtilBC { @@ -49,7 +52,8 @@ public static void pushFluidAround(IBlockAccess world, BlockPos pos, Tank tank) if (drained > 0) { FluidStack actuallyDrained = tank.drain(drained, true); if (actuallyDrained == null || actuallyDrained.amount != drained) { - throw new IllegalStateException("Bad tank! Could drain " + working + " but only drained " + actuallyDrained + "( tank " + tank.getClass() + ")"); + throw new IllegalStateException("Bad tank! Could drain " + working + " but only drained " + + actuallyDrained + "( tank " + tank.getClass() + ")"); } } } @@ -79,7 +83,8 @@ public static void pullFluidAround(IBlockAccess world, BlockPos pos, Tank tank) if (filled > 0) { FluidStack reallyDrained = handler.drain(filled, true); if (reallyDrained == null || reallyDrained.amount != filled) { - throw new IllegalStateException("Bad IFluidHandler.drain implementation! ( drained = " + drained + " reallyDrained = " + reallyDrained + " handler " + handler.getClass()); + throw new IllegalStateException("Bad IFluidHandler.drain implementation! ( drained = " + drained + + " reallyDrained = " + reallyDrained + " handler " + handler.getClass()); } max -= filled; } @@ -93,7 +98,8 @@ public static void pullFluidAround(IBlockAccess world, BlockPos pos, Tank tank) fluidFilter.amount = filled; FluidStack reallyDrained = handler.drain(fluidFilter, true); if (reallyDrained == null || reallyDrained.amount != filled) { - throw new IllegalStateException("Bad IFluidHandler.drain implementation! ( drained = " + drained + " reallyDrained = " + reallyDrained + " handler " + handler.getClass()); + throw new IllegalStateException("Bad IFluidHandler.drain implementation! ( drained = " + drained + + " reallyDrained = " + reallyDrained + " handler " + handler.getClass()); } max -= filled; } @@ -129,4 +135,35 @@ public static boolean areFluidsEqual(Fluid a, Fluid b) { } return a.getName().equals(b.getName()); } + + public static int move(IFluidHandler from, IFluidHandler to) { + return move(from, to, Integer.MAX_VALUE); + } + + public static int move(IFluidHandler from, IFluidHandler to, int max) { + if (from == null || to == null) { + return 0; + } + FluidStack toDrainPotential; + if (from instanceof IFluidHandlerAdv) { + IFluidFilter filter = f -> to.fill(f, false) > 0; + toDrainPotential = ((IFluidHandlerAdv) from).drain(filter, max, false); + } else { + toDrainPotential = from.drain(max, false); + } + int accepted = to.fill(toDrainPotential, false); + if (accepted <= 0) { + return 0; + } + FluidStack toDrain = new FluidStack(toDrainPotential, accepted); + FluidStack drained = from.drain(toDrain, true); + if (!toDrain.isFluidEqual(drained) || toDrain.amount != drained.amount) { + throw new IllegalStateException(""); + } + int actuallyAccepted = to.fill(drained, true); + if (actuallyAccepted != accepted) { + throw new IllegalStateException("Mismatched IFluidHandler implementations!"); + } + return actuallyAccepted; + } } diff --git a/common/buildcraft/lib/misc/MathUtil.java b/common/buildcraft/lib/misc/MathUtil.java index 0beb3166ed..3f513871f6 100644 --- a/common/buildcraft/lib/misc/MathUtil.java +++ b/common/buildcraft/lib/misc/MathUtil.java @@ -69,4 +69,8 @@ public static int findHighestCommonFactor(int a, int b) { } return a; } + + public static int findLowestCommonMultiple(int a, int b) { + return (a / findHighestCommonFactor(a, b)) * b; + } } From d697142d9f21009d575703b86021626ec7cfc2f2 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Wed, 28 Jun 2017 01:29:54 +0100 Subject: [PATCH 50/89] Add particle effects :P Tempt ofc - these need to be spawned on the client, this won't work outside of single-player. We also need other rendering... --- common/buildcraft/energy/BCEnergyRecipes.java | 6 +++ .../factory/tile/TileHeatExchangeStart.java | 46 ++++++++++++++-- .../client/render/PipeFlowRendererPower.java | 4 +- .../transport/pipe/flow/PipeFlowPower.java | 54 +++++++++---------- 4 files changed, 75 insertions(+), 35 deletions(-) diff --git a/common/buildcraft/energy/BCEnergyRecipes.java b/common/buildcraft/energy/BCEnergyRecipes.java index 738f047dc8..8e2eb2f3eb 100644 --- a/common/buildcraft/energy/BCEnergyRecipes.java +++ b/common/buildcraft/energy/BCEnergyRecipes.java @@ -126,6 +126,12 @@ public static void init() { addHeatExchange(BCEnergyFluids.fuelLight, 1); addHeatExchange(BCEnergyFluids.fuelDense, 2); addHeatExchange(BCEnergyFluids.oilResidue, 6); + + FluidStack water = new FluidStack(FluidRegistry.WATER, 10); + BuildcraftRecipeRegistry.refineryRecipes.addHeatableRecipe(water, null, 0, 1, 2); + + FluidStack lava = new FluidStack(FluidRegistry.LAVA, 5); + BuildcraftRecipeRegistry.refineryRecipes.addCoolableRecipe(lava, null, 4, 3, 5); } } diff --git a/common/buildcraft/factory/tile/TileHeatExchangeStart.java b/common/buildcraft/factory/tile/TileHeatExchangeStart.java index d2602bb1ac..a8253ffd35 100644 --- a/common/buildcraft/factory/tile/TileHeatExchangeStart.java +++ b/common/buildcraft/factory/tile/TileHeatExchangeStart.java @@ -12,13 +12,18 @@ import javax.annotation.Nullable; import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; @@ -39,6 +44,7 @@ import buildcraft.lib.misc.CapUtil; import buildcraft.lib.misc.FluidUtilBC; import buildcraft.lib.misc.MathUtil; +import buildcraft.lib.misc.VecUtil; import buildcraft.lib.net.PacketBufferBC; import buildcraft.lib.tile.TileBC_Neptune; @@ -177,7 +183,6 @@ private void craft() { ICoolableRecipe c_recipe = reg.getCoolableRegistry().getRecipeForInput(c_in.getFluid()); IHeatableRecipe h_recipe = reg.getHeatableRegistry().getRecipeForInput(h_in.getFluid()); if (h_recipe == null || c_recipe == null) { - BCLog.logger.warn("A recipe was null"); return; } if (c_recipe.heatFrom() <= h_recipe.heatFrom()) { @@ -209,7 +214,39 @@ private void craft() { drain(c_in, c_in_f); drain(h_in, h_in_f); progress = lag; - // TODO: Add particles if its water or lava + if (c_in_f.getFluid() == FluidRegistry.LAVA) { + // Output is at the other end + Vec3d from = VecUtil.convertCenter(getPos()); + EnumFacing dir = EnumFacing.SOUTH; + spewForth(from, dir, EnumParticleTypes.SMOKE_LARGE); + } + if (h_in_f.getFluid() == FluidRegistry.WATER) { + // Output is here + Vec3d from = VecUtil.convertCenter(tileEnd.getPos()); + EnumFacing dir = EnumFacing.UP; + spewForth(from, dir, EnumParticleTypes.CLOUD); + } + } + } + } + + private static void spewForth(Vec3d from, EnumFacing dir, EnumParticleTypes particle) { + Vec3d vecDir = new Vec3d(dir.getDirectionVec()); + from = from.add(VecUtil.scale(vecDir, 0.5)); + + double x = from.xCoord; + double y = from.yCoord; + double z = from.zCoord; + + Vec3d motion = VecUtil.scale(vecDir, 0.4); + for (int i = 0; i < 10; i++) { + double dx = motion.xCoord + Math.random() * 0.01; + double dy = motion.yCoord + Math.random() * 0.01; + double dz = motion.zCoord + Math.random() * 0.01; + + WorldClient w = Minecraft.getMinecraft().world; + if (w != null) { + w.spawnParticle(particle, x, y, z, dx, dy, dz); } } } @@ -238,7 +275,7 @@ private static FluidStack mult(FluidStack fluid, int mult) { } private static boolean canFill(Tank t, FluidStack fluid) { - return t.fillInternal(fluid, false) == fluid.amount; + return fluid == null || t.fillInternal(fluid, false) == fluid.amount; } private static boolean canDrain(Tank t, FluidStack fluid) { @@ -247,6 +284,9 @@ private static boolean canDrain(Tank t, FluidStack fluid) { } private static void fill(Tank t, FluidStack fluid) { + if (fluid == null) { + return; + } int a = t.fillInternal(fluid, true); if (a != fluid.amount) { String err = "Buggy transation! Failed to fill " + fluid.getFluid(); diff --git a/common/buildcraft/transport/client/render/PipeFlowRendererPower.java b/common/buildcraft/transport/client/render/PipeFlowRendererPower.java index 893dedccc3..db54db5b55 100644 --- a/common/buildcraft/transport/client/render/PipeFlowRendererPower.java +++ b/common/buildcraft/transport/client/render/PipeFlowRendererPower.java @@ -29,10 +29,10 @@ public enum PipeFlowRendererPower implements IPipeFlowRenderer { @Override public void render(PipeFlowPower flow, double x, double y, double z, float partialTicks, VertexBuffer vb) { - float r = (float) flow.clientPowerAmounts.values().stream() + float r = 0;/*(float) flow.clientPowerAmounts.values().stream() .mapToDouble(Double::valueOf) .average() - .orElse(0) / PipeFlowPower.DEFAULT_MAX_POWER * 0.8F; + .orElse(0) / PipeFlowPower.DEFAULT_MAX_POWER * 0.8F;*/ if (r == 0) { return; } diff --git a/common/buildcraft/transport/pipe/flow/PipeFlowPower.java b/common/buildcraft/transport/pipe/flow/PipeFlowPower.java index 6f3289683b..004b5cbb83 100644 --- a/common/buildcraft/transport/pipe/flow/PipeFlowPower.java +++ b/common/buildcraft/transport/pipe/flow/PipeFlowPower.java @@ -10,9 +10,7 @@ import java.util.Arrays; import java.util.EnumMap; import java.util.List; -import java.util.function.Function; import java.util.function.ToLongFunction; -import java.util.stream.Collectors; import javax.annotation.Nonnull; @@ -47,7 +45,7 @@ import buildcraft.lib.misc.data.AverageInt; public class PipeFlowPower extends PipeFlow implements IFlowPower, IDebuggable { - public static final long DEFAULT_MAX_POWER = MjAPI.MJ * 10; + private static final long DEFAULT_MAX_POWER = MjAPI.MJ * 10; public static final int NET_POWER_AMOUNTS = 2; private long maxPower = -1; @@ -57,29 +55,24 @@ public class PipeFlowPower extends PipeFlow implements IFlowPower, IDebuggable { private long currentWorldTime; private boolean isReceiver = false; - private final EnumMap sections = Arrays.stream(EnumFacing.VALUES) - .collect(Collectors.toMap( - Function.identity(), - Section::new, - (u, v) -> u, - () -> new EnumMap<>(EnumFacing.class) - )); - public final EnumMap clientPowerAmounts = Arrays.stream(EnumFacing.VALUES) - .collect(Collectors.toMap( - Function.identity(), - f -> 0D, - (u, v) -> u, - () -> new EnumMap<>(EnumFacing.class) - )); + private final EnumMap sections; private final SafeTimeTracker tracker = new SafeTimeTracker(1); public PipeFlowPower(IPipe pipe) { super(pipe); + sections = new EnumMap<>(EnumFacing.class); + for (EnumFacing face : EnumFacing.VALUES) { + sections.put(face, new Section(face)); + } } public PipeFlowPower(IPipe pipe, NBTTagCompound nbt) { super(pipe, nbt); + sections = new EnumMap<>(EnumFacing.class); + for (EnumFacing face : EnumFacing.VALUES) { + sections.put(face, new Section(face)); + } } @Override @@ -95,9 +88,7 @@ public void writePayload(int id, PacketBuffer buffer, Side side) { if (side == Side.SERVER) { if (id == NET_POWER_AMOUNTS || id == NET_ID_FULL_STATE) { for (EnumFacing face : EnumFacing.VALUES) { - buffer.writeDouble( - sections.get(face).displayPower - ); + buffer.writeDouble(sections.get(face).displayPower); } } } @@ -109,7 +100,7 @@ public void readPayload(int id, PacketBuffer buffer, Side side) throws IOExcepti if (side == Side.CLIENT) { if (id == NET_POWER_AMOUNTS || id == NET_ID_FULL_STATE) { for (EnumFacing face : EnumFacing.VALUES) { - clientPowerAmounts.put(face, buffer.readDouble()); + sections.get(face).clientPowerAmount = buffer.readDouble(); } } } @@ -179,7 +170,8 @@ public long tryExtractPower(long maxExtracted, EnumFacing from) { } @Override - public boolean onFlowActivate(EntityPlayer player, RayTraceResult trace, float hitX, float hitY, float hitZ, EnumPipePart part) { + public boolean onFlowActivate(EntityPlayer player, RayTraceResult trace, float hitX, float hitY, float hitZ, + EnumPipePart part) { return super.onFlowActivate(player, trace, hitX, hitY, hitZ, part); } @@ -201,9 +193,11 @@ public T getCapability(@Nonnull Capability capability, EnumFacing facing) public void getDebugInfo(List left, List right, EnumFacing side) { left.add("maxPower = " + LocaleUtil.localizeMj(maxPower)); left.add("isReceiver = " + isReceiver); - left.add("internalPower = " + arrayToString(s -> s.internalPower) + " <- " + arrayToString(s -> s.internalNextPower)); + left.add("internalPower = " + arrayToString(s -> s.internalPower) + " <- " + + arrayToString(s -> s.internalNextPower)); left.add("- powerQuery: " + arrayToString(s -> s.powerQuery) + " <- " + arrayToString(s -> s.nextPowerQuery)); - left.add("- power: IN " + arrayToString(s -> s.debugPowerInput) + ", OUT " + arrayToString(s -> s.debugPowerOutput)); + left.add( + "- power: IN " + arrayToString(s -> s.debugPowerInput) + ", OUT " + arrayToString(s -> s.debugPowerOutput)); left.add("- power: OFFERED " + arrayToString(s -> s.debugPowerOffered)); } @@ -250,11 +244,13 @@ public void onTick() { unusedPowerQuery -= s2.powerQuery; IPipe neighbour = pipe.getConnectedPipe(face2); long leftover = watts; - if (neighbour != null && neighbour.getFlow() instanceof PipeFlowPower && neighbour.isConnected(face2.getOpposite())) { + if (neighbour != null && neighbour.getFlow() instanceof PipeFlowPower + && neighbour.isConnected(face2.getOpposite())) { PipeFlowPower oFlow = (PipeFlowPower) neighbour.getFlow(); leftover = oFlow.sections.get(face2.getOpposite()).receivePowerInternal(watts); } else { - IMjReceiver reciever = pipe.getHolder().getCapabilityFromPipe(face2, MjAPI.CAP_RECEIVER); + IMjReceiver reciever = + pipe.getHolder().getCapabilityFromPipe(face2, MjAPI.CAP_RECEIVER); if (reciever != null && reciever.canReceive()) { leftover = reciever.receivePower(watts, false); } @@ -349,7 +345,7 @@ public class Section implements IMjReceiver { public final EnumFacing side; public final AverageInt clientDisplayAverage = new AverageInt(10); - public double clientDisplayFlow; + public double clientDisplayFlow, clientPowerAmount; public long displayPower; public EnumFlow displayFlow = EnumFlow.STATIONARY; @@ -360,9 +356,7 @@ public class Section implements IMjReceiver { long powerQuery; long internalPower; - /** - * Debugging fields - */ + /** Debugging fields */ long debugPowerInput, debugPowerOutput, debugPowerOffered; public Section(EnumFacing side) { From 78503e44c281968a9616afe215870f4d8440e247 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Wed, 28 Jun 2017 14:46:17 +0300 Subject: [PATCH 51/89] Fix snapshots loading --- .../builders/BCBuildersEventDist.java | 19 +-- .../container/ContainerElectronicLibrary.java | 4 +- .../builders/gui/GuiElectronicLibrary.java | 94 ++++++----- .../builders/item/ItemSnapshot.java | 15 +- .../builders/snapshot/Blueprint.java | 2 +- .../builders/snapshot/ClientSnapshots.java | 24 +-- .../snapshot/GlobalSavedDataSnapshots.java | 136 +++++++++------- .../snapshot/MessageSnapshotRequest.java | 12 +- .../builders/snapshot/Snapshot.java | 147 +++++++++--------- .../builders/snapshot/Template.java | 2 +- .../builders/tile/TileArchitectTable.java | 33 ++-- .../buildcraft/builders/tile/TileBuilder.java | 2 +- .../builders/tile/TileElectronicLibrary.java | 48 ++++-- .../builders/tile/TileReplacer.java | 16 +- common/buildcraft/lib/misc/StringUtilBC.java | 11 +- .../buildcraft/lib/misc/data/SingleCache.java | 35 +++++ 16 files changed, 344 insertions(+), 256 deletions(-) create mode 100644 common/buildcraft/lib/misc/data/SingleCache.java diff --git a/common/buildcraft/builders/BCBuildersEventDist.java b/common/buildcraft/builders/BCBuildersEventDist.java index 52a1defe40..483248fdd4 100644 --- a/common/buildcraft/builders/BCBuildersEventDist.java +++ b/common/buildcraft/builders/BCBuildersEventDist.java @@ -7,8 +7,6 @@ package buildcraft.builders; import java.lang.ref.WeakReference; -import java.time.Instant; -import java.util.Date; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; @@ -102,18 +100,17 @@ public void onRenderTooltipPostText(RenderTooltipEvent.PostText event) { ItemStack stack = event.getStack(); Header header = BCBuildersItems.snapshot.getHeader(stack); if (header != null) { - snapshot = ClientSnapshots.INSTANCE.getSnapshot(header); + snapshot = ClientSnapshots.INSTANCE.getSnapshot(header.key); } else { ISchematicBlock schematic = ItemSchematicSingle.getSchematicSafe(stack); if (schematic != null) { - // Create a blueprint specific for this given item - Blueprint bpt = new Blueprint(); - bpt.size = new BlockPos(1, 1, 1); - bpt.offset = BlockPos.ORIGIN; - bpt.data = new int[][][] { { { 0 } } }; - bpt.palette.add(schematic); - bpt.header = new Header(bpt.computeHash(), UUID_SINGLE_SCHEMATIC, Date.from(Instant.EPOCH), "_item"); - snapshot = bpt; + Blueprint blueprint = new Blueprint(); + blueprint.size = new BlockPos(1, 1, 1); + blueprint.offset = BlockPos.ORIGIN; + blueprint.data = new int[][][] { { { 0 } } }; + blueprint.palette.add(schematic); + blueprint.computeKey(); + snapshot = blueprint; } } diff --git a/common/buildcraft/builders/container/ContainerElectronicLibrary.java b/common/buildcraft/builders/container/ContainerElectronicLibrary.java index 30eb52d112..47f28e040a 100644 --- a/common/buildcraft/builders/container/ContainerElectronicLibrary.java +++ b/common/buildcraft/builders/container/ContainerElectronicLibrary.java @@ -78,7 +78,7 @@ public boolean canInteractWith(EntityPlayer entityplayer) { return true; } - public void sendSelectedToServer(Snapshot.Header selected) { + public void sendSelectedToServer(Snapshot.Key selected) { sendMessage(ID_SELECTED, buffer -> { buffer.writeBoolean(selected != null); if (selected != null) { @@ -93,7 +93,7 @@ public void readMessage(int id, PacketBufferBC buffer, Side side, MessageContext if (side == Side.SERVER) { if (id == ID_SELECTED) { if (buffer.readBoolean()) { - tile.selected = new Snapshot.Header(buffer); + tile.selected = new Snapshot.Key(buffer); } else { tile.selected = null; } diff --git a/common/buildcraft/builders/gui/GuiElectronicLibrary.java b/common/buildcraft/builders/gui/GuiElectronicLibrary.java index 5dd4207103..fa53d805bb 100644 --- a/common/buildcraft/builders/gui/GuiElectronicLibrary.java +++ b/common/buildcraft/builders/gui/GuiElectronicLibrary.java @@ -5,6 +5,7 @@ package buildcraft.builders.gui; import java.io.IOException; +import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import net.minecraft.util.ResourceLocation; @@ -40,29 +41,27 @@ public GuiElectronicLibrary(ContainerElectronicLibrary container) { public void initGui() { super.initGui(); buttonList.add( - delButton = new GuiBetterButton( - this, - 0, - guiLeft + 174, - guiTop + 109, - 25, - LocaleUtil.localize("gui.del") - ) - .setActive(container.tile.selected != null && getSnapshots().getSnapshotByHeader(container.tile.selected) != null) - .registerListener((button, buttonId, buttonKey) -> { - if (container.tile.selected != null) { - Snapshot snapshot = getSnapshots().getSnapshotByHeader(container.tile.selected); - if (snapshot != null) { - container.sendSelectedToServer(null); - getSnapshots().snapshots.remove(snapshot); - getSnapshots().markDirty(); - if (button instanceof GuiAbstractButton) { - ((GuiAbstractButton) button).setActive(false); - } - } - } - } - ) + delButton = new GuiBetterButton( + this, + 0, + guiLeft + 174, + guiTop + 109, + 25, + LocaleUtil.localize("gui.del") + ) + .setActive(container.tile.selected != null && getSnapshots().getSnapshot(container.tile.selected) != null) + .registerListener((button, buttonId, buttonKey) -> { + if (container.tile.selected != null) { + Snapshot snapshot = getSnapshots().getSnapshot(container.tile.selected); + if (snapshot != null) { + container.sendSelectedToServer(null); + getSnapshots().removeSnapshot(snapshot.key); + if (button instanceof GuiAbstractButton) { + ((GuiAbstractButton) button).setActive(false); + } + } + } + }) ); } @@ -70,21 +69,29 @@ public void initGui() { protected void drawBackgroundLayer(float partialTicks) { ICON_GUI.drawAt(rootElement); drawProgress( - RECT_PROGRESS_DOWN, - ICON_PROGRESS_DOWN, - -container.tile.deltaProgressDown.getDynamic(partialTicks), - 1 + RECT_PROGRESS_DOWN, + ICON_PROGRESS_DOWN, + -container.tile.deltaProgressDown.getDynamic(partialTicks), + 1 ); drawProgress( - RECT_PROGRESS_UP, - ICON_PROGRESS_UP, - container.tile.deltaProgressUp.getDynamic(partialTicks), - 1 + RECT_PROGRESS_UP, + ICON_PROGRESS_UP, + container.tile.deltaProgressUp.getDynamic(partialTicks), + 1 ); - iterateSnapshots((i, x, y, width, height, snapshot) -> - drawString(fontRenderer, snapshot.header.name, x, y, snapshot.header.equals(container.tile.selected) ? 0xffffa0 : 0xe0e0e0) + iterateSnapshots((i, x, y, width, height, key) -> + drawString( + fontRenderer, + key.toString(), + x, + y, + key.equals(container.tile.selected) + ? 0xffffa0 + : 0xe0e0e0 + ) ); - delButton.setActive(container.tile.selected != null && getSnapshots().getSnapshotByHeader(container.tile.selected) != null); + delButton.setActive(container.tile.selected != null && getSnapshots().getSnapshot(container.tile.selected) != null); } private GlobalSavedDataSnapshots getSnapshots() { @@ -92,18 +99,25 @@ private GlobalSavedDataSnapshots getSnapshots() { } private void iterateSnapshots(ISnapshotIterator iterator) { - for (int i = 0; i < getSnapshots().snapshots.size(); i++) { - Snapshot parameter = getSnapshots().snapshots.get(i); - iterator.call(i, rootElement.getX() + 8, rootElement.getY() + 22 + i * 8, 154, 8, parameter); + List list = getSnapshots().getList(); + for (int i = 0; i < list.size(); i++) { + iterator.call( + i, + rootElement.getX() + 8, + rootElement.getY() + 22 + i * 8, + 154, + 8, + list.get(i) + ); } } @Override protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { AtomicBoolean found = new AtomicBoolean(false); - iterateSnapshots((i, x, y, width, height, snapshot) -> { + iterateSnapshots((i, x, y, width, height, key) -> { if (mouseX >= x && mouseX < x + width && mouseY >= y && mouseY < y + height) { - container.sendSelectedToServer(snapshot.header); + container.sendSelectedToServer(key); delButton.setActive(true); found.set(true); } @@ -115,6 +129,6 @@ protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOEx @FunctionalInterface private interface ISnapshotIterator { - void call(int i, int x, int y, int width, int height, Snapshot snapshot); + void call(int i, int x, int y, int width, int height, Snapshot.Key key); } } diff --git a/common/buildcraft/builders/item/ItemSnapshot.java b/common/buildcraft/builders/item/ItemSnapshot.java index 2f0896d684..edb8c1b873 100644 --- a/common/buildcraft/builders/item/ItemSnapshot.java +++ b/common/buildcraft/builders/item/ItemSnapshot.java @@ -6,6 +6,7 @@ package buildcraft.builders.item; +import java.util.Arrays; import java.util.List; import java.util.Locale; @@ -27,7 +28,6 @@ import buildcraft.api.enums.EnumSnapshotType; import buildcraft.lib.item.ItemBC_Neptune; -import buildcraft.lib.misc.HashUtil; import buildcraft.lib.misc.LocaleUtil; import buildcraft.builders.snapshot.Snapshot; @@ -72,8 +72,7 @@ public int getItemStackLimit(ItemStack stack) { @Override public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { - subItems.add(getClean(EnumSnapshotType.TEMPLATE)); - subItems.add(getClean(EnumSnapshotType.BLUEPRINT)); + Arrays.stream(EnumSnapshotType.values()).map(this::getClean).forEach(subItems::add); } @Override @@ -100,14 +99,14 @@ public void addInformation(ItemStack stack, EntityPlayer player, List to tooltip.add(LocaleUtil.localize("item.blueprint.blank")); } else { tooltip.add(header.name); - EntityPlayer author = header.getOwnerPlayer(player.world); - if (author != null) { - tooltip.add(LocaleUtil.localize("item.blueprint.author") + " " + author.getName()); + EntityPlayer owner = header.getOwnerPlayer(player.world); + if (owner != null) { + tooltip.add(LocaleUtil.localize("item.blueprint.author") + " " + owner.getName()); } if (advanced) { - tooltip.add("Hash: " + HashUtil.convertHashToString(header.hash)); + tooltip.add("Hash: " + header.key.toString()); tooltip.add("Date: " + header.created); - tooltip.add("AuthorId: " + header.owner); + tooltip.add("Owner UUID: " + header.owner); } } } diff --git a/common/buildcraft/builders/snapshot/Blueprint.java b/common/buildcraft/builders/snapshot/Blueprint.java index 7a8648d2d6..e997d7ad5f 100644 --- a/common/buildcraft/builders/snapshot/Blueprint.java +++ b/common/buildcraft/builders/snapshot/Blueprint.java @@ -56,7 +56,7 @@ public Blueprint copy() { } } blueprint.entities.addAll(entities); - blueprint.header = header.withHash(blueprint.computeHash()); + blueprint.computeKey(); return blueprint; } diff --git a/common/buildcraft/builders/snapshot/ClientSnapshots.java b/common/buildcraft/builders/snapshot/ClientSnapshots.java index 49cde4cbc8..10d19648bb 100644 --- a/common/buildcraft/builders/snapshot/ClientSnapshots.java +++ b/common/buildcraft/builders/snapshot/ClientSnapshots.java @@ -40,21 +40,21 @@ public enum ClientSnapshots { INSTANCE; private final List snapshots = new ArrayList<>(); - private final List pending = new ArrayList<>(); - private final Map worlds = new HashMap<>(); - private final Map buffers = new HashMap<>(); + private final List pending = new ArrayList<>(); + private final Map worlds = new HashMap<>(); + private final Map buffers = new HashMap<>(); - public Snapshot getSnapshot(Snapshot.Header header) { - Snapshot found = snapshots.stream().filter(snapshot -> snapshot.header.equals(header)).findFirst().orElse(null); - if (found == null && !pending.contains(header)) { - pending.add(header); - MessageManager.sendToServer(new MessageSnapshotRequest(header)); + public Snapshot getSnapshot(Snapshot.Key key) { + Snapshot found = snapshots.stream().filter(snapshot -> snapshot.key.equals(key)).findFirst().orElse(null); + if (found == null && !pending.contains(key)) { + pending.add(key); + MessageManager.sendToServer(new MessageSnapshotRequest(key)); } return found; } public void onSnapshotReceived(Snapshot snapshot) { - pending.remove(snapshot.header); + pending.remove(snapshot.key); snapshots.add(snapshot); } @@ -63,7 +63,7 @@ public void renderSnapshot(Snapshot.Header header, int offsetX, int offsetY, int if (header == null) { return; } - Snapshot snapshot = getSnapshot(header); + Snapshot snapshot = getSnapshot(header.key); if (snapshot == null) { return; } @@ -72,7 +72,7 @@ public void renderSnapshot(Snapshot.Header header, int offsetX, int offsetY, int @SideOnly(Side.CLIENT) public void renderSnapshot(Snapshot snapshot, int offsetX, int offsetY, int sizeX, int sizeY) { - FakeWorld world = worlds.computeIfAbsent(snapshot.header, localHeader -> { + FakeWorld world = worlds.computeIfAbsent(snapshot.key, key -> { FakeWorld localWorld = new FakeWorld(); if (snapshot instanceof Blueprint) { localWorld.uploadBlueprint((Blueprint) snapshot, false); @@ -96,7 +96,7 @@ public void renderSnapshot(Snapshot snapshot, int offsetX, int offsetY, int size } return localWorld; }); - VertexBuffer vertexBuffer = buffers.computeIfAbsent(snapshot.header, localHeader -> { + VertexBuffer vertexBuffer = buffers.computeIfAbsent(snapshot.key, key -> { VertexBuffer localBuffer = new VertexBuffer(1024) { @Override public void reset() { diff --git a/common/buildcraft/builders/snapshot/GlobalSavedDataSnapshots.java b/common/buildcraft/builders/snapshot/GlobalSavedDataSnapshots.java index ec0f72982e..ec66c9d586 100644 --- a/common/buildcraft/builders/snapshot/GlobalSavedDataSnapshots.java +++ b/common/buildcraft/builders/snapshot/GlobalSavedDataSnapshots.java @@ -6,48 +6,58 @@ package buildcraft.builders.snapshot; -import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; -import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.TimeUnit; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; +import com.google.common.collect.ImmutableList; + +import org.apache.commons.lang3.tuple.Pair; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.relauncher.Side; -import buildcraft.lib.misc.HashUtil; -import buildcraft.lib.misc.StringUtilBC; +import buildcraft.lib.misc.data.SingleCache; import buildcraft.lib.nbt.NbtSquisher; public class GlobalSavedDataSnapshots { - public static final String SNAPSHOT_FILE_EXTENSION = ".bcnbt"; - + private static final String SNAPSHOT_FILE_EXTENSION = ".bcnbt"; private static final Map INSTANCES = new EnumMap<>(Side.class); - public final List snapshots = new ArrayList<>(); + private final LoadingCache> snapshotsCache = CacheBuilder.newBuilder() + .expireAfterAccess(10, TimeUnit.MINUTES) + .build(CacheLoader.from(key -> Optional.ofNullable(readSnapshot(key)).map(Pair::getLeft))); + private final SingleCache> listCache = new SingleCache<>( + this::readList, + 1, + TimeUnit.SECONDS + ); private final File snapshotsFile; private GlobalSavedDataSnapshots(Side side) { - snapshotsFile = new File(FMLCommonHandler.instance().getSavesDirectory().getParentFile(), "snapshots-" + side - .name().toLowerCase(Locale.ROOT)); + snapshotsFile = new File( + FMLCommonHandler.instance().getSavesDirectory().getParentFile(), + "snapshots-" + side.name().toLowerCase(Locale.ROOT) + ); if (!snapshotsFile.exists()) { if (!snapshotsFile.mkdirs()) { - throw new RuntimeException("Failed to make the directories required for snapshots! \n\tdir = " - + snapshotsFile); + throw new RuntimeException("Failed to make the directories required for snapshots: " + snapshotsFile); } } else if (!snapshotsFile.isDirectory()) { - throw new IllegalStateException("The snapshots directory was a file! We can't use this!\n\tfile = " - + snapshotsFile); + throw new IllegalStateException("The snapshots directory was not a directory: " + snapshotsFile); } - readSnapshots(); } public static void reInit(Side side) { @@ -65,60 +75,76 @@ public static GlobalSavedDataSnapshots get(World world) { return get(world.isRemote ? Side.CLIENT : Side.SERVER); } - public void exportSnapshot(Snapshot.Header header, File folder) { - Snapshot snapshot = snapshots.stream().filter(s -> header.equals(s.header)).findAny().orElse(null); - if (snapshot != null) { - String fileName = header.name + SNAPSHOT_FILE_EXTENSION; - fileName = StringUtilBC.replaceCharactersForFilename(fileName); - writeSingleSnapshot(snapshot, new File(folder, fileName)); + private Pair readSnapshot(Snapshot.Key key) { + File[] files = snapshotsFile.listFiles(); + if (files != null) { + for (File snapshotFile : files) { + if (snapshotFile.getName().startsWith(key.toString()) && + snapshotFile.getName().endsWith(SNAPSHOT_FILE_EXTENSION)) { + try (FileInputStream fileInputStream = new FileInputStream(snapshotFile)) { + Snapshot snapshot = Snapshot.readFromNBT(NbtSquisher.expand(fileInputStream)); + if (Objects.equals(snapshot.key, key)) { + return Pair.of(snapshot, snapshotFile); + } + } catch (IOException e) { + new IOException("Failed to read the snapshot " + snapshotFile, e).printStackTrace(); + } + } + } } + return null; } - private void writeSnapshots() { - for (Snapshot snapshot : snapshots) { - String hashName = HashUtil.convertHashToString(snapshot.header.hash); - File snapshotFile = new File(snapshotsFile, hashName + SNAPSHOT_FILE_EXTENSION); - writeSingleSnapshot(snapshot, snapshotFile); + private List readList() { + ImmutableList.Builder listBuilder = ImmutableList.builder(); + File[] files = snapshotsFile.listFiles(); + if (files != null) { + for (File snapshotFile : files) { + if (snapshotFile.getName().endsWith(SNAPSHOT_FILE_EXTENSION)) { + try (FileInputStream fileInputStream = new FileInputStream(snapshotFile)) { + Snapshot snapshot = Snapshot.readFromNBT(NbtSquisher.expand(fileInputStream)); + if (snapshotFile.getName().startsWith(snapshot.key.toString())) { + listBuilder.add(snapshot.key); + } + } catch (Exception ignored) { + } + } + } } + return listBuilder.build(); } - private static void writeSingleSnapshot(Snapshot snapshot, File snapshotFile) { + public void addSnapshot(Snapshot snapshot) { + File snapshotFile = new File( + snapshotsFile, + snapshot.key.toString() + SNAPSHOT_FILE_EXTENSION + ); if (!snapshotFile.exists()) { - try (FileOutputStream fos = new FileOutputStream(snapshotFile)) { - NbtSquisher.squishVanilla(Snapshot.writeToNBT(snapshot), fos); - } catch (IOException io) { - IOException ex = new IOException("Failed to write the snapshot file" + snapshotFile, io); - ex.printStackTrace(); + try (FileOutputStream fileOutputStream = new FileOutputStream(snapshotFile)) { + NbtSquisher.squishVanilla(Snapshot.writeToNBT(snapshot), fileOutputStream); + } catch (IOException e) { + new IOException("Failed to write the snapshot file: " + snapshotFile, e).printStackTrace(); } } + snapshotsCache.invalidate(snapshot.key); + listCache.clear(); } - private void readSnapshots() { - File[] files = snapshotsFile.listFiles(); - if (files != null) { - for (File snapshotFile : files) { - try (FileInputStream fis = new FileInputStream(snapshotFile)) { - NBTTagCompound nbt; - if (snapshotFile.getName().endsWith(SNAPSHOT_FILE_EXTENSION)) { - nbt = NbtSquisher.expand(fis); - } else { - // 7.99.4 + back compat - nbt = CompressedStreamTools.read(new DataInputStream(fis)); - } - snapshots.add(Snapshot.readFromNBT(nbt)); - } catch (IOException e) { - IOException ex = new IOException("Failed to read the snapshot " + snapshotFile, e); - ex.printStackTrace(); - } + public void removeSnapshot(Snapshot.Key key) { + Optional.ofNullable(readSnapshot(key)).map(Pair::getRight).ifPresent(snapshotFile -> { + if (!snapshotFile.delete()) { + new IOException("Failed to read the snapshot file: " + snapshotFile).printStackTrace(); } - } + snapshotsCache.invalidate(key); + }); + listCache.clear(); } - public void markDirty() { - writeSnapshots(); + public Snapshot getSnapshot(Snapshot.Key key) { + return snapshotsCache.getUnchecked(key).orElse(null); } - public Snapshot getSnapshotByHeader(Snapshot.Header header) { - return snapshots.stream().filter(snapshot -> snapshot.header.equals(header)).findFirst().orElse(null); + public List getList() { + return listCache.get(); } } diff --git a/common/buildcraft/builders/snapshot/MessageSnapshotRequest.java b/common/buildcraft/builders/snapshot/MessageSnapshotRequest.java index daeeff8654..b1052c38d5 100644 --- a/common/buildcraft/builders/snapshot/MessageSnapshotRequest.java +++ b/common/buildcraft/builders/snapshot/MessageSnapshotRequest.java @@ -15,27 +15,27 @@ import buildcraft.lib.net.PacketBufferBC; public class MessageSnapshotRequest implements IMessage { - private Snapshot.Header header; + private Snapshot.Key key; public MessageSnapshotRequest() { } - public MessageSnapshotRequest(Snapshot.Header header) { - this.header = header; + public MessageSnapshotRequest(Snapshot.Key key) { + this.key = key; } @Override public void toBytes(ByteBuf buf) { - header.writeToByteBuf(new PacketBufferBC(buf)); + key.writeToByteBuf(new PacketBufferBC(buf)); } @Override public void fromBytes(ByteBuf buf) { - header = new Snapshot.Header(new PacketBufferBC(buf)); + key = new Snapshot.Key(new PacketBufferBC(buf)); } public static final IMessageHandler HANDLER = (message, ctx) -> { - Snapshot snapshot = GlobalSavedDataSnapshots.get(Side.SERVER).getSnapshotByHeader(message.header); + Snapshot snapshot = GlobalSavedDataSnapshots.get(Side.SERVER).getSnapshot(message.key); return snapshot != null ? new MessageSnapshotResponse(snapshot) : null; }; } diff --git a/common/buildcraft/builders/snapshot/Snapshot.java b/common/buildcraft/builders/snapshot/Snapshot.java index 00d2b6cef4..aaf8e43842 100644 --- a/common/buildcraft/builders/snapshot/Snapshot.java +++ b/common/buildcraft/builders/snapshot/Snapshot.java @@ -29,18 +29,11 @@ import buildcraft.lib.net.PacketBufferBC; public abstract class Snapshot { - private static final String NBT_HEADER = "header"; - public Header header; + public Key key = new Key(new byte[0]); public BlockPos size; public EnumFacing facing; public BlockPos offset; - public Snapshot(Header header) { - this.header = header; - } - - public Snapshot() {} - public static Snapshot create(EnumSnapshotType type) { switch (type) { case TEMPLATE: @@ -70,9 +63,7 @@ public static Snapshot readFromNBT(NBTTagCompound nbt) throws InvalidInputDataEx public NBTTagCompound serializeNBT() { NBTTagCompound nbt = new NBTTagCompound(); - if (header != null) { - nbt.setTag(NBT_HEADER, header.serializeNBT()); - } + nbt.setTag("key", key.serializeNBT()); nbt.setTag("size", NBTUtil.createPosTag(size)); nbt.setTag("facing", NBTUtilBC.writeEnum(facing)); nbt.setTag("offset", NBTUtil.createPosTag(offset)); @@ -80,11 +71,7 @@ public NBTTagCompound serializeNBT() { } public void deserializeNBT(NBTTagCompound nbt) throws InvalidInputDataException { - Header h = new Header(nbt.getCompoundTag(NBT_HEADER)); - if (h.hash == null || h.hash.length != HashUtil.DIGEST_LENGTH) { - h = h.withHash(computeHash(nbt)); - } - header = h; + key = new Key(nbt.getCompoundTag("key")); size = NBTUtil.getPosFromTag(nbt.getCompoundTag("size")); facing = NBTUtilBC.readEnum(nbt.getTag("facing"), EnumFacing.class); offset = NBTUtil.getPosFromTag(nbt.getCompoundTag("offset")); @@ -92,74 +79,106 @@ public void deserializeNBT(NBTTagCompound nbt) throws InvalidInputDataException abstract public EnumSnapshotType getType(); - public final byte[] computeHash() { - return computeHash(writeToNBT(this)); - } - - private static byte[] computeHash(NBTTagCompound nbt) { - NBTTagCompound nbtHeader = null; - if (nbt.hasKey(NBT_HEADER, Constants.NBT.TAG_COMPOUND)) { - // Don't let the hash depend on the header - nbtHeader = nbt.getCompoundTag(NBT_HEADER); - nbt.removeTag(NBT_HEADER); - } - try { - return HashUtil.computeHash(nbt); - } finally { - // Re-add the header nbt - callers probably expect the header tag to still be there - if (nbtHeader != null) { - nbt.setTag(NBT_HEADER, nbtHeader); - } + public void computeKey() { + NBTTagCompound nbt = writeToNBT(this); + if (nbt.hasKey("key", Constants.NBT.TAG_COMPOUND)) { + nbt.removeTag("key"); } + key = new Key(HashUtil.computeHash(nbt)); } @Override public String toString() { - return getType() + " - " + StringUtilBC.blockPosToShortString(size).replace(',', 'x') + " = " + header; + return "Snapshot{" + + "key=" + key + + ", size=" + StringUtilBC.blockPosAsSizeToString(size) + + ", facing=" + facing + + ", offset=" + offset + + "}"; } - public static class Header { + public static class Key { public final byte[] hash; + + @SuppressWarnings("WeakerAccess") + public Key(byte[] hash) { + this.hash = hash; + } + + @SuppressWarnings("WeakerAccess") + public Key(NBTTagCompound nbt) { + hash = nbt.getByteArray("hash"); + } + + @SuppressWarnings("WeakerAccess") + public Key(PacketBufferBC buffer) { + hash = buffer.readByteArray(); + } + + public NBTTagCompound serializeNBT() { + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setByteArray("hash", hash); + return nbt; + } + + public void writeToByteBuf(PacketBufferBC buffer) { + buffer.writeByteArray(hash); + } + + @Override + public boolean equals(Object o) { + return this == o || !(o == null || getClass() != o.getClass()) && Arrays.equals(hash, ((Key) o).hash); + } + + @Override + public int hashCode() { + return Arrays.hashCode(hash); + } + + @Override + public String toString() { + return HashUtil.convertHashToString(hash); + } + } + + public static class Header { + public final Key key; public final UUID owner; public final Date created; public final String name; - public Header(byte[] hash, UUID owner, Date created, String name) { - this.hash = hash; + public Header(Key key, UUID owner, Date created, String name) { + this.key = key; this.owner = owner; this.created = created; this.name = name; } - public Header withHash(byte[] newHash) { - return new Header(newHash, owner, created, name); - } - public Header(NBTTagCompound nbt) { - hash = nbt.getByteArray("hash"); + key = new Key(nbt.getCompoundTag("key")); owner = nbt.getUniqueId("owner"); created = new Date(nbt.getLong("created")); name = nbt.getString("name"); } + public Header(PacketBufferBC buffer) { + key = new Key(buffer); + owner = buffer.readUniqueId(); + created = new Date(buffer.readLong()); + name = buffer.readString(); + } + public NBTTagCompound serializeNBT() { NBTTagCompound nbt = new NBTTagCompound(); - nbt.setByteArray("hash", hash); + nbt.setTag("key", key.serializeNBT()); nbt.setUniqueId("owner", owner); nbt.setLong("created", created.getTime()); nbt.setString("name", name); return nbt; } - public Header(PacketBufferBC buffer) { - hash = buffer.readByteArray(); - owner = buffer.readUniqueId(); - created = new Date(buffer.readLong()); - name = buffer.readString(); - } - public void writeToByteBuf(PacketBufferBC buffer) { - buffer.writeByteArray(hash); + key.writeToByteBuf(buffer); buffer.writeUniqueId(owner); buffer.writeLong(created.getTime()); buffer.writeString(name); @@ -168,29 +187,5 @@ public void writeToByteBuf(PacketBufferBC buffer) { public EntityPlayer getOwnerPlayer(World world) { return world.getPlayerEntityByUUID(owner); } - - @Override - public String toString() { - return name + " {" + HashUtil.convertHashToString(hash) + "}"; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Header header = (Header) o; - - return Arrays.equals(hash, header.hash); - } - - @Override - public int hashCode() { - return Arrays.hashCode(hash); - } } } diff --git a/common/buildcraft/builders/snapshot/Template.java b/common/buildcraft/builders/snapshot/Template.java index 6b14b78b33..57f755f4ed 100644 --- a/common/buildcraft/builders/snapshot/Template.java +++ b/common/buildcraft/builders/snapshot/Template.java @@ -24,7 +24,6 @@ public class Template extends Snapshot { public Template copy() { Template template = new Template(); - template.header = header; template.size = size; template.facing = facing; template.offset = offset; @@ -36,6 +35,7 @@ public Template copy() { } } } + template.computeKey(); return template; } diff --git a/common/buildcraft/builders/tile/TileArchitectTable.java b/common/buildcraft/builders/tile/TileArchitectTable.java index a40c3a8bab..30a6f5284e 100644 --- a/common/buildcraft/builders/tile/TileArchitectTable.java +++ b/common/buildcraft/builders/tile/TileArchitectTable.java @@ -255,27 +255,32 @@ private void finishScanning() { snapshot.offset = box.min().subtract(pos.offset(facing.getOpposite())); if (snapshot instanceof Template) { ((Template) snapshot).data = templateScannedBlocks; - } else if (snapshot instanceof Blueprint) { - // noinspection ConstantConditions - Blueprint bpt = (Blueprint) snapshot; - bpt.palette.addAll(blueprintScannedPalette); - bpt.data = blueprintScannedData; - bpt.entities.addAll(blueprintScannedEntities); - } else { - } - - snapshot.header = new Header(snapshot.computeHash(), getOwner().getId(), new Date(), name); - GlobalSavedDataSnapshots store = GlobalSavedDataSnapshots.get(world); - store.snapshots.add(snapshot); - store.markDirty(); + if (snapshot instanceof Blueprint) { + ((Blueprint) snapshot).palette.addAll(blueprintScannedPalette); + ((Blueprint) snapshot).data = blueprintScannedData; + ((Blueprint) snapshot).entities.addAll(blueprintScannedEntities); + } + snapshot.computeKey(); + GlobalSavedDataSnapshots.get(world).addSnapshot(snapshot); ItemStack stackIn = invSnapshotIn.getStackInSlot(0); stackIn.setCount(stackIn.getCount() - 1); if (stackIn.getCount() == 0) { stackIn = ItemStack.EMPTY; } invSnapshotIn.setStackInSlot(0, stackIn); - invSnapshotOut.setStackInSlot(0, BCBuildersItems.snapshot.getUsed(snapshotType, snapshot.header)); + invSnapshotOut.setStackInSlot( + 0, + BCBuildersItems.snapshot.getUsed( + snapshotType, + new Header( + snapshot.key, + getOwner().getId(), + new Date(), + name + ) + ) + ); templateScannedBlocks = null; blueprintScannedData = null; blueprintScannedEntities.clear(); diff --git a/common/buildcraft/builders/tile/TileBuilder.java b/common/buildcraft/builders/tile/TileBuilder.java index bcca88f735..bea657e970 100644 --- a/common/buildcraft/builders/tile/TileBuilder.java +++ b/common/buildcraft/builders/tile/TileBuilder.java @@ -142,7 +142,7 @@ protected void onSlotChange(IItemHandlerModifiable itemHandler, if (after.getItem() instanceof ItemSnapshot) { Snapshot.Header header = BCBuildersItems.snapshot.getHeader(after); if (header != null) { - Snapshot newSnapshot = GlobalSavedDataSnapshots.get(world).getSnapshotByHeader(header); + Snapshot newSnapshot = GlobalSavedDataSnapshots.get(world).getSnapshot(header.key); if (newSnapshot != null) { snapshot = newSnapshot; } diff --git a/common/buildcraft/builders/tile/TileElectronicLibrary.java b/common/buildcraft/builders/tile/TileElectronicLibrary.java index 8c5a133466..f0ced2c34f 100644 --- a/common/buildcraft/builders/tile/TileElectronicLibrary.java +++ b/common/buildcraft/builders/tile/TileElectronicLibrary.java @@ -5,6 +5,7 @@ package buildcraft.builders.tile; import java.io.IOException; +import java.util.Date; import javax.annotation.Nonnull; @@ -43,7 +44,7 @@ public class TileElectronicLibrary extends TileBC_Neptune implements ITickable { public final ItemHandlerSimple invDownOut = itemManager.addInvHandler("downOut", 1, EnumAccess.EXTRACT, EnumPipePart.VALUES); public final ItemHandlerSimple invUpIn = itemManager.addInvHandler("upIn", 1, EnumAccess.INSERT, EnumPipePart.VALUES); public final ItemHandlerSimple invUpOut = itemManager.addInvHandler("upOut", 1, EnumAccess.EXTRACT, EnumPipePart.VALUES); - public Snapshot.Header selected = null; + public Snapshot.Key selected = null; public int progressDown = -1; public int progressUp = -1; public final DeltaInt deltaProgressDown = deltaManager.addDelta("progressDown", DeltaManager.EnumNetworkVisibility.GUI_ONLY); @@ -88,7 +89,7 @@ public void update() { } else { progressDown++; } - } else if(progressDown != -1) { + } else if (progressDown != -1) { progressDown = -1; deltaProgressDown.setValue(0); } @@ -105,7 +106,7 @@ public void update() { } else { progressUp++; } - } else if(progressUp != -1) { + } else if (progressUp != -1) { progressUp = -1; deltaProgressUp.setValue(0); } @@ -133,10 +134,14 @@ public void writePayload(int id, PacketBufferBC buffer, Side side) { if (id == NET_DOWN) { Snapshot.Header header = BCBuildersItems.snapshot.getHeader(invDownIn.getStackInSlot(0)); if (header != null) { - Snapshot snapshot = GlobalSavedDataSnapshots.get(world).getSnapshotByHeader(header); + Snapshot snapshot = GlobalSavedDataSnapshots.get(world).getSnapshot(header.key); if (snapshot != null) { buffer.writeBoolean(true); - NbtSquisher.squish(Snapshot.writeToNBT(snapshot), NbtSquishConstants.BUILDCRAFT_V1_COMPRESSED, buffer); + NbtSquisher.squish( + Snapshot.writeToNBT(snapshot), + NbtSquishConstants.BUILDCRAFT_V1_COMPRESSED, + buffer + ); } else { buffer.writeBoolean(false); } @@ -144,16 +149,21 @@ public void writePayload(int id, PacketBufferBC buffer, Side side) { buffer.writeBoolean(false); } } + // noinspection StatementWithEmptyBody if (id == NET_UP) { } } if (side == Side.CLIENT) { if (id == NET_UP) { if (selected != null) { - Snapshot snapshot = GlobalSavedDataSnapshots.get(world).getSnapshotByHeader(selected); + Snapshot snapshot = GlobalSavedDataSnapshots.get(world).getSnapshot(selected); if (snapshot != null) { buffer.writeBoolean(true); - NbtSquisher.squish(Snapshot.writeToNBT(snapshot), NbtSquishConstants.BUILDCRAFT_V1_COMPRESSED, buffer); + NbtSquisher.squish( + Snapshot.writeToNBT(snapshot), + NbtSquishConstants.BUILDCRAFT_V1_COMPRESSED, + buffer + ); } else { buffer.writeBoolean(false); } @@ -167,11 +177,10 @@ public void writePayload(int id, PacketBufferBC buffer, Side side) { @Override public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext ctx) throws IOException { super.readPayload(id, buffer, side, ctx); - GlobalSavedDataSnapshots store = GlobalSavedDataSnapshots.get(world); if (side == Side.CLIENT) { if (id == NET_RENDER_DATA) { if (buffer.readBoolean()) { - selected = new Snapshot.Header(buffer); + selected = new Snapshot.Key(buffer); } else { selected = null; } @@ -179,8 +188,8 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext if (id == NET_DOWN) { if (buffer.readBoolean()) { Snapshot snapshot = Snapshot.readFromNBT(NbtSquisher.expand(buffer)); - store.snapshots.add(snapshot); - store.markDirty(); + snapshot.computeKey(); + GlobalSavedDataSnapshots.get(world).addSnapshot(snapshot); } } if (id == NET_UP) { @@ -193,9 +202,20 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext NBTTagCompound nbt = NbtSquisher.expand(buffer); Snapshot snapshot = Snapshot.readFromNBT(nbt); invUpIn.setStackInSlot(0, StackUtil.EMPTY); - store.snapshots.add(snapshot); - store.markDirty(); - invUpOut.setStackInSlot(0, BCBuildersItems.snapshot.getUsed(snapshot.getType(), snapshot.header)); + snapshot.computeKey(); + GlobalSavedDataSnapshots.get(world).addSnapshot(snapshot); + invUpOut.setStackInSlot( + 0, + BCBuildersItems.snapshot.getUsed( + snapshot.getType(), + new Snapshot.Header( + snapshot.key, + getOwner().getId(), + new Date(), + "From library" + ) + ) + ); } } } diff --git a/common/buildcraft/builders/tile/TileReplacer.java b/common/buildcraft/builders/tile/TileReplacer.java index 9a5d8acbe5..bbcad38715 100644 --- a/common/buildcraft/builders/tile/TileReplacer.java +++ b/common/buildcraft/builders/tile/TileReplacer.java @@ -46,8 +46,7 @@ public void update() { !invSchematicTo.getStackInSlot(0).isEmpty()) { Header header = BCBuildersItems.snapshot.getHeader(invSnapshot.getStackInSlot(0)); if (header != null) { - GlobalSavedDataSnapshots store = GlobalSavedDataSnapshots.get(world); - Snapshot snapshot = store.getSnapshotByHeader(header); + Snapshot snapshot = GlobalSavedDataSnapshots.get(world).getSnapshot(header.key); if (snapshot instanceof Blueprint) { Blueprint blueprint = (Blueprint) snapshot; try { @@ -61,15 +60,18 @@ public void update() { ); Blueprint newBlueprint = blueprint.copy(); newBlueprint.replace(from, to); - Header nHeader = new Header(newBlueprint.computeHash(), getOwner().getId(), new Date(), header.name); - newBlueprint.header = nHeader; - store.snapshots.add(newBlueprint); - store.markDirty(); + newBlueprint.computeKey(); + GlobalSavedDataSnapshots.get(world).addSnapshot(newBlueprint); invSnapshot.setStackInSlot( 0, BCBuildersItems.snapshot.getUsed( EnumSnapshotType.BLUEPRINT, - newBlueprint.header + new Header( + blueprint.key, + getOwner().getId(), + new Date(), + header.name + ) ) ); invSchematicFrom.setStackInSlot(0, ItemStack.EMPTY); diff --git a/common/buildcraft/lib/misc/StringUtilBC.java b/common/buildcraft/lib/misc/StringUtilBC.java index fb716f8758..4beb53eb10 100644 --- a/common/buildcraft/lib/misc/StringUtilBC.java +++ b/common/buildcraft/lib/misc/StringUtilBC.java @@ -72,17 +72,12 @@ private static String formatStringImpl(String string, Function implements Supplier { + private final Supplier delegate; + private final long duration; + private final TimeUnit timeUnit; + private Supplier cache; + + public SingleCache(Supplier delegate, long duration, TimeUnit timeUnit) { + this.delegate = delegate; + this.duration = duration; + this.timeUnit = timeUnit; + clear(); + } + + public void clear() { + cache = Suppliers.memoizeWithExpiration(delegate::get, duration, timeUnit)::get; + } + + @Override + public T get() { + return cache.get(); + } +} From 19d248bc71f9f3e61387d048f285078666f52e12 Mon Sep 17 00:00:00 2001 From: AEnterprise Date: Wed, 28 Jun 2017 17:13:28 +0200 Subject: [PATCH 52/89] make gates emit redstone signals again --- .../transport/block/BlockPipeHolder.java | 45 +++++++++++++++++-- .../transport/tile/TilePipeHolder.java | 22 ++++++++- 2 files changed, 62 insertions(+), 5 deletions(-) diff --git a/common/buildcraft/transport/block/BlockPipeHolder.java b/common/buildcraft/transport/block/BlockPipeHolder.java index 5d53f29366..4dc0457e48 100644 --- a/common/buildcraft/transport/block/BlockPipeHolder.java +++ b/common/buildcraft/transport/block/BlockPipeHolder.java @@ -10,7 +10,6 @@ import java.util.Arrays; import java.util.Comparator; import java.util.List; - import javax.annotation.Nullable; import net.minecraft.block.Block; @@ -66,6 +65,7 @@ import buildcraft.lib.prop.UnlistedNonNullProperty; import buildcraft.transport.BCTransportItems; +import buildcraft.transport.BCTransportPlugs; import buildcraft.transport.item.ItemWire; import buildcraft.transport.pipe.Pipe; import buildcraft.transport.tile.TilePipeHolder; @@ -122,8 +122,8 @@ public boolean isOpaqueCube(IBlockState state) { // Collisions @Override - public void addCollisionBoxToList(IBlockState state, World world, BlockPos pos, AxisAlignedBB entityBox, List< - AxisAlignedBB> collidingBoxes, Entity entityIn, boolean isPistonMoving) { + public void addCollisionBoxToList(IBlockState state, World world, BlockPos pos, AxisAlignedBB entityBox, + List collidingBoxes, Entity entityIn, boolean isPistonMoving) { TilePipeHolder tile = getPipe(world, pos, false); if (tile == null) { addCollisionBoxToList(pos, entityBox, collidingBoxes, FULL_BLOCK_AABB); @@ -725,4 +725,43 @@ public IBlockState getExtendedState(IBlockState state, IBlockAccess world, Block public boolean canRenderInLayer(IBlockState state, BlockRenderLayer layer) { return layer == BlockRenderLayer.CUTOUT_MIPPED || layer == BlockRenderLayer.TRANSLUCENT; } + + @Override + public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, @Nullable EnumFacing side) { + if (side == null) + return false; + TilePipeHolder tile = getPipe(world, pos, false); + if (tile != null) { + PipePluggable pluggable = tile.getPluggable(side.getOpposite()); + return pluggable != null && pluggable.definition == BCTransportPlugs.gate; + } + return false; + } + + @Override + public boolean canProvidePower(IBlockState state) { + return true; + } + + @Override + public int getStrongPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) { + if (side == null) { + return 0; + } + TilePipeHolder tile = getPipe(blockAccess, pos, false); + if (tile != null) { + return tile.getRedstoneOutput(side.getOpposite()); + } + return 0; + } + + @Override + public boolean isBlockNormalCube(IBlockState state) { + return false; + } + + @Override + public int getWeakPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) { + return getStrongPower(blockState, blockAccess, pos, side); + } } diff --git a/common/buildcraft/transport/tile/TilePipeHolder.java b/common/buildcraft/transport/tile/TilePipeHolder.java index bcaf2b650d..2e742b8b7e 100644 --- a/common/buildcraft/transport/tile/TilePipeHolder.java +++ b/common/buildcraft/transport/tile/TilePipeHolder.java @@ -15,7 +15,6 @@ import java.util.List; import java.util.Map; import java.util.Set; - import javax.annotation.Nonnull; import net.minecraft.entity.EntityLivingBase; @@ -72,6 +71,8 @@ public class TilePipeHolder extends TileBC_Neptune implements IPipeHolder, ITick public static final int NET_UPDATE_PLUG_EAST = getReceiverId(PipeMessageReceiver.PLUGGABLE_EAST); public static final int NET_UPDATE_WIRES = getReceiverId(PipeMessageReceiver.WIRES); + private int[] redstoneValues = new int[6]; + static { for (PipeMessageReceiver rec : PipeMessageReceiver.VALUES) { IDS.allocId("UPDATE_" + rec); @@ -126,6 +127,7 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { nbt.setTag("plugs", plugs); } nbt.setTag("wireManager", wireManager.writeToNbt()); + nbt.setIntArray("redstone", redstoneValues); return nbt; } @@ -151,6 +153,9 @@ public void readFromNBT(NBTTagCompound nbt) { pluggables.get(face).readFromNbt(plugs.getCompoundTag(face.getName())); } wireManager.readFromNbt(nbt.getCompoundTag("wireManager")); + if (nbt.hasKey("redstone")) { + redstoneValues = nbt.getIntArray("redstone"); + } } // Misc @@ -470,7 +475,20 @@ public int getRedstoneInput(EnumFacing side) { @Override public boolean setRedstoneOutput(EnumFacing side, int value) { - return false;// TODO! + if (side == null) { + for (EnumFacing facing : EnumFacing.values()) + setRedstoneOutput(facing, value); + } else { + if (redstoneValues[side.ordinal()] == value) + return true; + redstoneValues[side.ordinal()] = value; + world.notifyNeighborsOfStateChange(pos, world.getBlockState(pos).getBlock(), true); + } + return true; + } + + public int getRedstoneOutput(EnumFacing side) { + return redstoneValues[side.ordinal()]; } // Caps From 722dd8e4b72db96d773113f0fe8254e4d6ab1db9 Mon Sep 17 00:00:00 2001 From: AEnterprise Date: Wed, 28 Jun 2017 19:07:09 +0200 Subject: [PATCH 53/89] turn redstone off when action is off --- .../core/statements/ActionRedstoneOutput.java | 2 ++ .../transport/tile/TilePipeHolder.java | 17 ++++++++++++----- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/common/buildcraft/core/statements/ActionRedstoneOutput.java b/common/buildcraft/core/statements/ActionRedstoneOutput.java index cdb07f23cf..7c7a3009d7 100644 --- a/common/buildcraft/core/statements/ActionRedstoneOutput.java +++ b/common/buildcraft/core/statements/ActionRedstoneOutput.java @@ -72,6 +72,8 @@ public void actionActivate(IStatementContainer source, IStatementParameter[] par } } + + protected int getRGSOSlot() { return 0; } diff --git a/common/buildcraft/transport/tile/TilePipeHolder.java b/common/buildcraft/transport/tile/TilePipeHolder.java index 2e742b8b7e..4a3dacad15 100644 --- a/common/buildcraft/transport/tile/TilePipeHolder.java +++ b/common/buildcraft/transport/tile/TilePipeHolder.java @@ -9,6 +9,7 @@ import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; @@ -72,6 +73,7 @@ public class TilePipeHolder extends TileBC_Neptune implements IPipeHolder, ITick public static final int NET_UPDATE_WIRES = getReceiverId(PipeMessageReceiver.WIRES); private int[] redstoneValues = new int[6]; + private int[] oldredstoneValues = new int[]{ -1, -1, -1, -1, -1, -1}; static { for (PipeMessageReceiver rec : PipeMessageReceiver.VALUES) { @@ -216,6 +218,7 @@ public void onLoad() { @Override public void update() { + redstoneValues = new int[6]; // Tick objects if (pipe != null) { pipe.onTick(); @@ -254,6 +257,11 @@ public void update() { wireManager.updateBetweens(false); wireManager.inited = true; } + + if (!Arrays.equals(redstoneValues, oldredstoneValues)) { + world.notifyNeighborsOfStateChange(pos, world.getBlockState(pos).getBlock(), true); + oldredstoneValues = redstoneValues; + } } // Network @@ -381,6 +389,7 @@ public PipePluggable getPluggable(EnumFacing side) { } public PipePluggable replacePluggable(EnumFacing side, PipePluggable with) { + redstoneValues = new int[6]; PluggableHolder holder = pluggables.get(side); PipePluggable old = holder.pluggable; holder.pluggable = with; @@ -476,13 +485,11 @@ public int getRedstoneInput(EnumFacing side) { @Override public boolean setRedstoneOutput(EnumFacing side, int value) { if (side == null) { - for (EnumFacing facing : EnumFacing.values()) - setRedstoneOutput(facing, value); + for (EnumFacing facing : EnumFacing.values()) { + redstoneValues[facing.ordinal()] = value; + } } else { - if (redstoneValues[side.ordinal()] == value) - return true; redstoneValues[side.ordinal()] = value; - world.notifyNeighborsOfStateChange(pos, world.getBlockState(pos).getBlock(), true); } return true; } From 5bb1142e0043d7b6fd50857f3f14d55c3abe45a6 Mon Sep 17 00:00:00 2001 From: AEnterprise Date: Wed, 28 Jun 2017 19:11:23 +0200 Subject: [PATCH 54/89] remove extra blank lines --- common/buildcraft/core/statements/ActionRedstoneOutput.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/common/buildcraft/core/statements/ActionRedstoneOutput.java b/common/buildcraft/core/statements/ActionRedstoneOutput.java index 7c7a3009d7..cdb07f23cf 100644 --- a/common/buildcraft/core/statements/ActionRedstoneOutput.java +++ b/common/buildcraft/core/statements/ActionRedstoneOutput.java @@ -72,8 +72,6 @@ public void actionActivate(IStatementContainer source, IStatementParameter[] par } } - - protected int getRGSOSlot() { return 0; } From ae68bf75fca0cc5b9160638e66f86649042d4e78 Mon Sep 17 00:00:00 2001 From: AEnterprise Date: Wed, 28 Jun 2017 19:12:52 +0200 Subject: [PATCH 55/89] fix oldRedstoneValues naming --- BuildCraft-Localization | 2 +- common/buildcraft/transport/tile/TilePipeHolder.java | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/BuildCraft-Localization b/BuildCraft-Localization index 78e87a0d54..c2c624a8f6 160000 --- a/BuildCraft-Localization +++ b/BuildCraft-Localization @@ -1 +1 @@ -Subproject commit 78e87a0d54a1794ff45a4a4a5699797f784bf90d +Subproject commit c2c624a8f696406ac13276ac648856446f79d75d diff --git a/common/buildcraft/transport/tile/TilePipeHolder.java b/common/buildcraft/transport/tile/TilePipeHolder.java index 4a3dacad15..79099b923a 100644 --- a/common/buildcraft/transport/tile/TilePipeHolder.java +++ b/common/buildcraft/transport/tile/TilePipeHolder.java @@ -73,7 +73,7 @@ public class TilePipeHolder extends TileBC_Neptune implements IPipeHolder, ITick public static final int NET_UPDATE_WIRES = getReceiverId(PipeMessageReceiver.WIRES); private int[] redstoneValues = new int[6]; - private int[] oldredstoneValues = new int[]{ -1, -1, -1, -1, -1, -1}; + private int[] oldRedstoneValues = new int[]{ -1, -1, -1, -1, -1, -1}; static { for (PipeMessageReceiver rec : PipeMessageReceiver.VALUES) { @@ -258,9 +258,9 @@ public void update() { wireManager.inited = true; } - if (!Arrays.equals(redstoneValues, oldredstoneValues)) { + if (!Arrays.equals(redstoneValues, oldRedstoneValues)) { world.notifyNeighborsOfStateChange(pos, world.getBlockState(pos).getBlock(), true); - oldredstoneValues = redstoneValues; + oldRedstoneValues = redstoneValues; } } From b9fc3adbe6529b82c348015ee95dc56903b19ac3 Mon Sep 17 00:00:00 2001 From: AEnterprise Date: Wed, 28 Jun 2017 19:19:08 +0200 Subject: [PATCH 56/89] use enumfacing values cache --- common/buildcraft/transport/tile/TilePipeHolder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/buildcraft/transport/tile/TilePipeHolder.java b/common/buildcraft/transport/tile/TilePipeHolder.java index 79099b923a..acf904df13 100644 --- a/common/buildcraft/transport/tile/TilePipeHolder.java +++ b/common/buildcraft/transport/tile/TilePipeHolder.java @@ -485,7 +485,7 @@ public int getRedstoneInput(EnumFacing side) { @Override public boolean setRedstoneOutput(EnumFacing side, int value) { if (side == null) { - for (EnumFacing facing : EnumFacing.values()) { + for (EnumFacing facing : EnumFacing.VALUES) { redstoneValues[facing.ordinal()] = value; } } else { From d2f2b8da73c1f1f6cc74ac53bf366d458965b1b4 Mon Sep 17 00:00:00 2001 From: AEnterprise Date: Wed, 28 Jun 2017 19:32:47 +0200 Subject: [PATCH 57/89] allow other plugables to connect to redstone --- BuildCraftAPI | 2 +- common/buildcraft/transport/block/BlockPipeHolder.java | 3 +-- common/buildcraft/transport/plug/PluggableGate.java | 6 ++++++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/BuildCraftAPI b/BuildCraftAPI index b396bc79d7..a061e443e9 160000 --- a/BuildCraftAPI +++ b/BuildCraftAPI @@ -1 +1 @@ -Subproject commit b396bc79d72c6f2cc2876cbd9a780407fa536d09 +Subproject commit a061e443e9bd518c9c4f554da51e3d16308b1878 diff --git a/common/buildcraft/transport/block/BlockPipeHolder.java b/common/buildcraft/transport/block/BlockPipeHolder.java index 4dc0457e48..2be90621d7 100644 --- a/common/buildcraft/transport/block/BlockPipeHolder.java +++ b/common/buildcraft/transport/block/BlockPipeHolder.java @@ -65,7 +65,6 @@ import buildcraft.lib.prop.UnlistedNonNullProperty; import buildcraft.transport.BCTransportItems; -import buildcraft.transport.BCTransportPlugs; import buildcraft.transport.item.ItemWire; import buildcraft.transport.pipe.Pipe; import buildcraft.transport.tile.TilePipeHolder; @@ -733,7 +732,7 @@ public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPo TilePipeHolder tile = getPipe(world, pos, false); if (tile != null) { PipePluggable pluggable = tile.getPluggable(side.getOpposite()); - return pluggable != null && pluggable.definition == BCTransportPlugs.gate; + return pluggable != null && pluggable.canConnectToRedstone(side); } return false; } diff --git a/common/buildcraft/transport/plug/PluggableGate.java b/common/buildcraft/transport/plug/PluggableGate.java index 4545ac636a..8918a6505c 100644 --- a/common/buildcraft/transport/plug/PluggableGate.java +++ b/common/buildcraft/transport/plug/PluggableGate.java @@ -9,6 +9,7 @@ import java.io.IOException; import java.util.Arrays; import java.util.stream.Collectors; +import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -226,6 +227,11 @@ public void onTick() { } } + @Override + public boolean canConnectToRedstone(@Nullable EnumFacing to) { + return true; + } + // Model public static void setClientModelVariables(EnumFacing side, GateVariant variant) { From e5154dbb66784a6c629de22bb809add4de4316ef Mon Sep 17 00:00:00 2001 From: AEnterprise Date: Wed, 28 Jun 2017 20:22:52 +0200 Subject: [PATCH 58/89] check for nbt validity --- common/buildcraft/transport/tile/TilePipeHolder.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/common/buildcraft/transport/tile/TilePipeHolder.java b/common/buildcraft/transport/tile/TilePipeHolder.java index acf904df13..8c5273355f 100644 --- a/common/buildcraft/transport/tile/TilePipeHolder.java +++ b/common/buildcraft/transport/tile/TilePipeHolder.java @@ -156,7 +156,11 @@ public void readFromNBT(NBTTagCompound nbt) { } wireManager.readFromNbt(nbt.getCompoundTag("wireManager")); if (nbt.hasKey("redstone")) { - redstoneValues = nbt.getIntArray("redstone"); + + int[] temp = nbt.getIntArray("redstone"); + if (temp.length == 6) { + redstoneValues = temp; + } } } From bec39348443cde4014b8f74b5e19babfdfdb797c Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Thu, 29 Jun 2017 00:40:28 +0100 Subject: [PATCH 59/89] Work on fluid smoothing, and partially fix the issue where activating a tank does the wrong thing if the tank couldn't be interacted with --- BuildCraftAPI | 2 +- .../buildcraft/factory/block/BlockTank.java | 12 +- .../client/render/RenderHeatExchange.java | 13 ++ .../factory/client/render/RenderTank.java | 8 +- .../factory/tile/TileHeatExchangeStart.java | 2 +- common/buildcraft/factory/tile/TileTank.java | 160 ++++++------- .../buildcraft/lib/fluid/FluidSmoother.java | 214 ++++++++++++++++++ common/buildcraft/lib/fluid/Tank.java | 22 +- .../transport/block/BlockPipeHolder.java | 8 +- .../behaviour/PipeBehaviourWoodDiamond.java | 12 +- 10 files changed, 338 insertions(+), 115 deletions(-) create mode 100644 common/buildcraft/factory/client/render/RenderHeatExchange.java create mode 100644 common/buildcraft/lib/fluid/FluidSmoother.java diff --git a/BuildCraftAPI b/BuildCraftAPI index b396bc79d7..a061e443e9 160000 --- a/BuildCraftAPI +++ b/BuildCraftAPI @@ -1 +1 @@ -Subproject commit b396bc79d72c6f2cc2876cbd9a780407fa536d09 +Subproject commit a061e443e9bd518c9c4f554da51e3d16308b1878 diff --git a/common/buildcraft/factory/block/BlockTank.java b/common/buildcraft/factory/block/BlockTank.java index 9c83a36bf7..ef5726f8dc 100644 --- a/common/buildcraft/factory/block/BlockTank.java +++ b/common/buildcraft/factory/block/BlockTank.java @@ -105,20 +105,10 @@ public int getComparatorInputOverride(IBlockState blockState, World world, Block @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { - if (world.isRemote) { - return true; - } - if (player.getHeldItem(hand).isEmpty()) { - return super.onBlockActivated(world, pos, state, player, hand, side, hitX, hitY, hitZ); - } TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileTank) { TileTank tank = (TileTank) tile; - if (FluidUtil.interactWithFluidHandler(player, hand, world, pos, side)) { - tank.sendNetworkUpdate(TileBC_Neptune.NET_RENDER_DATA); - player.inventoryContainer.detectAndSendChanges(); - return true; - } + return tank.onActivate(player, hand); } return false; } diff --git a/common/buildcraft/factory/client/render/RenderHeatExchange.java b/common/buildcraft/factory/client/render/RenderHeatExchange.java new file mode 100644 index 0000000000..9f2590e14f --- /dev/null +++ b/common/buildcraft/factory/client/render/RenderHeatExchange.java @@ -0,0 +1,13 @@ +package buildcraft.factory.client.render; + +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; + +import buildcraft.factory.tile.TileHeatExchangeStart; + +public class RenderHeatExchange extends TileEntitySpecialRenderer { + @Override + public void renderTileEntityAt(TileHeatExchangeStart tile, double x, double y, double z, float partialTicks, + int destroyStage) { + + } +} diff --git a/common/buildcraft/factory/client/render/RenderTank.java b/common/buildcraft/factory/client/render/RenderTank.java index d29084b786..b8c1c52237 100644 --- a/common/buildcraft/factory/client/render/RenderTank.java +++ b/common/buildcraft/factory/client/render/RenderTank.java @@ -27,6 +27,7 @@ import buildcraft.lib.client.render.fluid.FluidRenderer; import buildcraft.lib.client.render.fluid.FluidSpriteType; +import buildcraft.lib.fluid.FluidSmoother.SmoothedFluid; import buildcraft.lib.fluid.Tank; import buildcraft.factory.tile.TileTank; @@ -41,7 +42,7 @@ public RenderTank() {} @Override public void renderTileEntityAt(TileTank tile, double x, double y, double z, float partialTicks, int destroyStage) { - FluidStack forRender = tile.tank.getFluidForRender(); + SmoothedFluid forRender = tile.getFluidForRender(partialTicks); if (forRender == null) { return; } @@ -67,12 +68,13 @@ public void renderTileEntityAt(TileTank tile, double x, double y, double z, floa Vec3d min = connectedDown ? MIN_CONNECTED : MIN; Vec3d max = connectedUp ? MAX_CONNECTED : MAX; - int blocklight = forRender.getFluid().getLuminosity(forRender); + FluidStack fluid = forRender.fluid; + int blocklight = fluid.getFluid().getLuminosity(fluid); int combinedLight = tile.getWorld().getCombinedLight(tile.getPos(), blocklight); FluidRenderer.vertex.lighti(combinedLight); - FluidRenderer.renderFluid(FluidSpriteType.STILL, forRender, tile.getFluidAmountForRender(partialTicks), tile.tank.getCapacity(), min, max, vb, sideRender); + FluidRenderer.renderFluid(FluidSpriteType.STILL, fluid, forRender.amount, tile.tank.getCapacity(), min, max, vb, sideRender); // buffer finish vb.setTranslation(0, 0, 0); diff --git a/common/buildcraft/factory/tile/TileHeatExchangeStart.java b/common/buildcraft/factory/tile/TileHeatExchangeStart.java index a8253ffd35..c5da2953f8 100644 --- a/common/buildcraft/factory/tile/TileHeatExchangeStart.java +++ b/common/buildcraft/factory/tile/TileHeatExchangeStart.java @@ -140,7 +140,7 @@ private void findEnd() { EnumFacing facing = state.getValue(BlockBCBase_Neptune.PROP_FACING); int middles = 0; BlockPos search = getPos(); - for (int i = 0; i < 3; i++) { + for (int i = 0; i <= 3; i++) { search = search.offset(facing); state = getLocalState(search); if (state.getBlock() != BCFactoryBlocks.heatExchangeMiddle) { diff --git a/common/buildcraft/factory/tile/TileTank.java b/common/buildcraft/factory/tile/TileTank.java index c53c8b8199..f1a79e7569 100644 --- a/common/buildcraft/factory/tile/TileTank.java +++ b/common/buildcraft/factory/tile/TileTank.java @@ -12,15 +12,19 @@ import java.util.List; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fluids.capability.FluidTankProperties; +import net.minecraftforge.fluids.capability.IFluidHandlerItem; import net.minecraftforge.fluids.capability.IFluidTankProperties; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; @@ -29,33 +33,25 @@ import buildcraft.api.core.EnumPipePart; import buildcraft.api.core.IFluidFilter; import buildcraft.api.core.IFluidHandlerAdv; -import buildcraft.api.core.SafeTimeTracker; import buildcraft.api.tiles.IDebuggable; +import buildcraft.lib.fluid.FluidSmoother; +import buildcraft.lib.fluid.FluidSmoother.SmoothedFluid; import buildcraft.lib.fluid.Tank; import buildcraft.lib.misc.CapUtil; -import buildcraft.lib.misc.MathUtil; +import buildcraft.lib.misc.FluidUtilBC; import buildcraft.lib.misc.data.IdAllocator; import buildcraft.lib.net.PacketBufferBC; import buildcraft.lib.tile.TileBC_Neptune; -import buildcraft.core.BCCoreConfig; - public class TileTank extends TileBC_Neptune implements ITickable, IDebuggable, IFluidHandlerAdv { public static final IdAllocator IDS = TileBC_Neptune.IDS.makeChild("tank"); public static final int NET_FLUID_DELTA = IDS.allocId("FLUID_DELTA"); - public Tank tank = new Tank("tank", 16000, this); - - private int lastSentAmount = -1; - private boolean lastSentFluid = false; - private final SafeTimeTracker tracker = new SafeTimeTracker(BCCoreConfig.networkUpdateRate, 4); - - // client side + private static boolean isPlayerInteracting = false; - private int target; - private int amount, amountLast; - private long lastMessage, lastMessageMinus1; + public final Tank tank = new Tank("tank", 16000, this); + public final FluidSmoother smoothedTank = new FluidSmoother(w -> createAndSendMessage(NET_FLUID_DELTA, w), tank); public TileTank() { caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, this, EnumPipePart.VALUES); @@ -70,36 +66,11 @@ public IdAllocator getIdAllocator() { @Override public void update() { - if (world.isRemote) { - amountLast = amount; - if (amount != target) { - int delta = target - amount; - long msgDelta = lastMessage - lastMessageMinus1; - msgDelta = MathUtil.clamp((int) msgDelta, 1, 60); - if (Math.abs(delta) < msgDelta) { - amount += delta; - } else { - amount += delta / (int) msgDelta; - } - } - return; - } - - if (lastSentFluid != (tank.getFluid() != null)) { - if (tracker.markTimeIfDelay(world)) { - lastSentFluid = tank.getFluid() != null; - lastSentAmount = tank.getFluidAmount(); - sendNetworkUpdate(NET_RENDER_DATA); - } - } else if (lastSentAmount != tank.getFluidAmount()) { - if (tracker.markTimeIfDelay(world)) { - lastSentAmount = tank.getFluidAmount(); - world.notifyNeighborsOfStateChange(pos, world.getBlockState(pos).getBlock(), false); - sendNetworkUpdate(NET_FLUID_DELTA); - } - } + smoothedTank.tick(getWorld()); } + // TileEntity + @Override public void onPlacedBy(EntityLivingBase placer, ItemStack stack) { super.onPlacedBy(placer, stack); @@ -125,6 +96,30 @@ public void onPlacedBy(EntityLivingBase placer, ItemStack stack) { } } + public boolean onActivate(EntityPlayer player, EnumHand hand) { + ItemStack held = player.getHeldItem(hand); + if (held.isEmpty()) { + return false; + } + boolean replace = !player.capabilities.isCreativeMode; + IFluidHandlerItem flItem = FluidUtil.getFluidHandler(replace ? held : held.copy()); + if (flItem == null) { + return false; + } + if (getWorld().isRemote) { + return true; + } + isPlayerInteracting = true; + if (FluidUtilBC.move(flItem, this) > 0 || FluidUtilBC.move(this, flItem) > 0) { + if (replace) { + player.setHeldItem(hand, flItem.getContainer()); + player.inventoryContainer.detectAndSendChanges(); + } + } + isPlayerInteracting = false; + return true; + } + // NBT @Override @@ -147,9 +142,9 @@ public void writePayload(int id, PacketBufferBC buffer, Side side) { super.writePayload(id, buffer, side); if (side == Side.SERVER) { if (id == NET_RENDER_DATA) { - tank.writeToBuffer(buffer); + writePayload(NET_FLUID_DELTA, buffer, side); } else if (id == NET_FLUID_DELTA) { - buffer.writeInt(tank.getFluidAmount()); + smoothedTank.writeInit(buffer); } } } @@ -159,13 +154,10 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext super.readPayload(id, buffer, side, ctx); if (side == Side.CLIENT) { if (id == NET_RENDER_DATA) { - tank.readFromBuffer(buffer); - target = tank.getClientAmount(); - lastMessageMinus1 = lastMessage = world.getTotalWorldTime(); + readPayload(NET_FLUID_DELTA, buffer, side, ctx); + smoothedTank.resetSmoothing(getWorld()); } else if (id == NET_FLUID_DELTA) { - target = buffer.readInt(); - lastMessageMinus1 = lastMessage; - lastMessage = world.getTotalWorldTime(); + smoothedTank.handleMessage(getWorld(), buffer); } } } @@ -176,43 +168,31 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext @SideOnly(Side.CLIENT) public void getDebugInfo(List left, List right, EnumFacing side) { left.add("fluid = " + tank.getDebugString()); - if (world.isRemote) { - left.add("shown = " + amount + ", target = " + target); - left.add("lastMsg = " + lastMessage + ", lastMsg-1 = " + lastMessageMinus1 + ", diff = " + (lastMessage - lastMessageMinus1)); - } else { - left.add("current = " + tank.getFluidAmount() + " of " + ((tank.getFluid() != null) ? "Something" : "Nothing")); - left.add("lastSent = " + lastSentAmount + " of " + (lastSentFluid ? "Something" : "Nothing")); - } + smoothedTank.getDebugInfo(left, right, side); } // Rendering @SideOnly(Side.CLIENT) - public double getFluidAmountForRender(float partialTicks) { - float interpAmount = amountLast * (1 - partialTicks) + this.amount * partialTicks; - Tank other = getTank(pos.up()); - if (other != null && !other.isEmpty()) { - interpAmount = tank.getCapacity(); - } - return interpAmount; + public SmoothedFluid getFluidForRender(float partialTicks) { + return smoothedTank.getFluidForRender(partialTicks); } // Tank helper methods - private Tank getTank(BlockPos at) { + private TileTank getTank(BlockPos at) { TileEntity tile = world.getTileEntity(at); if (tile instanceof TileTank) { - TileTank tileTank = (TileTank) tile; - return tileTank.tank; + return (TileTank) tile; } return null; } - private List getTanks() { - List tanks = new ArrayList<>(); + private List getTanks() { + List tanks = new ArrayList<>(); BlockPos currentPos = pos; while (true) { - Tank tankUp = getTank(currentPos); + TileTank tankUp = getTank(currentPos); if (tankUp != null) { tanks.add(tankUp); } else { @@ -222,7 +202,7 @@ private List getTanks() { } currentPos = pos.down(); while (true) { - Tank tankBelow = getTank(currentPos); + TileTank tankBelow = getTank(currentPos); if (tankBelow != null) { tanks.add(0, tankBelow); } else { @@ -237,23 +217,23 @@ private List getTanks() { @Override public IFluidTankProperties[] getTankProperties() { - List tanks = getTanks(); - Tank bottom = tanks.get(0); - FluidStack total = bottom.getFluid(); + List tanks = getTanks(); + TileTank bottom = tanks.get(0); + FluidStack total = bottom.tank.getFluid(); int capacity = 0; if (total == null) { - for (Tank t : tanks) { - capacity += t.getCapacity(); + for (TileTank t : tanks) { + capacity += t.tank.getCapacity(); } } else { total = total.copy(); total.amount = 0; - for (Tank t : tanks) { - FluidStack other = t.getFluid(); + for (TileTank t : tanks) { + FluidStack other = t.tank.getFluid(); if (other != null) { total.amount += other.amount; } - capacity += t.getCapacity(); + capacity += t.tank.getCapacity(); } } return new IFluidTankProperties[] { new FluidTankProperties(total, capacity) }; @@ -265,16 +245,19 @@ public int fill(FluidStack resource, boolean doFill) { return 0; } int filled = 0; - List tanks = getTanks(); - for (Tank t : tanks) { - FluidStack current = t.getFluid(); + List tanks = getTanks(); + for (TileTank t : tanks) { + FluidStack current = t.tank.getFluid(); if (current != null && !current.isFluidEqual(resource)) { return 0; } } - for (Tank t : tanks) { - int tankFilled = t.fill(resource, doFill); + for (TileTank t : tanks) { + int tankFilled = t.tank.fill(resource, doFill); if (tankFilled > 0) { + if (isPlayerInteracting) { + t.sendNetworkUpdate(NET_RENDER_DATA); + } resource.amount -= tankFilled; filled += tankFilled; if (resource.amount == 0) { @@ -305,17 +288,20 @@ public FluidStack drain(IFluidFilter filter, int maxDrain, boolean doDrain) { if (maxDrain <= 0) { return null; } - List tanks = getTanks(); + List tanks = getTanks(); // The returned list is ordered bottom -> top, but we want top -> bottom Collections.reverse(tanks); FluidStack total = null; - for (Tank t : tanks) { + for (TileTank t : tanks) { int realMax = maxDrain - (total == null ? 0 : total.amount); if (realMax <= 0) { break; } - FluidStack drained = t.drain(filter, realMax, doDrain); + FluidStack drained = t.tank.drain(filter, realMax, doDrain); if (drained == null) continue; + if (isPlayerInteracting) { + t.sendNetworkUpdate(NET_RENDER_DATA); + } if (total == null) { total = drained.copy(); total.amount = 0; diff --git a/common/buildcraft/lib/fluid/FluidSmoother.java b/common/buildcraft/lib/fluid/FluidSmoother.java new file mode 100644 index 0000000000..afecaaaf78 --- /dev/null +++ b/common/buildcraft/lib/fluid/FluidSmoother.java @@ -0,0 +1,214 @@ +package buildcraft.lib.fluid; + +import java.util.List; + +import net.minecraft.util.EnumFacing; +import net.minecraft.world.World; + +import net.minecraftforge.fluids.FluidStack; + +import buildcraft.api.core.SafeTimeTracker; +import buildcraft.api.tiles.IDebuggable; + +import buildcraft.lib.misc.MathUtil; +import buildcraft.lib.net.IPayloadWriter; +import buildcraft.lib.net.PacketBufferBC; +import buildcraft.lib.net.cache.BuildCraftObjectCaches; +import buildcraft.lib.net.cache.NetworkedFluidStackCache; + +import buildcraft.core.BCCoreConfig; + +public class FluidSmoother implements IDebuggable { + final IFluidDataSender sender; + final Tank tank; + _Side data; + + public FluidSmoother(IFluidDataSender sender, Tank tank) { + this.sender = sender; + this.tank = tank; + } + + public void tick(World world) { + if (data == null) { + if (world == null) { + return; + } + data = world.isRemote ? new _Client() : new _Server(); + } + data.tick(world); + } + + public void handleMessage(World world, PacketBufferBC buffer) { + if (data == null) { + data = new _Client(); + } + if (data instanceof _Client) { + ((_Client) data).handleMessage(world, buffer); + } else { + throw new IllegalStateException("You can only call this on the client!"); + } + } + + public void writeInit(PacketBufferBC buffer) { + if (data == null) { + data = new _Server(); + } + if (data instanceof _Server) { + ((_Server) data).writeMessage(buffer); + } else { + throw new IllegalStateException("You can only call this on the client!"); + } + } + + public void resetSmoothing(World world) { + if (data == null && world.isRemote) { + data = new _Client(); + } + if (data instanceof _Client) { + _Client client = (_Client) data; + client.resetSmoothing(world); + } else { + throw new IllegalStateException("You can only call this on the client!"); + } + } + + public FluidStack getFluidForRender() { + if (data instanceof _Client) { + _Client client = (_Client) data; + FluidStack fluid = client.link.get(); + if (fluid == null) { + return null; + } + return new FluidStack(fluid, client.amount); + } + return null; + } + + public SmoothedFluid getFluidForRender(double partialTicks) { + if (data instanceof _Client) { + _Client client = (_Client) data; + if (client.link == null) { + return null; + } + FluidStack fluid = client.link.get(); + if (fluid == null) { + return null; + } + double amount = client.amountLast * (1 - partialTicks) + client.amount * partialTicks; + return new SmoothedFluid(fluid, amount); + } + return null; + } + + @Override + public void getDebugInfo(List left, List right, EnumFacing side) { + if (data != null) { + data.getDebugInfo(left, right, side); + } + } + + @FunctionalInterface + public interface IFluidDataSender { + void writePacket(IPayloadWriter writer); + } + + public static class SmoothedFluid { + public final FluidStack fluid; + public final double amount; + + public SmoothedFluid(FluidStack fluid, double amount) { + this.fluid = fluid; + this.amount = amount; + } + } + + abstract class _Side implements IDebuggable { + abstract void tick(World world); + } + + final class _Server extends _Side { + private int sentAmount = -1; + private boolean sentHasFluid = false; + private final SafeTimeTracker tracker = new SafeTimeTracker(BCCoreConfig.networkUpdateRate, 4); + + @Override + void tick(World world) { + FluidStack fluid = tank.getFluid(); + boolean hasFluid = fluid != null; + if ((tank.getFluidAmount() != sentAmount || hasFluid != sentHasFluid)) { + if (tracker.markTimeIfDelay(world)) { + sender.writePacket(this::writeMessage); + } + } + } + + void writeMessage(PacketBufferBC buffer) { + FluidStack fluid = tank.getFluid(); + boolean hasFluid = fluid != null; + + sentAmount = tank.getFluidAmount(); + sentHasFluid = hasFluid; + + final int amount = sentAmount; + final int flId = hasFluid ? BuildCraftObjectCaches.CACHE_FLUIDS.server().store(fluid) : -1; + + buffer.writeInt(amount); + if (hasFluid) { + buffer.writeBoolean(true); + buffer.writeInt(flId); + } else { + buffer.writeBoolean(false); + } + } + + @Override + public void getDebugInfo(List left, List right, EnumFacing side) { + String contents = (tank.getFluid() != null) ? "Something" : "Nothing"; + left.add("current = " + tank.getFluidAmount() + " of " + contents); + left.add("lastSent = " + sentAmount + " of " + (sentHasFluid ? "Something" : "Nothing")); + } + } + + final class _Client extends _Side { + private int target; + int amount, amountLast; + long lastMessage, lastMessageMinus1; + NetworkedFluidStackCache.Link link; + + @Override + void tick(World world) { + amountLast = amount; + if (amount != target) { + int delta = target - amount; + long msgDelta = lastMessage - lastMessageMinus1; + msgDelta = MathUtil.clamp((int) msgDelta, 1, 60); + if (Math.abs(delta) < msgDelta) { + amount += delta; + } else { + amount += delta / (int) msgDelta; + } + } + } + + void handleMessage(World world, PacketBufferBC buffer) { + target = buffer.readInt(); + if (buffer.readBoolean()) { + link = BuildCraftObjectCaches.CACHE_FLUIDS.client().retrieve(buffer.readInt()); + } + lastMessageMinus1 = lastMessage; + lastMessage = world.getTotalWorldTime(); + } + + void resetSmoothing(World world) { + lastMessageMinus1 = lastMessage = world.getTotalWorldTime(); + lastMessageMinus1 -= 1; + } + + @Override + public void getDebugInfo(List left, List right, EnumFacing side) { + left.add("shown = " + amount + ", target = " + target); + left.add("lastMsg = " + lastMessage + ", lastMsg-1 = " + lastMessageMinus1 + ", diff = " + + (lastMessage - lastMessageMinus1)); + } + } +} diff --git a/common/buildcraft/lib/fluid/Tank.java b/common/buildcraft/lib/fluid/Tank.java index 6a08d2daa8..757b1684d2 100644 --- a/common/buildcraft/lib/fluid/Tank.java +++ b/common/buildcraft/lib/fluid/Tank.java @@ -1,7 +1,9 @@ -/* Copyright (c) 2016 SpaceToad and the BuildCraft team +/* + * Copyright (c) 2016 SpaceToad and the BuildCraft team * * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not - * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ package buildcraft.lib.fluid; import java.util.HashMap; @@ -59,8 +61,8 @@ public void refresh() { @Nonnull private final Predicate filter; - private NetworkedFluidStackCache.Link clientFluid = null; - private int clientAmount = 0; + NetworkedFluidStackCache.Link clientFluid = null; + int clientAmount = 0; public ElementHelpInfo helpInfo; @@ -80,7 +82,8 @@ public Tank(@Nonnull String name, int capacity, TileEntity tile, @Nullable Predi this.name = name; this.tile = tile; this.filter = filter == null ? ((f) -> true) : filter; - helpInfo = new ElementHelpInfo("buildcraft.help.tank.title." + name, 0xFF_00_00_00 | name.hashCode(), DEFAULT_HELP_KEY); + helpInfo = new ElementHelpInfo("buildcraft.help.tank.title." + name, 0xFF_00_00_00 | name.hashCode(), + DEFAULT_HELP_KEY); } @Nonnull @@ -270,7 +273,8 @@ public void onGuiClicked(ContainerBC_Neptune container) { hasFilled = true; int reallyAccepted = fill(result.fluidStack, true); if (reallyAccepted != accepted) { - throw new IllegalStateException("We seem to be buggy! (accepted = " + accepted + ", reallyAccepted = " + reallyAccepted + ")"); + throw new IllegalStateException("We seem to be buggy! (accepted = " + accepted + + ", reallyAccepted = " + reallyAccepted + ")"); } held.shrink(1); if (isSurvival) { @@ -295,7 +299,8 @@ public void onGuiClicked(ContainerBC_Neptune container) { if (hasFilled) { FluidStack fl = getFluid(); if (fl != null) { - SoundEvent sound = fl.getFluid().getEmptySound(container.player.world, container.player.getPosition()); + SoundEvent sound = + fl.getFluid().getEmptySound(container.player.world, container.player.getPosition()); container.player.world.playSound(null, player.getPosition(), sound, SoundCategory.BLOCKS, 1, 1); } return; @@ -318,7 +323,8 @@ public void onGuiClicked(ContainerBC_Neptune container) { player.inventory.setItemStack(filledContainer); ((EntityPlayerMP) player).updateHeldItem(); } - SoundEvent sound = reallyDrained.getFluid().getFillSound(container.player.world, container.player.getPosition()); + SoundEvent sound = + reallyDrained.getFluid().getFillSound(container.player.world, container.player.getPosition()); container.player.world.playSound(null, player.getPosition(), sound, SoundCategory.BLOCKS, 1, 1); } } diff --git a/common/buildcraft/transport/block/BlockPipeHolder.java b/common/buildcraft/transport/block/BlockPipeHolder.java index 5d53f29366..3aad5559cd 100644 --- a/common/buildcraft/transport/block/BlockPipeHolder.java +++ b/common/buildcraft/transport/block/BlockPipeHolder.java @@ -481,10 +481,14 @@ public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, En } } } - if (tile.getPipe().behaviour.onPipeActivate(player, trace, hitX, hitY, hitZ, part)) { + Pipe pipe = tile.getPipe(); + if (pipe == null) { + return false; + } + if (pipe.behaviour.onPipeActivate(player, trace, hitX, hitY, hitZ, part)) { return true; } - if (tile.getPipe().flow.onFlowActivate(player, trace, hitX, hitY, hitZ, part)) { + if (pipe.flow.onFlowActivate(player, trace, hitX, hitY, hitZ, part)) { return true; } return false; diff --git a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourWoodDiamond.java b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourWoodDiamond.java index 6113922986..2822f42084 100644 --- a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourWoodDiamond.java +++ b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourWoodDiamond.java @@ -107,7 +107,8 @@ public void writePayload(PacketBuffer buffer, Side side) { } @Override - public boolean onPipeActivate(EntityPlayer player, RayTraceResult trace, float hitX, float hitY, float hitZ, EnumPipePart part) { + public boolean onPipeActivate(EntityPlayer player, RayTraceResult trace, float hitX, float hitY, float hitZ, + EnumPipePart part) { if (EntityUtil.getWrenchHand(player) != null) { return super.onPipeActivate(player, trace, hitX, hitY, hitZ, part); } @@ -138,9 +139,13 @@ private IStackFilter getStackFilter() { switch (filterMode) { default: case WHITE_LIST: + if (filters.extract(s -> true, 1, 1, true).isEmpty()) { + return s -> true; + } return new DelegatingItemHandlerFilter(StackUtil::isMatchingItemOrList, filters); case BLACK_LIST: - return new InvertedStackFilter(new DelegatingItemHandlerFilter(StackUtil::isMatchingItemOrList, filters)); + return new InvertedStackFilter( + new DelegatingItemHandlerFilter(StackUtil::isMatchingItemOrList, filters)); case ROUND_ROBIN: return (comparison) -> { ItemStack filter = filters.getStackInSlot(currentFilter); @@ -170,6 +175,9 @@ protected FluidStack extractFluid(IFlowFluid flow, EnumFacing dir, int millibuck switch (filterMode) { default: case WHITE_LIST: + if (filters.extract(s -> true, 1, 1, true).isEmpty()) { + return flow.tryExtractFluid(millibuckets, dir, null); + } // Firstly try the advanced version - if that fails we will need to try the basic version ActionResult result = flow.tryExtractFluidAdv(millibuckets, dir, new ArrayFluidFilter(filters.stacks)); FluidStack extracted = result.getResult(); From d758e9fb21aeabd1ccb0eb28b6d27be888c1e039 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Thu, 29 Jun 2017 13:52:49 +0300 Subject: [PATCH 60/89] Fix flood gate --- BuildCraft-Localization | 2 +- .../builders/addon/AddonFillingPlanner.java | 11 +- .../builders/snapshot/Blueprint.java | 8 +- .../snapshot/SchematicBlockDefault.java | 11 +- .../buildcraft/builders/tile/TileBuilder.java | 5 +- .../buildcraft/core/marker/volume/Lock.java | 4 +- .../factory/block/BlockFloodGate.java | 23 +- .../client/render/AdvDebuggerFloodGate.java | 65 ---- .../factory/tile/TileFloodGate.java | 314 ++++++++++++++++++ common/buildcraft/factory/tile/TilePump.java | 6 +- common/buildcraft/lib/misc/NBTUtilBC.java | 40 ++- common/buildcraft/robotics/zone/ZonePlan.java | 4 +- .../factory/tile/TileFloodGate.java | 273 --------------- 13 files changed, 382 insertions(+), 384 deletions(-) delete mode 100644 common/buildcraft/factory/client/render/AdvDebuggerFloodGate.java create mode 100644 common/buildcraft/factory/tile/TileFloodGate.java delete mode 100644 common_old_license/buildcraft/factory/tile/TileFloodGate.java diff --git a/BuildCraft-Localization b/BuildCraft-Localization index c2c624a8f6..78e87a0d54 160000 --- a/BuildCraft-Localization +++ b/BuildCraft-Localization @@ -1 +1 @@ -Subproject commit c2c624a8f696406ac13276ac648856446f79d75d +Subproject commit 78e87a0d54a1794ff45a4a4a5699797f784bf90d diff --git a/common/buildcraft/builders/addon/AddonFillingPlanner.java b/common/buildcraft/builders/addon/AddonFillingPlanner.java index 6d007cc05d..5ffb2911f9 100644 --- a/common/buildcraft/builders/addon/AddonFillingPlanner.java +++ b/common/buildcraft/builders/addon/AddonFillingPlanner.java @@ -17,8 +17,6 @@ import net.minecraft.util.Rotation; import net.minecraft.util.math.BlockPos; -import net.minecraftforge.common.util.Constants; - import buildcraft.lib.misc.NBTUtilBC; import buildcraft.builders.BCBuildersGuis; @@ -97,14 +95,7 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { @Override public void readFromNBT(NBTTagCompound nbt) { - NBTUtilBC.readCompoundList( - nbt.getTagList( - "parameters", - Constants.NBT.TAG_COMPOUND - ) - ) - .map(IParameter::readFromNBT) - .forEach(parameters::add); + NBTUtilBC.readCompoundList(nbt.getTag("parameters")).map(IParameter::readFromNBT).forEach(parameters::add); updateBuildingInfo(); } diff --git a/common/buildcraft/builders/snapshot/Blueprint.java b/common/buildcraft/builders/snapshot/Blueprint.java index e997d7ad5f..079ace51bb 100644 --- a/common/buildcraft/builders/snapshot/Blueprint.java +++ b/common/buildcraft/builders/snapshot/Blueprint.java @@ -86,8 +86,8 @@ public NBTTagCompound serializeNBT() { public void deserializeNBT(NBTTagCompound nbt) throws InvalidInputDataException { super.deserializeNBT(nbt); palette.clear(); - for (NBTTagCompound schematicBlockTag : NBTUtilBC.readCompoundList(nbt.getTagList("palette", - Constants.NBT.TAG_COMPOUND)).collect(Collectors.toList())) { + for (NBTTagCompound schematicBlockTag : + NBTUtilBC.readCompoundList(nbt.getTag("palette")).collect(Collectors.toList())) { // TODO: Allow reading blueprints partially - invalid elements should be replaced with air // (Although this needs to add a "pass-through" ISchematicBlock that will store the // invalid NBTTagCompound and show up in the tooltip as an error, so that we can migrate @@ -116,8 +116,8 @@ public void deserializeNBT(NBTTagCompound nbt) throws InvalidInputDataException } } } - for (NBTTagCompound schematicEntityTag : NBTUtilBC.readCompoundList(nbt.getTagList("entities", - Constants.NBT.TAG_COMPOUND)).collect(Collectors.toList())) { + for (NBTTagCompound schematicEntityTag : + NBTUtilBC.readCompoundList(nbt.getTag("entities")).collect(Collectors.toList())) { entities.add(SchematicEntityManager.readFromNBT(schematicEntityTag)); } } diff --git a/common/buildcraft/builders/snapshot/SchematicBlockDefault.java b/common/buildcraft/builders/snapshot/SchematicBlockDefault.java index 3344ab252f..a94ce4a9bc 100644 --- a/common/buildcraft/builders/snapshot/SchematicBlockDefault.java +++ b/common/buildcraft/builders/snapshot/SchematicBlockDefault.java @@ -37,7 +37,6 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import net.minecraftforge.common.util.Constants; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.items.CapabilityItemHandler; @@ -445,11 +444,11 @@ public NBTTagCompound serializeNBT() { @Override public void deserializeNBT(NBTTagCompound nbt) throws InvalidInputDataException { - NBTUtilBC.readCompoundList(nbt.getTagList("requiredBlockOffsets", Constants.NBT.TAG_COMPOUND)) + NBTUtilBC.readCompoundList(nbt.getTag("requiredBlockOffsets")) .map(NBTUtil::getPosFromTag) .forEach(requiredBlockOffsets::add); blockState = NBTUtil.readBlockState(nbt.getCompoundTag("blockState")); - NBTUtilBC.readStringList(nbt.getTagList("ignoredProperties", Constants.NBT.TAG_STRING)) + NBTUtilBC.readStringList(nbt.getTag("ignoredProperties")) .map(propertyName -> blockState.getPropertyKeys().stream() .filter(property -> property.getName().equals(propertyName)) @@ -460,13 +459,13 @@ public void deserializeNBT(NBTTagCompound nbt) throws InvalidInputDataException if (nbt.hasKey("tileNbt")) { tileNbt = nbt.getCompoundTag("tileNbt"); } - NBTUtilBC.readStringList(nbt.getTagList("ignoredTags", Constants.NBT.TAG_STRING)).forEach(ignoredTags::add); + NBTUtilBC.readStringList(nbt.getTag("ignoredTags")).forEach(ignoredTags::add); tileRotation = NBTUtilBC.readEnum(nbt.getTag("tileRotation"), Rotation.class); placeBlock = Block.REGISTRY.getObject(new ResourceLocation(nbt.getString("placeBlock"))); - NBTUtilBC.readCompoundList(nbt.getTagList("updateBlockOffsets", Constants.NBT.TAG_COMPOUND)) + NBTUtilBC.readCompoundList(nbt.getTag("updateBlockOffsets")) .map(NBTUtil::getPosFromTag) .forEach(updateBlockOffsets::add); - NBTUtilBC.readStringList(nbt.getTagList("canBeReplacedWithBlocks", Constants.NBT.TAG_STRING)) + NBTUtilBC.readStringList(nbt.getTag("canBeReplacedWithBlocks")) .map(ResourceLocation::new) .map(Block.REGISTRY::getObject) .forEach(canBeReplacedWithBlocks::add); diff --git a/common/buildcraft/builders/tile/TileBuilder.java b/common/buildcraft/builders/tile/TileBuilder.java index bea657e970..2d1b3c59a1 100644 --- a/common/buildcraft/builders/tile/TileBuilder.java +++ b/common/buildcraft/builders/tile/TileBuilder.java @@ -29,7 +29,6 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import net.minecraftforge.common.util.Constants; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; @@ -348,11 +347,11 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); if (nbt.hasKey("path")) { - path = NBTUtilBC.readCompoundList(nbt.getTagList("path", Constants.NBT.TAG_COMPOUND)) + path = NBTUtilBC.readCompoundList(nbt.getTag("path")) .map(NBTUtil::getPosFromTag) .collect(Collectors.toList()); } - basePoses = NBTUtilBC.readCompoundList(nbt.getTagList("basePoses", Constants.NBT.TAG_COMPOUND)) + basePoses = NBTUtilBC.readCompoundList(nbt.getTag("basePoses")) .map(NBTUtil::getPosFromTag) .collect(Collectors.toList()); canExcavate = nbt.getBoolean("canExcavate"); diff --git a/common/buildcraft/core/marker/volume/Lock.java b/common/buildcraft/core/marker/volume/Lock.java index 4dc10ecd62..c19fa200ba 100644 --- a/common/buildcraft/core/marker/volume/Lock.java +++ b/common/buildcraft/core/marker/volume/Lock.java @@ -19,8 +19,6 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import net.minecraftforge.common.util.Constants; - import buildcraft.lib.client.render.laser.LaserData_BC8; import buildcraft.lib.misc.MessageUtil; import buildcraft.lib.misc.NBTUtilBC; @@ -62,7 +60,7 @@ public void readFromNBT(NBTTagCompound nbt) { throw new RuntimeException(e); } cause.readFromNBT(causeTag.getCompoundTag("data")); - NBTUtilBC.readCompoundList(nbt.getTagList("targets", Constants.NBT.TAG_COMPOUND)).map(targetTag -> { + NBTUtilBC.readCompoundList(nbt.getTag("targets")).map(targetTag -> { Target target; try { target = NBTUtilBC.readEnum(targetTag.getTag("type"), Target.EnumTarget.class).clazz.newInstance(); diff --git a/common/buildcraft/factory/block/BlockFloodGate.java b/common/buildcraft/factory/block/BlockFloodGate.java index 784fee6a57..1d776a0e4d 100644 --- a/common/buildcraft/factory/block/BlockFloodGate.java +++ b/common/buildcraft/factory/block/BlockFloodGate.java @@ -27,6 +27,7 @@ import buildcraft.lib.block.BlockBCTile_Neptune; import buildcraft.lib.misc.BlockUtil; +import buildcraft.lib.tile.TileBC_Neptune; import buildcraft.factory.tile.TileFloodGate; @@ -49,7 +50,7 @@ protected void addProperties(List> properties) { } @Override - public TileEntity createNewTileEntity(World worldIn, int meta) { + public TileEntity createNewTileEntity(World world, int meta) { return new TileFloodGate(); } @@ -57,9 +58,8 @@ public TileEntity createNewTileEntity(World worldIn, int meta) { public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) { TileEntity tile = BlockUtil.getTileEntityForGetActualState(world, pos); if (tile instanceof TileFloodGate) { - TileFloodGate gate = (TileFloodGate) tile; for (EnumFacing side : CONNECTED_MAP.keySet()) { - state = state.withProperty(CONNECTED_MAP.get(side), !gate.isSideBlocked(side)); + state = state.withProperty(CONNECTED_MAP.get(side), ((TileFloodGate) tile).openSides.get(side)); } } return state; @@ -69,12 +69,17 @@ public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPo public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { ItemStack heldItem = player.getHeldItem(hand); if (heldItem.getItem() instanceof IToolWrench) { - TileEntity tile = world.getTileEntity(pos); - if (tile instanceof TileFloodGate) { - TileFloodGate gate = (TileFloodGate) tile; - if (CONNECTED_MAP.containsKey(side)) { - gate.setSideBlocked(side, !gate.isSideBlocked(side)); - return true; + if (!world.isRemote) { + if (side != EnumFacing.UP) { + TileEntity tile = world.getTileEntity(pos); + if (tile instanceof TileFloodGate) { + if (CONNECTED_MAP.containsKey(side)) { + ((TileFloodGate) tile).openSides.put(side, !((TileFloodGate) tile).openSides.get(side)); + ((TileFloodGate) tile).queue.clear(); + ((TileFloodGate) tile).sendNetworkUpdate(TileBC_Neptune.NET_RENDER_DATA); + return true; + } + } } } return false; diff --git a/common/buildcraft/factory/client/render/AdvDebuggerFloodGate.java b/common/buildcraft/factory/client/render/AdvDebuggerFloodGate.java deleted file mode 100644 index 1f0540c577..0000000000 --- a/common/buildcraft/factory/client/render/AdvDebuggerFloodGate.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2017 SpaceToad and the BuildCraft team - * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not - * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ - */ - -package buildcraft.factory.client.render; - -import java.util.Deque; -import java.util.Map.Entry; -import java.util.TreeMap; - -import org.lwjgl.opengl.GL11; - -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.VertexBuffer; -import net.minecraft.client.renderer.vertex.DefaultVertexFormats; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.math.BlockPos; - -import buildcraft.lib.client.render.DetatchedRenderer.IDetachedRenderer; -import buildcraft.lib.debug.DebugRenderHelper; - -import buildcraft.factory.tile.TileFloodGate; - -public class AdvDebuggerFloodGate implements IDetachedRenderer { - public final TileFloodGate target; - - public AdvDebuggerFloodGate(TileFloodGate target) { - this.target = target; - } - - @Override - public void render(EntityPlayer player, float partialTicks) { - VertexBuffer vb = Tessellator.getInstance().getBuffer(); - vb.begin(GL11.GL_QUADS, DefaultVertexFormats.BLOCK); - - TreeMap> queues = target.clientLayerQueues; - - int r = 255; - int g = 255; - int b = 255; - for (Entry> entry : queues.entrySet()) { - Deque positions = entry.getValue(); - for (BlockPos p : positions) { - int colour = 0xFF_00_00_00 | (r << 16) | (g << 8) | b; - DebugRenderHelper.renderSmallCuboid(vb, p, colour); - r -= 16; - if (r < 0) { - r = 256; - g -= 16; - if (g < 0) { - g = 256; - b -= 16; - if (b < 0) { - b = 256; - } - } - } - } - } - - Tessellator.getInstance().draw(); - } -} diff --git a/common/buildcraft/factory/tile/TileFloodGate.java b/common/buildcraft/factory/tile/TileFloodGate.java new file mode 100644 index 0000000000..841692f81e --- /dev/null +++ b/common/buildcraft/factory/tile/TileFloodGate.java @@ -0,0 +1,314 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.factory.tile; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.Set; +import java.util.stream.Collectors; + +import com.google.common.collect.ImmutableList; +import com.google.common.primitives.Booleans; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.ITickable; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.WorldServer; + +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; +import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import buildcraft.api.core.BuildCraftAPI; +import buildcraft.api.core.EnumPipePart; +import buildcraft.api.tiles.IDebuggable; + +import buildcraft.lib.fluid.Tank; +import buildcraft.lib.misc.BlockUtil; +import buildcraft.lib.misc.CapUtil; +import buildcraft.lib.misc.FluidUtilBC; +import buildcraft.lib.misc.MessageUtil; +import buildcraft.lib.misc.NBTUtilBC; +import buildcraft.lib.net.PacketBufferBC; +import buildcraft.lib.tile.TileBC_Neptune; + +import buildcraft.factory.BCFactoryBlocks; +import buildcraft.factory.block.BlockFloodGate; + +public class TileFloodGate extends TileBC_Neptune implements ITickable, IDebuggable { + private static final int[] REBUILD_DELAYS = new int[] { + 1, + 2, + 4, + 8, + 16, + 32, + 64, + 128, + 256, + 512, + 1024, + 2048, + 4096, + 8192, + 16384 + }; + + private final Tank tank = new Tank("tank", 16 * Fluid.BUCKET_VOLUME, this); + public final EnumMap openSides = new EnumMap<>(EnumFacing.class); + public final Queue queue = new PriorityQueue<>( + Comparator.comparingInt(blockPos -> + (blockPos.getX() - pos.getX()) * (blockPos.getX() - pos.getX()) + + (blockPos.getY() - pos.getY()) * (blockPos.getY() - pos.getY()) + + (blockPos.getZ() - pos.getZ()) * (blockPos.getZ() - pos.getZ()) + ) + ); + private final Map> paths = new HashMap<>(); + private int delayIndex = 0; + private int tick = 0; + + public TileFloodGate() { + caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tank, EnumPipePart.VALUES); + Arrays.stream(EnumFacing.VALUES) + .forEach(side -> openSides.put(side, BlockFloodGate.CONNECTED_MAP.containsKey(side))); + } + + private int getCurrentDelay() { + return REBUILD_DELAYS[delayIndex]; + } + + private void buildQueue() { + world.profiler.startSection("prepare"); + queue.clear(); + paths.clear(); + if (tank.isEmpty()) { + world.profiler.endSection(); + return; + } + Set checked = new HashSet<>(); + List nextPosesToCheck = new ArrayList<>(); + openSides.entrySet().stream() + .filter(Entry::getValue) + .map(Entry::getKey) + .map(pos::offset) + .forEach(nextPosesToCheck::add); + world.profiler.endStartSection("build"); + outer: + while (!nextPosesToCheck.isEmpty()) { + List nextPosesToCheckCopy = new ArrayList<>(nextPosesToCheck); + nextPosesToCheck.clear(); + for (BlockPos posToCheck : nextPosesToCheckCopy) { + for (EnumFacing side : new EnumFacing[] { + EnumFacing.DOWN, + EnumFacing.NORTH, + EnumFacing.SOUTH, + EnumFacing.WEST, + EnumFacing.EAST + }) { + BlockPos offsetPos = posToCheck.offset(side); + if ((offsetPos.getX() - pos.getX()) * (offsetPos.getX() - pos.getX()) + + (offsetPos.getZ() - pos.getZ()) * (offsetPos.getZ() - pos.getZ()) > 64 * 64) { + continue; + } + if (!openSides.get(side)) { + if (side == EnumFacing.NORTH && offsetPos.getZ() >= pos.getZ()) { + continue; + } + if (side == EnumFacing.SOUTH && offsetPos.getZ() <= pos.getZ()) { + continue; + } + if (side == EnumFacing.WEST && offsetPos.getX() >= pos.getX()) { + continue; + } + if (side == EnumFacing.EAST && offsetPos.getX() <= pos.getX()) { + continue; + } + } + if (!checked.contains(offsetPos)) { + if (canSearch(offsetPos)) { + ImmutableList.Builder pathBuilder = new ImmutableList.Builder<>(); + if (paths.containsKey(posToCheck)) { + pathBuilder.addAll(paths.get(posToCheck)); + } + pathBuilder.add(offsetPos); + paths.put(offsetPos, pathBuilder.build()); + if (canFill(offsetPos)) { + if (openSides.get(EnumFacing.DOWN) || + Math.abs(offsetPos.getY() - pos.getY()) < Math.abs(offsetPos.getX() - pos.getX()) || + Math.abs(offsetPos.getY() - pos.getY()) < Math.abs(offsetPos.getZ() - pos.getZ())) { + queue.add(offsetPos); + } + if (queue.size() >= 4096) { + break outer; + } + } + nextPosesToCheck.add(offsetPos); + } + checked.add(offsetPos); + } + } + } + } + world.profiler.endSection(); + } + + private boolean canFill(BlockPos offsetPos) { + if (world.isAirBlock(offsetPos)) { + return true; + } + Fluid fluid = BlockUtil.getFluidWithFlowing(world, offsetPos); + // noinspection RedundantIfStatement + if (fluid != null && + Objects.equals(fluid.getName(), tank.getFluidType().getName()) && + BlockUtil.getFluid(world, offsetPos) == null) { + return true; + } + return false; + } + + private boolean canSearch(BlockPos offsetPos) { + if (canFill(offsetPos)) { + return true; + } + Fluid fluid = BlockUtil.getFluid(world, offsetPos); + return fluid != null && Objects.equals(fluid.getName(), tank.getFluidType().getName()); + } + + // ITickable + + @Override + public void update() { + if (world.isRemote) { + return; + } + +// tank.fill(new FluidStack(FluidRegistry.WATER, 1000), true); + FluidUtilBC.pullFluidAround(world, pos, tank); + + tick++; + if (tick % 16 == 0) { + if (!tank.isEmpty() && !queue.isEmpty()) { + FluidStack fluid = tank.drain(Fluid.BUCKET_VOLUME, false); + if (fluid != null && fluid.amount >= Fluid.BUCKET_VOLUME) { + BlockPos currentPos = queue.poll(); + if (paths.get(currentPos).stream().allMatch(this::canSearch) && canFill(currentPos)) { + if (FluidUtil.tryPlaceFluid( + BuildCraftAPI.fakePlayerProvider.getFakePlayer( + (WorldServer) world, + getOwner(), + currentPos + ), + world, + currentPos, + tank, + fluid + )) { + for (EnumFacing side : EnumFacing.VALUES) { + world.notifyNeighborsOfStateChange( + currentPos.offset(side), + BCFactoryBlocks.floodGate, + false + ); + } + delayIndex = 0; + } + } else { + buildQueue(); + } + } + } + } + + if (queue.isEmpty() && tick % getCurrentDelay() == 0) { + delayIndex = Math.min(delayIndex + 1, REBUILD_DELAYS.length - 1); + buildQueue(); + } + } + + // NBT + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { + super.writeToNBT(nbt); + nbt.setTag("tank", tank.writeToNBT(new NBTTagCompound())); + nbt.setTag("openSides", NBTUtilBC.writeBooleanList(openSides.values().stream())); + return nbt; + } + + @Override + public void readFromNBT(NBTTagCompound nbt) { + super.readFromNBT(nbt); + tank.readFromNBT(nbt.getCompoundTag("tank")); + Boolean[] blockedSidesArray = NBTUtilBC.readBooleanList(nbt.getTag("openSides")).toArray(Boolean[]::new); + for (int i = 0; i < blockedSidesArray.length; i++) { + openSides.put(EnumFacing.getFront(i), blockedSidesArray[i]); + } + } + + // Netwokring + + @Override + public void writePayload(int id, PacketBufferBC buffer, Side side) { + super.writePayload(id, buffer, side); + if (side == Side.SERVER) { + if (id == NET_RENDER_DATA) { + // tank.writeToBuffer(buffer); + MessageUtil.writeBooleanArray(buffer, Booleans.toArray(openSides.values())); + } + } + } + + @Override + public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext ctx) throws IOException { + super.readPayload(id, buffer, side, ctx); + if (side == Side.CLIENT) { + if (id == NET_RENDER_DATA) { + // tank.readFromBuffer(buffer); + boolean[] old = Booleans.toArray(openSides.values()); + boolean[] blockedSidesArray = MessageUtil.readBooleanArray(buffer, openSides.values().size()); + for (int i = 0; i < blockedSidesArray.length; i++) { + openSides.put(EnumFacing.getFront(i), blockedSidesArray[i]); + } + if (!Arrays.equals(old, Booleans.toArray(openSides.values()))) { + redrawBlock(); + } + } + } + } + + // IDebuggable + + @Override + @SideOnly(Side.CLIENT) + public void getDebugInfo(List left, List right, EnumFacing side) { + left.add(""); + left.add("fluid = " + tank.getDebugString()); + left.add("open sides = " + openSides.entrySet().stream() + .filter(Entry::getValue) + .map(Entry::getKey) + .map(Enum::name) + .collect(Collectors.joining(", "))); + left.add("delay = " + getCurrentDelay()); + left.add("tick = " + tick); + left.add("queue size = " + queue.size()); + } +} diff --git a/common/buildcraft/factory/tile/TilePump.java b/common/buildcraft/factory/tile/TilePump.java index 7014cdfb38..acc7712268 100644 --- a/common/buildcraft/factory/tile/TilePump.java +++ b/common/buildcraft/factory/tile/TilePump.java @@ -46,13 +46,13 @@ public class TilePump extends TileMiner { private final Tank tank = new Tank("tank", 16 * Fluid.BUCKET_VOLUME, this); private boolean queueBuilt = false; - private Queue queue = new PriorityQueue<>( - Comparator.comparing(blockPos -> + private final Queue queue = new PriorityQueue<>( + Comparator.comparingInt(blockPos -> (blockPos.getX() - pos.getX()) * (blockPos.getX() - pos.getX()) + (blockPos.getZ() - pos.getZ()) * (blockPos.getZ() - pos.getZ()) ).reversed() ); - private Map> paths = new HashMap<>(); + private final Map> paths = new HashMap<>(); public TilePump() { tank.setCanFill(false); diff --git a/common/buildcraft/lib/misc/NBTUtilBC.java b/common/buildcraft/lib/misc/NBTUtilBC.java index b57dd8ea9b..125fef33fb 100644 --- a/common/buildcraft/lib/misc/NBTUtilBC.java +++ b/common/buildcraft/lib/misc/NBTUtilBC.java @@ -350,8 +350,14 @@ public static NBTTagList writeCompoundList(Stream stream) { return list; } - public static Stream readCompoundList(NBTTagList list) { - return IntStream.range(0, list.tagCount()).mapToObj(list::getCompoundTagAt); + public static Stream readCompoundList(NBTBase list) { + if (list == null) { + return Stream.empty(); + } + if (!(list instanceof NBTTagList)) { + throw new IllegalArgumentException(); + } + return IntStream.range(0, ((NBTTagList) list).tagCount()).mapToObj(((NBTTagList) list)::getCompoundTagAt); } public static NBTTagList writeStringList(Stream stream) { @@ -360,7 +366,33 @@ public static NBTTagList writeStringList(Stream stream) { return list; } - public static Stream readStringList(NBTTagList list) { - return IntStream.range(0, list.tagCount()).mapToObj(list::getStringTagAt); + public static Stream readStringList(NBTBase list) { + if (list == null) { + return Stream.empty(); + } + if (!(list instanceof NBTTagList)) { + throw new IllegalArgumentException(); + } + return IntStream.range(0, ((NBTTagList) list).tagCount()).mapToObj(((NBTTagList) list)::getStringTagAt); + } + + public static NBTTagByteArray writeBooleanList(Stream stream) { + Boolean[] booleans = stream.toArray(Boolean[]::new); + BitSet bitSet = new BitSet(booleans.length); + for (int i = 0; i < booleans.length; i++) { + bitSet.set(i, bitSet.get(i)); + } + return new NBTTagByteArray(bitSet.toByteArray()); + } + + public static Stream readBooleanList(NBTBase list) { + if (list == null) { + return Stream.empty(); + } + if (!(list instanceof NBTTagByteArray)) { + throw new IllegalArgumentException(); + } + BitSet bitSet = BitSet.valueOf(((NBTTagByteArray) list).getByteArray()); + return IntStream.range(0, bitSet.length()).mapToObj(bitSet::get); } } diff --git a/common/buildcraft/robotics/zone/ZonePlan.java b/common/buildcraft/robotics/zone/ZonePlan.java index 890643e163..c987359067 100755 --- a/common/buildcraft/robotics/zone/ZonePlan.java +++ b/common/buildcraft/robotics/zone/ZonePlan.java @@ -22,8 +22,6 @@ import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.Vec3d; -import net.minecraftforge.common.util.Constants; - import buildcraft.api.core.IZone; import buildcraft.lib.misc.NBTUtilBC; @@ -129,7 +127,7 @@ public void writeToNBT(NBTTagCompound nbt) { } public void readFromNBT(NBTTagCompound nbt) { - NBTUtilBC.readCompoundList(nbt.getTagList("chunkMapping", Constants.NBT.TAG_COMPOUND)) + NBTUtilBC.readCompoundList(nbt.getTag("chunkMapping")) .forEach(zoneChunkTag -> { ZoneChunk chunk = new ZoneChunk(); chunk.readFromNBT(zoneChunkTag); diff --git a/common_old_license/buildcraft/factory/tile/TileFloodGate.java b/common_old_license/buildcraft/factory/tile/TileFloodGate.java deleted file mode 100644 index 1fd7848003..0000000000 --- a/common_old_license/buildcraft/factory/tile/TileFloodGate.java +++ /dev/null @@ -1,273 +0,0 @@ -package buildcraft.factory.tile; - -import java.io.IOException; -import java.util.ArrayDeque; -import java.util.Arrays; -import java.util.Deque; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TreeMap; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockLiquid; -import net.minecraft.block.state.IBlockState; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.ITickable; -import net.minecraft.util.math.BlockPos; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import buildcraft.api.core.EnumPipePart; -import buildcraft.api.tiles.IDebuggable; - -import buildcraft.lib.client.render.DetatchedRenderer.IDetachedRenderer; -import buildcraft.lib.debug.IAdvDebugTarget; -import buildcraft.lib.fluid.Tank; -import buildcraft.lib.misc.BlockUtil; -import buildcraft.lib.misc.CapUtil; -import buildcraft.lib.misc.FluidUtilBC; -import buildcraft.lib.misc.MessageUtil; -import buildcraft.lib.net.PacketBufferBC; -import buildcraft.lib.tile.TileBC_Neptune; - -import buildcraft.factory.block.BlockFloodGate; -import buildcraft.factory.client.render.AdvDebuggerFloodGate; - -public class TileFloodGate extends TileBC_Neptune implements ITickable, IDebuggable { - public static final EnumFacing[] SIDE_INDEXES = new EnumFacing[] { EnumFacing.DOWN, EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.WEST, EnumFacing.EAST }; - public static final int[] REBUILD_DELAYS = new int[] { 128, 256, 512, 1024, 2048, 4096, 8192, 16384 }; - - private boolean[] sidesBlocked = new boolean[5]; - private final Tank tank = new Tank("tank", 2000, this); - private int delayIndex = 0; - private int tick = 120; - private final TreeMap> layerQueues = new TreeMap<>(); - - /** Used for debugging on the client with {@link IAdvDebugTarget} */ - public final TreeMap> clientLayerQueues = new TreeMap<>(); - - public TileFloodGate() { - caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tank, EnumPipePart.VALUES); - } - - public static int getIndexFromSide(EnumFacing side) { - return Arrays.binarySearch(SIDE_INDEXES, side); - } - - public boolean isSideBlocked(EnumFacing side) { - return sidesBlocked[getIndexFromSide(side)]; - } - - public void setSideBlocked(EnumFacing side, boolean blocked) { - sidesBlocked[getIndexFromSide(side)] = blocked; - sendNetworkUpdate(NET_RENDER_DATA); - } - - public int getCurrentDelay() { - return REBUILD_DELAYS[delayIndex]; - } - - private Deque getLayerQueue(int layer) { - return layerQueues.computeIfAbsent(layer, k -> new LinkedList<>()); - } - - private void rebuildQueue() { - layerQueues.clear(); - - Set visitedBlocks = new HashSet<>(); - Deque blocksFound = new LinkedList<>(); - - tryAddToQueue(pos, visitedBlocks, blocksFound); - - while (!blocksFound.isEmpty()) { - Deque blocksToExpand = blocksFound; - blocksFound = new LinkedList<>(); - - for (BlockPos index : blocksToExpand) { - tryAddToQueue(index, visitedBlocks, blocksFound); - } - } - } - - private void tryAddToQueue(BlockPos blockPos, Set visitedBlocks, Deque blocksFound) { - for (EnumFacing side : EnumFacing.VALUES) { - if (side != EnumFacing.UP && !isSideBlocked(side)) { - BlockPos currentPos = blockPos.offset(side); - - if (currentPos.getY() < 0 || currentPos.getY() > 255) { - return; - } - if (visitedBlocks.add(currentPos)) { - if ((currentPos.getX() - pos.getX()) * (currentPos.getX() - pos.getX()) + (currentPos.getZ() - pos.getZ()) * (currentPos.getZ() - pos.getZ()) > 64 * 64) { - return; - } - - IBlockState blockState = world.getBlockState(currentPos); - - Block block = blockState.getBlock(); - Fluid fluid = BlockUtil.getFluidWithFlowing(block); - - boolean isCurrentFluid = this.tank.getFluidType() != null && this.tank.getFluidType() == fluid; - - if (world.isAirBlock(currentPos) || block instanceof BlockFloodGate || isCurrentFluid) { - blocksFound.add(currentPos); - if (world.isAirBlock(currentPos) || (isCurrentFluid && blockState.getValue(BlockLiquid.LEVEL) != 0)) { - getLayerQueue(currentPos.getY()).addLast(currentPos); - } - } - } - } - } - } - - private BlockPos getNext() { - if (layerQueues.isEmpty()) { - return null; - } - - Deque bottomLayer = layerQueues.firstEntry().getValue(); - - if (bottomLayer != null) { - if (bottomLayer.isEmpty()) { - bottomLayer = layerQueues.pollFirstEntry().getValue(); - } - return bottomLayer.pollFirst(); - } - - return null; - } - - // ITickable - - @Override - public void update() { - if (world.isRemote) { - return; - } - - FluidUtilBC.pullFluidAround(world, pos, tank); - - tick++; - if (tick % 16 == 0) { - FluidStack fluid = tank.drain(1000, false); - if (fluid != null && fluid.amount == 1000) { - BlockPos current = getNext(); - if (current != null && world.isAirBlock(current)) { - world.setBlockState(current, fluid.getFluid().getBlock().getDefaultState()); - tank.drain(1000, true); - delayIndex = 0; - } - } - } - - if (tick % getCurrentDelay() == 0) { - delayIndex = Math.min(delayIndex + 1, REBUILD_DELAYS.length - 1); - rebuildQueue(); - } - } - - // IDebuggable - - @Override - @SideOnly(Side.CLIENT) - public void getDebugInfo(List left, List right, EnumFacing side) { - left.add(""); - left.add("fluid = " + tank.getDebugString()); - String[] sides = new String[5]; - for (int i = 0; i < sidesBlocked.length; i++) { - sides[i] = SIDE_INDEXES[i].toString().toLowerCase() + "(" + sidesBlocked[i] + ")"; - } - left.add("sides = " + String.join(" ", sides)); - left.add("delay = " + getCurrentDelay()); - } - - @Override - @SideOnly(Side.CLIENT) - public IDetachedRenderer getDebugRenderer() { - return new AdvDebuggerFloodGate(this); - } - - // NBT - - @Override - public void readFromNBT(NBTTagCompound nbt) { - super.readFromNBT(nbt); - tank.readFromNBT(nbt); - for (int i = 0; i < sidesBlocked.length; i++) { - nbt.setBoolean("sides_blocked_" + i, sidesBlocked[i]); - } - } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbt) { - super.writeToNBT(nbt); - tank.writeToNBT(nbt); - for (int i = 0; i < sidesBlocked.length; i++) { - sidesBlocked[i] = nbt.getBoolean("sides_blocked_" + i); - } - return nbt; - } - - // Netwokring - - @Override - public void writePayload(int id, PacketBufferBC buffer, Side side) { - super.writePayload(id, buffer, side); - if (side == Side.SERVER) { - if (id == NET_RENDER_DATA) { - // tank.writeToBuffer(buffer); - MessageUtil.writeBooleanArray(buffer, sidesBlocked); - } else if (id == NET_ADV_DEBUG) { - buffer.writeInt(layerQueues.size()); - for (Entry> entry : layerQueues.entrySet()) { - Integer key = entry.getKey(); - Deque positions = entry.getValue(); - buffer.writeInt(key); - buffer.writeInt(positions.size()); - for (BlockPos p : positions) { - BlockPos diff = p.subtract(getPos()); - buffer.writeByte(diff.getX()); - buffer.writeByte(diff.getZ()); - } - } - } - } - } - - @Override - public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext ctx) throws IOException { - super.readPayload(id, buffer, side, ctx); - if (side == Side.CLIENT) { - if (id == NET_RENDER_DATA) { - // tank.readFromBuffer(buffer); - boolean[] read = MessageUtil.readBooleanArray(buffer, sidesBlocked.length); - if (!Arrays.equals(read, sidesBlocked)) { - sidesBlocked = read; - redrawBlock(); - } - } else if (id == NET_ADV_DEBUG) { - clientLayerQueues.clear(); - int count = buffer.readInt(); - for (int i = 0; i < count; i++) { - int key = buffer.readInt(); - int values = buffer.readInt(); - Deque positions = new ArrayDeque<>(values); - for (int j = 0; j < values; j++) { - int x = getPos().getX() + buffer.readByte(); - int z = getPos().getZ() + buffer.readByte(); - positions.add(new BlockPos(x, key, z)); - } - clientLayerQueues.put(key, positions); - } - } - } - } -} From 9a2cd1b724c2c2cd992b5e203f26acc4b42cb13b Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Thu, 29 Jun 2017 14:39:07 +0300 Subject: [PATCH 61/89] Port TriggerInventoryLevel and remove common_old_license --- build.gradle | 1 - common/buildcraft/core/BCCoreStatements.java | 16 ++-- .../core/statements/ActionMachineControl.java | 5 +- .../statements/TriggerFluidContainer.java | 35 +++---- .../TriggerFluidContainerLevel.java | 52 +++++------ .../core/statements/TriggerInventory.java | 35 +++---- .../statements/TriggerInventoryLevel.java | 75 ++++++++------- common/buildcraft/lib/misc/StackUtil.java | 8 +- .../lib/inventory/InventoryIterator.java | 57 ------------ .../inventory/InventoryIteratorHandler.java | 90 ------------------ .../lib/inventory/InventoryIteratorSided.java | 93 ------------------- .../inventory/InventoryIteratorSimple.java | 87 ----------------- 12 files changed, 111 insertions(+), 443 deletions(-) rename {common_old_license => common}/buildcraft/core/statements/TriggerInventoryLevel.java (66%) delete mode 100644 common_old_license/buildcraft/lib/inventory/InventoryIterator.java delete mode 100644 common_old_license/buildcraft/lib/inventory/InventoryIteratorHandler.java delete mode 100644 common_old_license/buildcraft/lib/inventory/InventoryIteratorSided.java delete mode 100644 common_old_license/buildcraft/lib/inventory/InventoryIteratorSimple.java diff --git a/build.gradle b/build.gradle index 72d2f361a7..893c77509b 100644 --- a/build.gradle +++ b/build.gradle @@ -84,7 +84,6 @@ sourceSets { main { java { srcDir "common" - srcDir "common_old_license" // srcDir "src_old_license" } resources { diff --git a/common/buildcraft/core/BCCoreStatements.java b/common/buildcraft/core/BCCoreStatements.java index 2e29649ac5..2c46c116c8 100644 --- a/common/buildcraft/core/BCCoreStatements.java +++ b/common/buildcraft/core/BCCoreStatements.java @@ -47,18 +47,18 @@ public class BCCoreStatements { public static final TriggerPower TRIGGER_POWER_LOW = new TriggerPower(false); public static final TriggerPower[] TRIGGER_POWER = { TRIGGER_POWER_LOW, TRIGGER_POWER_HIGH }; - public static final TriggerInventory TRIGGER_INVENTORY_EMPTY = new TriggerInventory(TriggerInventory.State.Empty); - public static final TriggerInventory TRIGGER_INVENTORY_CONTAINS = new TriggerInventory(TriggerInventory.State.Contains); - public static final TriggerInventory TRIGGER_INVENTORY_SPACE = new TriggerInventory(TriggerInventory.State.Space); - public static final TriggerInventory TRIGGER_INVENTORY_FULL = new TriggerInventory(TriggerInventory.State.Full); + public static final TriggerInventory TRIGGER_INVENTORY_EMPTY = new TriggerInventory(TriggerInventory.State.EMPTY); + public static final TriggerInventory TRIGGER_INVENTORY_CONTAINS = new TriggerInventory(TriggerInventory.State.CONTAINS); + public static final TriggerInventory TRIGGER_INVENTORY_SPACE = new TriggerInventory(TriggerInventory.State.SPACE); + public static final TriggerInventory TRIGGER_INVENTORY_FULL = new TriggerInventory(TriggerInventory.State.FULL); public static final TriggerInventory[] TRIGGER_INVENTORY = {// TRIGGER_INVENTORY_EMPTY, TRIGGER_INVENTORY_SPACE, TRIGGER_INVENTORY_CONTAINS, TRIGGER_INVENTORY_FULL // }; - public static final TriggerFluidContainer TRIGGER_FLUID_EMPTY = new TriggerFluidContainer(TriggerFluidContainer.State.Empty); - public static final TriggerFluidContainer TRIGGER_FLUID_CONTAINS = new TriggerFluidContainer(TriggerFluidContainer.State.Contains); - public static final TriggerFluidContainer TRIGGER_FLUID_SPACE = new TriggerFluidContainer(TriggerFluidContainer.State.Space); - public static final TriggerFluidContainer TRIGGER_FLUID_FULL = new TriggerFluidContainer(TriggerFluidContainer.State.Full); + public static final TriggerFluidContainer TRIGGER_FLUID_EMPTY = new TriggerFluidContainer(TriggerFluidContainer.State.EMPTY); + public static final TriggerFluidContainer TRIGGER_FLUID_CONTAINS = new TriggerFluidContainer(TriggerFluidContainer.State.CONTAINS); + public static final TriggerFluidContainer TRIGGER_FLUID_SPACE = new TriggerFluidContainer(TriggerFluidContainer.State.SPACE); + public static final TriggerFluidContainer TRIGGER_FLUID_FULL = new TriggerFluidContainer(TriggerFluidContainer.State.FULL); public static final TriggerFluidContainer[] TRIGGER_FLUID = {// TRIGGER_FLUID_EMPTY, TRIGGER_FLUID_SPACE, TRIGGER_FLUID_CONTAINS, TRIGGER_FLUID_FULL // }; diff --git a/common/buildcraft/core/statements/ActionMachineControl.java b/common/buildcraft/core/statements/ActionMachineControl.java index 039e43b797..b5bd4483a5 100644 --- a/common/buildcraft/core/statements/ActionMachineControl.java +++ b/common/buildcraft/core/statements/ActionMachineControl.java @@ -30,7 +30,10 @@ public class ActionMachineControl extends BCStatement implements IActionExternal public final Mode mode; public ActionMachineControl(Mode mode) { - super("buildcraft:machine." + mode.name().toLowerCase(Locale.ROOT), "buildcraft.machine." + mode.name().toLowerCase(Locale.ROOT)); + super( + "buildcraft:machine." + mode.name().toLowerCase(Locale.ROOT), + "buildcraft.machine." + mode.name().toLowerCase(Locale.ROOT) + ); this.mode = mode; } diff --git a/common/buildcraft/core/statements/TriggerFluidContainer.java b/common/buildcraft/core/statements/TriggerFluidContainer.java index fa666e26e8..e3f5cd20e6 100644 --- a/common/buildcraft/core/statements/TriggerFluidContainer.java +++ b/common/buildcraft/core/statements/TriggerFluidContainer.java @@ -31,21 +31,13 @@ import buildcraft.core.BCCoreStatements; public class TriggerFluidContainer extends BCStatement implements ITriggerExternal { - - public enum State { - - Empty, - Contains, - Space, - Full; - - public static final State[] VALUES = values(); - } - public State state; public TriggerFluidContainer(State state) { - super("buildcraft:fluid." + state.name().toLowerCase(Locale.ROOT), "buildcraft.fluid." + state.name().toLowerCase(Locale.ROOT)); + super( + "buildcraft:fluid." + state.name().toLowerCase(Locale.ROOT), + "buildcraft.fluid." + state.name().toLowerCase(Locale.ROOT) + ); this.state = state; } @@ -57,7 +49,7 @@ public SpriteHolder getSpriteHolder() { @Override public int maxParameters() { - return state == State.Contains || state == State.Space ? 1 : 0; + return state == State.CONTAINS || state == State.SPACE ? 1 : 0; } @Override @@ -86,10 +78,10 @@ public boolean isTriggerActive(TileEntity tile, EnumFacing side, IStatementConta } switch (state) { - case Empty: + case EMPTY: FluidStack drained = handler.drain(1, false); return drained == null || drained.amount <= 0; - case Contains: + case CONTAINS: for (IFluidTankProperties c : liquids) { if (c == null) continue; FluidStack fluid = c.getContents(); @@ -98,7 +90,7 @@ public boolean isTriggerActive(TileEntity tile, EnumFacing side, IStatementConta } } return false; - case Space: + case SPACE: if (searchedFluid == null) { for (IFluidTankProperties c : liquids) { if (c == null) continue; @@ -110,7 +102,7 @@ public boolean isTriggerActive(TileEntity tile, EnumFacing side, IStatementConta return false; } return handler.fill(searchedFluid, false) > 0; - case Full: + case FULL: if (searchedFluid == null) { for (IFluidTankProperties c : liquids) { if (c == null) continue; @@ -137,4 +129,13 @@ public IStatementParameter createParameter(int index) { public IStatement[] getPossible() { return BCCoreStatements.TRIGGER_FLUID_ALL; } + + public enum State { + EMPTY, + CONTAINS, + SPACE, + FULL; + + public static final State[] VALUES = values(); + } } diff --git a/common/buildcraft/core/statements/TriggerFluidContainerLevel.java b/common/buildcraft/core/statements/TriggerFluidContainerLevel.java index 6c48c0a47a..4a6673d637 100644 --- a/common/buildcraft/core/statements/TriggerFluidContainerLevel.java +++ b/common/buildcraft/core/statements/TriggerFluidContainerLevel.java @@ -29,26 +29,13 @@ import buildcraft.core.BCCoreStatements; public class TriggerFluidContainerLevel extends BCStatement implements ITriggerExternal { - - public enum TriggerType { - - BELOW25(0.25F), - BELOW50(0.5F), - BELOW75(0.75F); - - public static final TriggerType[] VALUES = values(); - - public final float level; - - TriggerType(float level) { - this.level = level; - } - } - public final TriggerType type; public TriggerFluidContainerLevel(TriggerType type) { - super("buildcraft:fluid." + type.name().toLowerCase(Locale.ROOT), "buildcraft.fluid." + type.name().toLowerCase(Locale.ROOT)); + super( + "buildcraft:fluid." + type.name().toLowerCase(Locale.ROOT), + "buildcraft.fluid." + type.name().toLowerCase(Locale.ROOT) + ); this.type = type; } @@ -82,25 +69,22 @@ public boolean isTriggerActive(TileEntity tile, EnumFacing side, IStatementConta } } - IFluidTankProperties[] liquids = handler.getTankProperties(); - if (liquids == null || liquids.length == 0) { + IFluidTankProperties[] tankPropertiesArray = handler.getTankProperties(); + if (tankPropertiesArray == null || tankPropertiesArray.length == 0) { return false; } - for (IFluidTankProperties c : liquids) { - if (c == null) { + for (IFluidTankProperties tankProperties : tankPropertiesArray) { + if (tankProperties == null) { continue; } - FluidStack fluid = c.getContents(); + FluidStack fluid = tankProperties.getContents(); if (fluid == null) { - if (searchedFluid == null) { - return true; - } - return handler.fill(searchedFluid, false) > 0; + return searchedFluid == null || handler.fill(searchedFluid, false) > 0; } if (searchedFluid == null || searchedFluid.isFluidEqual(fluid)) { - float percentage = fluid.amount / (float) c.getCapacity(); + float percentage = fluid.amount / (float) tankProperties.getCapacity(); return percentage < type.level; } } @@ -116,4 +100,18 @@ public IStatementParameter createParameter(int index) { public IStatement[] getPossible() { return BCCoreStatements.TRIGGER_FLUID_ALL; } + + public enum TriggerType { + BELOW25(0.25F), + BELOW50(0.5F), + BELOW75(0.75F); + + TriggerType(float level) { + this.level = level; + } + + public static final TriggerType[] VALUES = values(); + + public final float level; + } } diff --git a/common/buildcraft/core/statements/TriggerInventory.java b/common/buildcraft/core/statements/TriggerInventory.java index 53dd37872f..381e04ded5 100644 --- a/common/buildcraft/core/statements/TriggerInventory.java +++ b/common/buildcraft/core/statements/TriggerInventory.java @@ -29,21 +29,13 @@ import buildcraft.core.BCCoreStatements; public class TriggerInventory extends BCStatement implements ITriggerExternal { - - public enum State { - - Empty, - Contains, - Space, - Full; - - public static final State[] VALUES = values(); - } - public State state; public TriggerInventory(State state) { - super("buildcraft:inventory." + state.name().toLowerCase(Locale.ENGLISH), "buildcraft.inventory." + state.name().toLowerCase(Locale.ENGLISH)); + super( + "buildcraft:inventory." + state.name().toLowerCase(Locale.ROOT), + "buildcraft.inventory." + state.name().toLowerCase(Locale.ROOT) + ); this.state = state; } @@ -54,12 +46,12 @@ public SpriteHolder getSpriteHolder() { @Override public int maxParameters() { - return state == State.Contains || state == State.Space ? 1 : 0; + return state == State.CONTAINS || state == State.SPACE ? 1 : 0; } @Override public String getDescription() { - return LocaleUtil.localize("gate.trigger.inventory." + state.name().toLowerCase(Locale.ENGLISH)); + return LocaleUtil.localize("gate.trigger.inventory." + state.name().toLowerCase(Locale.ROOT)); } @Override @@ -97,11 +89,11 @@ public boolean isTriggerActive(TileEntity tile, EnumFacing side, IStatementConta } switch (state) { - case Empty: + case EMPTY: return !foundItems; - case Contains: + case CONTAINS: return foundItems; - case Space: + case SPACE: return foundSpace; default: return !foundSpace; @@ -120,4 +112,13 @@ public IStatementParameter createParameter(int index) { public IStatement[] getPossible() { return BCCoreStatements.TRIGGER_INVENTORY_ALL; } + + public enum State { + EMPTY, + CONTAINS, + SPACE, + FULL; + + public static final State[] VALUES = values(); + } } diff --git a/common_old_license/buildcraft/core/statements/TriggerInventoryLevel.java b/common/buildcraft/core/statements/TriggerInventoryLevel.java similarity index 66% rename from common_old_license/buildcraft/core/statements/TriggerInventoryLevel.java rename to common/buildcraft/core/statements/TriggerInventoryLevel.java index 3d479d572a..b7ae7bec9e 100644 --- a/common_old_license/buildcraft/core/statements/TriggerInventoryLevel.java +++ b/common/buildcraft/core/statements/TriggerInventoryLevel.java @@ -1,20 +1,20 @@ -/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com - *

    - * BuildCraft is distributed under the terms of the Minecraft Mod Public License 1.0, or MMPL. Please check the contents - * of the license located in http://www.mod-buildcraft.com/MMPL-1.0.txt */ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ package buildcraft.core.statements; import java.util.Locale; -import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.items.IItemHandler; -import buildcraft.api.core.IInvSlot; import buildcraft.api.statements.IStatement; import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.IStatementParameter; @@ -22,7 +22,7 @@ import buildcraft.api.statements.StatementParameterItemStack; import buildcraft.lib.client.sprite.SpriteHolderRegistry.SpriteHolder; -import buildcraft.lib.inventory.InventoryIterator; +import buildcraft.lib.misc.CapUtil; import buildcraft.lib.misc.LocaleUtil; import buildcraft.lib.misc.StackUtil; @@ -30,28 +30,14 @@ import buildcraft.core.BCCoreStatements; public class TriggerInventoryLevel extends BCStatement implements ITriggerExternal { - - public enum TriggerType { - - BELOW25(0.25F), - BELOW50(0.5F), - BELOW75(0.75F); - - public static final TriggerType[] VALUES = values(); - - public final float level; - - TriggerType(float level) { - this.level = level; - } - } - public TriggerType type; public TriggerInventoryLevel(TriggerType type) { - super("buildcraft:inventorylevel." + type.name().toLowerCase(Locale.ROOT),// - "buildcraft.inventorylevel." + type.name().toLowerCase(Locale.ROOT), // - "buildcraft.filteredBuffer." + type.name().toLowerCase(Locale.ROOT)); + super( + "buildcraft:inventorylevel." + type.name().toLowerCase(Locale.ROOT), + "buildcraft.inventorylevel." + type.name().toLowerCase(Locale.ROOT), + "buildcraft.filteredBuffer." + type.name().toLowerCase(Locale.ROOT) + ); this.type = type; } @@ -78,13 +64,15 @@ public String getDescription() { @Override public boolean isTriggerActive(TileEntity tile, EnumFacing side, IStatementContainer container, IStatementParameter[] parameters) { - // A parameter is required if (parameters == null || parameters.length < 1 || parameters[0] == null) { return false; } - if (tile instanceof IInventory) { - IInventory inventory = (IInventory) tile; + if (tile.hasCapability(CapUtil.CAP_ITEMS, side.getOpposite())) { + IItemHandler itemHandler = tile.getCapability(CapUtil.CAP_ITEMS, side.getOpposite()); + if (itemHandler == null) { + return false; + } ItemStack searchStack = parameters[0].getItemStack(); if (searchStack.isEmpty()) { @@ -93,21 +81,18 @@ public boolean isTriggerActive(TileEntity tile, EnumFacing side, IStatementConta int stackSpace = 0; int foundItems = 0; - for (IInvSlot slot : InventoryIterator.getIterable(inventory, side.getOpposite())) { - if (slot.canPutStackInSlot(searchStack)) { - ItemStack stackInSlot = slot.getStackInSlot(); - if (stackInSlot == null || StackUtil.canStacksOrListsMerge(stackInSlot, searchStack)) { - stackSpace++; - foundItems += stackInSlot == null ? 0 : stackInSlot.getCount(); - } + for (int slot = 0; slot < itemHandler.getSlots(); slot++) { + ItemStack stackInSlot = itemHandler.getStackInSlot(slot); + if (stackInSlot.isEmpty() || StackUtil.canStacksOrListsMerge(stackInSlot, searchStack)) { + stackSpace++; + foundItems += stackInSlot.isEmpty() ? 0 : stackInSlot.getCount(); } } if (stackSpace > 0) { - float percentage = foundItems / ((float) stackSpace * (float) Math.min(searchStack.getMaxStackSize(), inventory.getInventoryStackLimit())); + float percentage = foundItems / ((float) stackSpace * (float) searchStack.getMaxStackSize()); return percentage < type.level; } - } return false; @@ -122,4 +107,18 @@ public IStatementParameter createParameter(int index) { public IStatement[] getPossible() { return BCCoreStatements.TRIGGER_INVENTORY_ALL; } + + public enum TriggerType { + BELOW25(0.25F), + BELOW50(0.5F), + BELOW75(0.75F); + + TriggerType(float level) { + this.level = level; + } + + public static final TriggerType[] VALUES = values(); + + public final float level; + } } diff --git a/common/buildcraft/lib/misc/StackUtil.java b/common/buildcraft/lib/misc/StackUtil.java index b36909c212..9692854cc5 100644 --- a/common/buildcraft/lib/misc/StackUtil.java +++ b/common/buildcraft/lib/misc/StackUtil.java @@ -153,13 +153,7 @@ public static boolean canStacksOrListsMerge(@Nonnull ItemStack stack1, @Nonnull return list.matches(stack2, stack1); } - if (!stack1.isItemEqual(stack2)) { - return false; - } - if (!ItemStack.areItemStackTagsEqual(stack1, stack2)) { - return false; - } - return true; + return stack1.isItemEqual(stack2) && ItemStack.areItemStackTagsEqual(stack1, stack2); } diff --git a/common_old_license/buildcraft/lib/inventory/InventoryIterator.java b/common_old_license/buildcraft/lib/inventory/InventoryIterator.java deleted file mode 100644 index a7bd71fe1b..0000000000 --- a/common_old_license/buildcraft/lib/inventory/InventoryIterator.java +++ /dev/null @@ -1,57 +0,0 @@ -/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com - *

    - * BuildCraft is distributed under the terms of the Minecraft Mod Public License 1.0, or MMPL. Please check the contents - * of the license located in http://www.mod-buildcraft.com/MMPL-1.0.txt */ -package buildcraft.lib.inventory; - -import com.google.common.collect.ImmutableList; - -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.common.capabilities.ICapabilityProvider; -import net.minecraftforge.items.IItemHandler; - -import buildcraft.api.core.IInvSlot; - -import buildcraft.lib.misc.CapUtil; - -public final class InventoryIterator { - - /** Deactivate constructor */ - private InventoryIterator() {} - - public static Iterable getIterable(ICapabilityProvider provider) { - return getIterable(provider, null); - } - - public static Iterable getIterable(ICapabilityProvider provider, EnumFacing side) { - IItemHandler itemHandler = provider.getCapability(CapUtil.CAP_ITEMS, side); - if (itemHandler != null) { - return new InventoryIteratorHandler(itemHandler); - } else if (provider instanceof IInventory) { - return getIterable((IInventory) provider, side); - } else { - return ImmutableList.of(); - } - } - - public static Iterable getIterable(IInventory inv) { - return getIterable(inv, null); - } - - /** Returns an Iterable object for the specified side of the inventory. - * - * @param inv - * @param side - * @return Iterable */ - public static Iterable getIterable(IInventory inv, EnumFacing side) { - if (inv instanceof ISidedInventory) { - return new InventoryIteratorSided((ISidedInventory) inv, side); - } - - return new InventoryIteratorSimple(inv); - } - -} diff --git a/common_old_license/buildcraft/lib/inventory/InventoryIteratorHandler.java b/common_old_license/buildcraft/lib/inventory/InventoryIteratorHandler.java deleted file mode 100644 index b7d33e81c9..0000000000 --- a/common_old_license/buildcraft/lib/inventory/InventoryIteratorHandler.java +++ /dev/null @@ -1,90 +0,0 @@ -package buildcraft.lib.inventory; - -import java.util.Iterator; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.IItemHandlerModifiable; - -import buildcraft.api.core.IInvSlot; - -// Ok, this class is HORRID. IInvSlot needs to be redone to be based off of IItemHandler rather than IInventory -class InventoryIteratorHandler implements Iterable { - - private final IItemHandler inv; - - InventoryIteratorHandler(IItemHandler inv) { - this.inv = inv; - } - - @Override - public Iterator iterator() { - return new Iterator() { - int slot = 0; - - @Override - public boolean hasNext() { - return slot < inv.getSlots(); - } - - @Override - public IInvSlot next() { - return new InvSlot(slot++); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Remove not supported."); - } - }; - } - - class InvSlot implements IInvSlot { - - private int slot; - - InvSlot(int slot) { - this.slot = slot; - } - - @Override - public ItemStack getStackInSlot() { - return inv.getStackInSlot(slot); - } - - @Override - public void setStackInSlot(ItemStack stack) { - if (inv instanceof IItemHandlerModifiable) { - ((IItemHandlerModifiable) inv).setStackInSlot(slot, stack); - } else { - throw new IllegalStateException("Invalid IItemHandler class " + inv.getClass()); - } - } - - @Override - public boolean canPutStackInSlot(ItemStack stack) { - return inv.insertItem(slot, stack, true).isEmpty(); - } - - @Override - public boolean canTakeStackFromSlot(ItemStack stack) { - return !inv.extractItem(slot, 1, true).isEmpty(); - } - - @Override - public boolean isItemValidForSlot(ItemStack stack) { - return inv.insertItem(slot, stack, true).isEmpty(); - } - - @Override - public ItemStack decreaseStackInSlot(int amount) { - return inv.extractItem(slot, amount, false); - } - - @Override - public int getIndex() { - return slot; - } - } -} diff --git a/common_old_license/buildcraft/lib/inventory/InventoryIteratorSided.java b/common_old_license/buildcraft/lib/inventory/InventoryIteratorSided.java deleted file mode 100644 index e11cebdf75..0000000000 --- a/common_old_license/buildcraft/lib/inventory/InventoryIteratorSided.java +++ /dev/null @@ -1,93 +0,0 @@ -/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com - *

    - * BuildCraft is distributed under the terms of the Minecraft Mod Public License 1.0, or MMPL. Please check the contents - * of the license located in http://www.mod-buildcraft.com/MMPL-1.0.txt */ -package buildcraft.lib.inventory; - -import java.util.Iterator; - -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - -import buildcraft.api.core.IInvSlot; - -class InventoryIteratorSided implements Iterable { - - private final ISidedInventory inv; - private final EnumFacing side; - - InventoryIteratorSided(ISidedInventory inv, EnumFacing side) { - this.inv = inv; - this.side = side; - } - - @Override - public Iterator iterator() { - return new Iterator() { - int[] slots = inv.getSlotsForFace(side); - int index = 0; - - @Override - public boolean hasNext() { - return slots != null && index < slots.length; - } - - @Override - public IInvSlot next() { - return slots != null ? new InvSlot(slots[index++]) : null; - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Remove not supported."); - } - - }; - } - - private class InvSlot implements IInvSlot { - - private int slot; - - public InvSlot(int slot) { - this.slot = slot; - } - - @Override - public ItemStack getStackInSlot() { - return inv.getStackInSlot(slot); - } - - @Override - public void setStackInSlot(ItemStack stack) { - inv.setInventorySlotContents(slot, stack); - } - - @Override - public boolean canPutStackInSlot(ItemStack stack) { - return inv.canInsertItem(slot, stack, side) && inv.isItemValidForSlot(slot, stack); - } - - @Override - public boolean canTakeStackFromSlot(ItemStack stack) { - return inv.canExtractItem(slot, stack, side); - } - - @Override - public boolean isItemValidForSlot(ItemStack stack) { - return inv.isItemValidForSlot(slot, stack); - } - - @Override - public ItemStack decreaseStackInSlot(int amount) { - return inv.decrStackSize(slot, amount); - } - - @Override - public int getIndex() { - return slot; - } - - } -} diff --git a/common_old_license/buildcraft/lib/inventory/InventoryIteratorSimple.java b/common_old_license/buildcraft/lib/inventory/InventoryIteratorSimple.java deleted file mode 100644 index e6da0b8a8c..0000000000 --- a/common_old_license/buildcraft/lib/inventory/InventoryIteratorSimple.java +++ /dev/null @@ -1,87 +0,0 @@ -/** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com - *

    - * BuildCraft is distributed under the terms of the Minecraft Mod Public License 1.0, or MMPL. Please check the contents - * of the license located in http://www.mod-buildcraft.com/MMPL-1.0.txt */ -package buildcraft.lib.inventory; - -import java.util.Iterator; - -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - -import buildcraft.api.core.IInvSlot; - -class InventoryIteratorSimple implements Iterable { - - private final IInventory inv; - - InventoryIteratorSimple(IInventory inv) { - this.inv = inv; - } - - @Override - public Iterator iterator() { - return new Iterator() { - int slot = 0; - - @Override - public boolean hasNext() { - return slot < inv.getSizeInventory(); - } - - @Override - public IInvSlot next() { - return new InvSlot(slot++); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Remove not supported."); - } - }; - } - - private class InvSlot implements IInvSlot { - - private int slot; - - public InvSlot(int slot) { - this.slot = slot; - } - - @Override - public ItemStack getStackInSlot() { - return inv.getStackInSlot(slot); - } - - @Override - public void setStackInSlot(ItemStack stack) { - inv.setInventorySlotContents(slot, stack); - } - - @Override - public boolean canPutStackInSlot(ItemStack stack) { - return inv.isItemValidForSlot(slot, stack); - } - - @Override - public boolean canTakeStackFromSlot(ItemStack stack) { - return true; - } - - @Override - public boolean isItemValidForSlot(ItemStack stack) { - return inv.isItemValidForSlot(slot, stack); - } - - @Override - public ItemStack decreaseStackInSlot(int amount) { - return inv.decrStackSize(slot, amount); - } - - @Override - public int getIndex() { - return slot; - } - } -} From 69c17341be608e4963589db79792632985222e06 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Thu, 29 Jun 2017 15:38:11 +0300 Subject: [PATCH 62/89] Add blank line after copyright --- common/buildcraft/core/block/BlockSpring.java | 1 + common/buildcraft/core/gen/SpringPopulate.java | 1 + common/buildcraft/core/item/ItemMapLocation.java | 1 + common/buildcraft/core/list/ContainerList.java | 1 + common/buildcraft/core/list/GuiList.java | 1 + common/buildcraft/core/statements/ActionMachineControl.java | 1 + common/buildcraft/core/statements/ActionRedstoneOutput.java | 1 + common/buildcraft/core/statements/BCStatement.java | 1 + common/buildcraft/core/statements/CoreActionProvider.java | 1 + common/buildcraft/core/statements/CoreTriggerProvider.java | 1 + .../buildcraft/core/statements/StatementParameterDirection.java | 1 + .../core/statements/StatementParameterRedstoneLevel.java | 1 + common/buildcraft/core/statements/TriggerFluidContainer.java | 1 + .../buildcraft/core/statements/TriggerFluidContainerLevel.java | 1 + common/buildcraft/core/statements/TriggerInventory.java | 1 + common/buildcraft/core/statements/TriggerInventoryLevel.java | 1 + common/buildcraft/core/statements/TriggerMachine.java | 1 + common/buildcraft/core/statements/TriggerPower.java | 1 + common/buildcraft/core/statements/TriggerRedstoneInput.java | 1 + common/buildcraft/energy/generation/OilPopulate.java | 1 + common/buildcraft/lib/gui/button/ButtonTextureSet.java | 1 + common/buildcraft/lib/gui/button/GuiBetterButton.java | 1 + common/buildcraft/lib/gui/button/GuiButtonSmall.java | 1 + common/buildcraft/lib/gui/button/IButtonTextureSet.java | 1 + common/buildcraft/lib/gui/button/StandardButtonTextureSets.java | 1 + common/buildcraft/lib/gui/elem/ToolTip.java | 1 + common/buildcraft/lib/gui/slot/IPhantomSlot.java | 1 + common/buildcraft/lib/gui/slot/SlotBase.java | 1 + common/buildcraft/lib/gui/slot/SlotHidden.java | 1 + common/buildcraft/lib/gui/slot/SlotLimited.java | 1 + common/buildcraft/lib/gui/slot/SlotOutput.java | 1 + common/buildcraft/lib/gui/slot/SlotPhantom.java | 1 + common/buildcraft/lib/gui/slot/SlotUntouchable.java | 1 + common/buildcraft/lib/gui/slot/SlotValidated.java | 1 + common/buildcraft/lib/inventory/filter/AggregateFilter.java | 1 + common/buildcraft/lib/inventory/filter/ArrayFluidFilter.java | 1 + common/buildcraft/lib/inventory/filter/ArrayStackFilter.java | 1 + .../buildcraft/lib/inventory/filter/ArrayStackOrListFilter.java | 1 + common/buildcraft/lib/inventory/filter/CompositeFilter.java | 1 + common/buildcraft/lib/inventory/filter/CraftingFilter.java | 1 + common/buildcraft/lib/inventory/filter/InvertedStackFilter.java | 1 + common/buildcraft/lib/inventory/filter/OreStackFilter.java | 1 + .../buildcraft/lib/inventory/filter/PassThroughFluidFilter.java | 1 + .../buildcraft/lib/inventory/filter/PassThroughStackFilter.java | 1 + common/buildcraft/lib/inventory/filter/SimpleFluidFilter.java | 1 + common/buildcraft/lib/inventory/filter/StackFilter.java | 1 + common/buildcraft/lib/misc/BlockUtil.java | 1 + common/buildcraft/lib/misc/CraftingUtil.java | 1 + common/buildcraft/lib/misc/NBTUtilBC.java | 1 + common/buildcraft/lib/misc/StringUtilBC.java | 1 + common/buildcraft/lib/misc/data/AverageDouble.java | 1 + common/buildcraft/lib/misc/data/AverageInt.java | 1 + common/buildcraft/lib/misc/data/AverageLong.java | 1 + common/buildcraft/lib/misc/data/Box.java | 1 + common/buildcraft/silicon/block/BlockLaserTable.java | 1 + common/buildcraft/transport/container/ContainerDiamondPipe.java | 1 + .../buildcraft/transport/container/ContainerDiamondWoodPipe.java | 1 + common/buildcraft/transport/gui/GuiDiamondPipe.java | 1 + common/buildcraft/transport/gui/GuiDiamondWoodPipe.java | 1 + .../buildcraft/transport/pipe/flow/IPipeTransportPowerHook.java | 1 + common/buildcraft/transport/plug/FacadeStateManager.java | 1 + .../buildcraft/transport/statements/ActionExtractionPreset.java | 1 + .../buildcraft/transport/statements/ActionParameterSignal.java | 1 + common/buildcraft/transport/statements/ActionPipeDirection.java | 1 + common/buildcraft/transport/statements/ActionPipeSignal.java | 1 + common/buildcraft/transport/statements/ActionPowerPulsar.java | 1 + .../buildcraft/transport/statements/TriggerParameterSignal.java | 1 + common/buildcraft/transport/statements/TriggerPipeSignal.java | 1 + .../transport/stripes/StripesHandlerEntityInteract.java | 1 + .../transport/stripes/StripesHandlerMinecartDestroy.java | 1 + 70 files changed, 70 insertions(+) diff --git a/common/buildcraft/core/block/BlockSpring.java b/common/buildcraft/core/block/BlockSpring.java index 4e06b1d747..2c42bd7c11 100644 --- a/common/buildcraft/core/block/BlockSpring.java +++ b/common/buildcraft/core/block/BlockSpring.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.block; import java.util.Random; diff --git a/common/buildcraft/core/gen/SpringPopulate.java b/common/buildcraft/core/gen/SpringPopulate.java index 717c3bb355..2c9b60dc9f 100644 --- a/common/buildcraft/core/gen/SpringPopulate.java +++ b/common/buildcraft/core/gen/SpringPopulate.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.gen; import java.util.Random; diff --git a/common/buildcraft/core/item/ItemMapLocation.java b/common/buildcraft/core/item/ItemMapLocation.java index f971c92085..43ab9e8093 100755 --- a/common/buildcraft/core/item/ItemMapLocation.java +++ b/common/buildcraft/core/item/ItemMapLocation.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.item; import java.util.ArrayList; diff --git a/common/buildcraft/core/list/ContainerList.java b/common/buildcraft/core/list/ContainerList.java index 328c1c6cae..5bf98ce1cd 100755 --- a/common/buildcraft/core/list/ContainerList.java +++ b/common/buildcraft/core/list/ContainerList.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.list; import java.io.IOException; diff --git a/common/buildcraft/core/list/GuiList.java b/common/buildcraft/core/list/GuiList.java index 193c50e7f5..9d0e170637 100755 --- a/common/buildcraft/core/list/GuiList.java +++ b/common/buildcraft/core/list/GuiList.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.list; import java.io.IOException; diff --git a/common/buildcraft/core/statements/ActionMachineControl.java b/common/buildcraft/core/statements/ActionMachineControl.java index b5bd4483a5..e350f107de 100644 --- a/common/buildcraft/core/statements/ActionMachineControl.java +++ b/common/buildcraft/core/statements/ActionMachineControl.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import java.util.Locale; diff --git a/common/buildcraft/core/statements/ActionRedstoneOutput.java b/common/buildcraft/core/statements/ActionRedstoneOutput.java index cdb07f23cf..d786564a68 100644 --- a/common/buildcraft/core/statements/ActionRedstoneOutput.java +++ b/common/buildcraft/core/statements/ActionRedstoneOutput.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import net.minecraft.util.EnumFacing; diff --git a/common/buildcraft/core/statements/BCStatement.java b/common/buildcraft/core/statements/BCStatement.java index 8fd847fe7f..fb6aecd835 100644 --- a/common/buildcraft/core/statements/BCStatement.java +++ b/common/buildcraft/core/statements/BCStatement.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import net.minecraft.client.renderer.texture.TextureAtlasSprite; diff --git a/common/buildcraft/core/statements/CoreActionProvider.java b/common/buildcraft/core/statements/CoreActionProvider.java index 01b10ebb4d..e97290c8b3 100644 --- a/common/buildcraft/core/statements/CoreActionProvider.java +++ b/common/buildcraft/core/statements/CoreActionProvider.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import java.util.Arrays; diff --git a/common/buildcraft/core/statements/CoreTriggerProvider.java b/common/buildcraft/core/statements/CoreTriggerProvider.java index 0ae0cf91e1..0aa978cc75 100644 --- a/common/buildcraft/core/statements/CoreTriggerProvider.java +++ b/common/buildcraft/core/statements/CoreTriggerProvider.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import java.util.Collection; diff --git a/common/buildcraft/core/statements/StatementParameterDirection.java b/common/buildcraft/core/statements/StatementParameterDirection.java index 841fcf97f9..af3f4f3deb 100644 --- a/common/buildcraft/core/statements/StatementParameterDirection.java +++ b/common/buildcraft/core/statements/StatementParameterDirection.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import java.util.Objects; diff --git a/common/buildcraft/core/statements/StatementParameterRedstoneLevel.java b/common/buildcraft/core/statements/StatementParameterRedstoneLevel.java index c060aeee62..d607a5f9f6 100644 --- a/common/buildcraft/core/statements/StatementParameterRedstoneLevel.java +++ b/common/buildcraft/core/statements/StatementParameterRedstoneLevel.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import java.util.Objects; diff --git a/common/buildcraft/core/statements/TriggerFluidContainer.java b/common/buildcraft/core/statements/TriggerFluidContainer.java index e3f5cd20e6..6193a6e179 100644 --- a/common/buildcraft/core/statements/TriggerFluidContainer.java +++ b/common/buildcraft/core/statements/TriggerFluidContainer.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import java.util.Locale; diff --git a/common/buildcraft/core/statements/TriggerFluidContainerLevel.java b/common/buildcraft/core/statements/TriggerFluidContainerLevel.java index 4a6673d637..4cc8a0188f 100644 --- a/common/buildcraft/core/statements/TriggerFluidContainerLevel.java +++ b/common/buildcraft/core/statements/TriggerFluidContainerLevel.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import java.util.Locale; diff --git a/common/buildcraft/core/statements/TriggerInventory.java b/common/buildcraft/core/statements/TriggerInventory.java index 381e04ded5..e4b9ae3ed7 100644 --- a/common/buildcraft/core/statements/TriggerInventory.java +++ b/common/buildcraft/core/statements/TriggerInventory.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import java.util.Locale; diff --git a/common/buildcraft/core/statements/TriggerInventoryLevel.java b/common/buildcraft/core/statements/TriggerInventoryLevel.java index b7ae7bec9e..6dcb9b90a6 100644 --- a/common/buildcraft/core/statements/TriggerInventoryLevel.java +++ b/common/buildcraft/core/statements/TriggerInventoryLevel.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import java.util.Locale; diff --git a/common/buildcraft/core/statements/TriggerMachine.java b/common/buildcraft/core/statements/TriggerMachine.java index c4cca88854..53b44916df 100644 --- a/common/buildcraft/core/statements/TriggerMachine.java +++ b/common/buildcraft/core/statements/TriggerMachine.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import net.minecraft.tileentity.TileEntity; diff --git a/common/buildcraft/core/statements/TriggerPower.java b/common/buildcraft/core/statements/TriggerPower.java index 9e5f2053d7..96603008ad 100644 --- a/common/buildcraft/core/statements/TriggerPower.java +++ b/common/buildcraft/core/statements/TriggerPower.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import net.minecraft.tileentity.TileEntity; diff --git a/common/buildcraft/core/statements/TriggerRedstoneInput.java b/common/buildcraft/core/statements/TriggerRedstoneInput.java index 509d3e03a8..be4f55f081 100644 --- a/common/buildcraft/core/statements/TriggerRedstoneInput.java +++ b/common/buildcraft/core/statements/TriggerRedstoneInput.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.core.statements; import buildcraft.api.statements.IStatement; diff --git a/common/buildcraft/energy/generation/OilPopulate.java b/common/buildcraft/energy/generation/OilPopulate.java index 884a915f64..6999d2f441 100644 --- a/common/buildcraft/energy/generation/OilPopulate.java +++ b/common/buildcraft/energy/generation/OilPopulate.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.energy.generation; import java.util.Arrays; diff --git a/common/buildcraft/lib/gui/button/ButtonTextureSet.java b/common/buildcraft/lib/gui/button/ButtonTextureSet.java index f4df01dfde..241221ccbe 100644 --- a/common/buildcraft/lib/gui/button/ButtonTextureSet.java +++ b/common/buildcraft/lib/gui/button/ButtonTextureSet.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.button; import net.minecraft.util.ResourceLocation; diff --git a/common/buildcraft/lib/gui/button/GuiBetterButton.java b/common/buildcraft/lib/gui/button/GuiBetterButton.java index 56a46fb46b..2c4018779b 100644 --- a/common/buildcraft/lib/gui/button/GuiBetterButton.java +++ b/common/buildcraft/lib/gui/button/GuiBetterButton.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.button; import org.lwjgl.opengl.GL11; diff --git a/common/buildcraft/lib/gui/button/GuiButtonSmall.java b/common/buildcraft/lib/gui/button/GuiButtonSmall.java index d033912dbf..5b6977066d 100644 --- a/common/buildcraft/lib/gui/button/GuiButtonSmall.java +++ b/common/buildcraft/lib/gui/button/GuiButtonSmall.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.button; import net.minecraftforge.fml.relauncher.Side; diff --git a/common/buildcraft/lib/gui/button/IButtonTextureSet.java b/common/buildcraft/lib/gui/button/IButtonTextureSet.java index 7b09282846..f99e663ee6 100644 --- a/common/buildcraft/lib/gui/button/IButtonTextureSet.java +++ b/common/buildcraft/lib/gui/button/IButtonTextureSet.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.button; import net.minecraft.util.ResourceLocation; diff --git a/common/buildcraft/lib/gui/button/StandardButtonTextureSets.java b/common/buildcraft/lib/gui/button/StandardButtonTextureSets.java index fadd006e8b..5dd4d6a5e4 100644 --- a/common/buildcraft/lib/gui/button/StandardButtonTextureSets.java +++ b/common/buildcraft/lib/gui/button/StandardButtonTextureSets.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.button; import net.minecraft.util.ResourceLocation; diff --git a/common/buildcraft/lib/gui/elem/ToolTip.java b/common/buildcraft/lib/gui/elem/ToolTip.java index e253458dab..6f9427329d 100644 --- a/common/buildcraft/lib/gui/elem/ToolTip.java +++ b/common/buildcraft/lib/gui/elem/ToolTip.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.elem; import java.util.ArrayList; diff --git a/common/buildcraft/lib/gui/slot/IPhantomSlot.java b/common/buildcraft/lib/gui/slot/IPhantomSlot.java index 0b261b93c8..53f0d6e3db 100644 --- a/common/buildcraft/lib/gui/slot/IPhantomSlot.java +++ b/common/buildcraft/lib/gui/slot/IPhantomSlot.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.slot; import net.minecraft.item.ItemStack; diff --git a/common/buildcraft/lib/gui/slot/SlotBase.java b/common/buildcraft/lib/gui/slot/SlotBase.java index c6b7915faf..ad924e457b 100644 --- a/common/buildcraft/lib/gui/slot/SlotBase.java +++ b/common/buildcraft/lib/gui/slot/SlotBase.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.slot; import javax.annotation.Nonnull; diff --git a/common/buildcraft/lib/gui/slot/SlotHidden.java b/common/buildcraft/lib/gui/slot/SlotHidden.java index 168d439610..352554c885 100755 --- a/common/buildcraft/lib/gui/slot/SlotHidden.java +++ b/common/buildcraft/lib/gui/slot/SlotHidden.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.slot; import net.minecraft.inventory.IInventory; diff --git a/common/buildcraft/lib/gui/slot/SlotLimited.java b/common/buildcraft/lib/gui/slot/SlotLimited.java index 403b245f09..c4ae7fa1f3 100644 --- a/common/buildcraft/lib/gui/slot/SlotLimited.java +++ b/common/buildcraft/lib/gui/slot/SlotLimited.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.slot; import buildcraft.lib.tile.item.IItemHandlerAdv; diff --git a/common/buildcraft/lib/gui/slot/SlotOutput.java b/common/buildcraft/lib/gui/slot/SlotOutput.java index 2a775b7a2e..87bef320a3 100644 --- a/common/buildcraft/lib/gui/slot/SlotOutput.java +++ b/common/buildcraft/lib/gui/slot/SlotOutput.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.slot; import javax.annotation.Nonnull; diff --git a/common/buildcraft/lib/gui/slot/SlotPhantom.java b/common/buildcraft/lib/gui/slot/SlotPhantom.java index ef8790e8c5..18eac19fbe 100644 --- a/common/buildcraft/lib/gui/slot/SlotPhantom.java +++ b/common/buildcraft/lib/gui/slot/SlotPhantom.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.slot; import javax.annotation.Nonnull; diff --git a/common/buildcraft/lib/gui/slot/SlotUntouchable.java b/common/buildcraft/lib/gui/slot/SlotUntouchable.java index 9525bb523b..99564c7f6c 100644 --- a/common/buildcraft/lib/gui/slot/SlotUntouchable.java +++ b/common/buildcraft/lib/gui/slot/SlotUntouchable.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.slot; import javax.annotation.Nonnull; diff --git a/common/buildcraft/lib/gui/slot/SlotValidated.java b/common/buildcraft/lib/gui/slot/SlotValidated.java index 1fe1074db3..50e7d06b45 100644 --- a/common/buildcraft/lib/gui/slot/SlotValidated.java +++ b/common/buildcraft/lib/gui/slot/SlotValidated.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.gui.slot; import net.minecraft.inventory.IInventory; diff --git a/common/buildcraft/lib/inventory/filter/AggregateFilter.java b/common/buildcraft/lib/inventory/filter/AggregateFilter.java index f7688ecd1f..94bf9b0b4a 100644 --- a/common/buildcraft/lib/inventory/filter/AggregateFilter.java +++ b/common/buildcraft/lib/inventory/filter/AggregateFilter.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.inventory.filter; import javax.annotation.Nonnull; diff --git a/common/buildcraft/lib/inventory/filter/ArrayFluidFilter.java b/common/buildcraft/lib/inventory/filter/ArrayFluidFilter.java index 1f70dd2798..61da91e754 100755 --- a/common/buildcraft/lib/inventory/filter/ArrayFluidFilter.java +++ b/common/buildcraft/lib/inventory/filter/ArrayFluidFilter.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.inventory.filter; import net.minecraft.item.ItemStack; diff --git a/common/buildcraft/lib/inventory/filter/ArrayStackFilter.java b/common/buildcraft/lib/inventory/filter/ArrayStackFilter.java index 994d59a78d..45c819fa70 100644 --- a/common/buildcraft/lib/inventory/filter/ArrayStackFilter.java +++ b/common/buildcraft/lib/inventory/filter/ArrayStackFilter.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.inventory.filter; import java.util.Arrays; diff --git a/common/buildcraft/lib/inventory/filter/ArrayStackOrListFilter.java b/common/buildcraft/lib/inventory/filter/ArrayStackOrListFilter.java index 715625c504..f17501b8d0 100755 --- a/common/buildcraft/lib/inventory/filter/ArrayStackOrListFilter.java +++ b/common/buildcraft/lib/inventory/filter/ArrayStackOrListFilter.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.inventory.filter; import javax.annotation.Nonnull; diff --git a/common/buildcraft/lib/inventory/filter/CompositeFilter.java b/common/buildcraft/lib/inventory/filter/CompositeFilter.java index cc50d3b597..fb07ed7497 100755 --- a/common/buildcraft/lib/inventory/filter/CompositeFilter.java +++ b/common/buildcraft/lib/inventory/filter/CompositeFilter.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.inventory.filter; import javax.annotation.Nonnull; diff --git a/common/buildcraft/lib/inventory/filter/CraftingFilter.java b/common/buildcraft/lib/inventory/filter/CraftingFilter.java index a743ae40f0..be9c78d6c0 100644 --- a/common/buildcraft/lib/inventory/filter/CraftingFilter.java +++ b/common/buildcraft/lib/inventory/filter/CraftingFilter.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.inventory.filter; import javax.annotation.Nonnull; diff --git a/common/buildcraft/lib/inventory/filter/InvertedStackFilter.java b/common/buildcraft/lib/inventory/filter/InvertedStackFilter.java index 76af1a3fde..fbb74d24af 100644 --- a/common/buildcraft/lib/inventory/filter/InvertedStackFilter.java +++ b/common/buildcraft/lib/inventory/filter/InvertedStackFilter.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.inventory.filter; import javax.annotation.Nonnull; diff --git a/common/buildcraft/lib/inventory/filter/OreStackFilter.java b/common/buildcraft/lib/inventory/filter/OreStackFilter.java index 7a89310f61..b5037be936 100755 --- a/common/buildcraft/lib/inventory/filter/OreStackFilter.java +++ b/common/buildcraft/lib/inventory/filter/OreStackFilter.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.inventory.filter; import java.util.Arrays; diff --git a/common/buildcraft/lib/inventory/filter/PassThroughFluidFilter.java b/common/buildcraft/lib/inventory/filter/PassThroughFluidFilter.java index c948f80875..00109ebaa7 100755 --- a/common/buildcraft/lib/inventory/filter/PassThroughFluidFilter.java +++ b/common/buildcraft/lib/inventory/filter/PassThroughFluidFilter.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.inventory.filter; import net.minecraftforge.fluids.FluidStack; diff --git a/common/buildcraft/lib/inventory/filter/PassThroughStackFilter.java b/common/buildcraft/lib/inventory/filter/PassThroughStackFilter.java index 64da82a7f0..5cc2e0fbe7 100755 --- a/common/buildcraft/lib/inventory/filter/PassThroughStackFilter.java +++ b/common/buildcraft/lib/inventory/filter/PassThroughStackFilter.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.inventory.filter; import javax.annotation.Nonnull; diff --git a/common/buildcraft/lib/inventory/filter/SimpleFluidFilter.java b/common/buildcraft/lib/inventory/filter/SimpleFluidFilter.java index 2187224454..1f24ad618e 100755 --- a/common/buildcraft/lib/inventory/filter/SimpleFluidFilter.java +++ b/common/buildcraft/lib/inventory/filter/SimpleFluidFilter.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.inventory.filter; import net.minecraftforge.fluids.FluidStack; diff --git a/common/buildcraft/lib/inventory/filter/StackFilter.java b/common/buildcraft/lib/inventory/filter/StackFilter.java index cbba34f2ea..2d6bc84952 100644 --- a/common/buildcraft/lib/inventory/filter/StackFilter.java +++ b/common/buildcraft/lib/inventory/filter/StackFilter.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.inventory.filter; import javax.annotation.Nonnull; diff --git a/common/buildcraft/lib/misc/BlockUtil.java b/common/buildcraft/lib/misc/BlockUtil.java index 6b5cf1a414..4ed008127c 100644 --- a/common/buildcraft/lib/misc/BlockUtil.java +++ b/common/buildcraft/lib/misc/BlockUtil.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.misc; import java.util.Collection; diff --git a/common/buildcraft/lib/misc/CraftingUtil.java b/common/buildcraft/lib/misc/CraftingUtil.java index 90ac6e99cd..8c55fe28fc 100644 --- a/common/buildcraft/lib/misc/CraftingUtil.java +++ b/common/buildcraft/lib/misc/CraftingUtil.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.misc; import java.util.List; diff --git a/common/buildcraft/lib/misc/NBTUtilBC.java b/common/buildcraft/lib/misc/NBTUtilBC.java index 125fef33fb..43589454f9 100644 --- a/common/buildcraft/lib/misc/NBTUtilBC.java +++ b/common/buildcraft/lib/misc/NBTUtilBC.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.misc; import java.io.ByteArrayInputStream; diff --git a/common/buildcraft/lib/misc/StringUtilBC.java b/common/buildcraft/lib/misc/StringUtilBC.java index 4beb53eb10..01004ec24b 100644 --- a/common/buildcraft/lib/misc/StringUtilBC.java +++ b/common/buildcraft/lib/misc/StringUtilBC.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.misc; import java.text.DecimalFormat; diff --git a/common/buildcraft/lib/misc/data/AverageDouble.java b/common/buildcraft/lib/misc/data/AverageDouble.java index a732c2df81..90e21bb4b6 100644 --- a/common/buildcraft/lib/misc/data/AverageDouble.java +++ b/common/buildcraft/lib/misc/data/AverageDouble.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.misc.data; import net.minecraft.nbt.NBTTagCompound; diff --git a/common/buildcraft/lib/misc/data/AverageInt.java b/common/buildcraft/lib/misc/data/AverageInt.java index b7c1b2534e..c45a6db314 100644 --- a/common/buildcraft/lib/misc/data/AverageInt.java +++ b/common/buildcraft/lib/misc/data/AverageInt.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.misc.data; public class AverageInt { diff --git a/common/buildcraft/lib/misc/data/AverageLong.java b/common/buildcraft/lib/misc/data/AverageLong.java index 2f3f6c160b..e170b06ecb 100644 --- a/common/buildcraft/lib/misc/data/AverageLong.java +++ b/common/buildcraft/lib/misc/data/AverageLong.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.misc.data; import net.minecraft.nbt.NBTTagCompound; diff --git a/common/buildcraft/lib/misc/data/Box.java b/common/buildcraft/lib/misc/data/Box.java index b4a83fb56a..1ccd3c77ea 100644 --- a/common/buildcraft/lib/misc/data/Box.java +++ b/common/buildcraft/lib/misc/data/Box.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.lib.misc.data; import java.util.ArrayList; diff --git a/common/buildcraft/silicon/block/BlockLaserTable.java b/common/buildcraft/silicon/block/BlockLaserTable.java index 7e4d4962dd..3b112c1f83 100644 --- a/common/buildcraft/silicon/block/BlockLaserTable.java +++ b/common/buildcraft/silicon/block/BlockLaserTable.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.silicon.block; import net.minecraft.block.material.Material; diff --git a/common/buildcraft/transport/container/ContainerDiamondPipe.java b/common/buildcraft/transport/container/ContainerDiamondPipe.java index 90088e10cd..e072221068 100644 --- a/common/buildcraft/transport/container/ContainerDiamondPipe.java +++ b/common/buildcraft/transport/container/ContainerDiamondPipe.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.container; import net.minecraft.entity.player.EntityPlayer; diff --git a/common/buildcraft/transport/container/ContainerDiamondWoodPipe.java b/common/buildcraft/transport/container/ContainerDiamondWoodPipe.java index d82d6f6ea6..489ca75ba5 100644 --- a/common/buildcraft/transport/container/ContainerDiamondWoodPipe.java +++ b/common/buildcraft/transport/container/ContainerDiamondWoodPipe.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.container; import java.io.IOException; diff --git a/common/buildcraft/transport/gui/GuiDiamondPipe.java b/common/buildcraft/transport/gui/GuiDiamondPipe.java index 36b3406f13..a2a34aedb3 100644 --- a/common/buildcraft/transport/gui/GuiDiamondPipe.java +++ b/common/buildcraft/transport/gui/GuiDiamondPipe.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.gui; import net.minecraft.entity.player.EntityPlayer; diff --git a/common/buildcraft/transport/gui/GuiDiamondWoodPipe.java b/common/buildcraft/transport/gui/GuiDiamondWoodPipe.java index d9ed2f5ded..7380796719 100644 --- a/common/buildcraft/transport/gui/GuiDiamondWoodPipe.java +++ b/common/buildcraft/transport/gui/GuiDiamondWoodPipe.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.gui; import net.minecraft.client.renderer.GlStateManager; diff --git a/common/buildcraft/transport/pipe/flow/IPipeTransportPowerHook.java b/common/buildcraft/transport/pipe/flow/IPipeTransportPowerHook.java index 3a86b7d5d9..844dcc49be 100644 --- a/common/buildcraft/transport/pipe/flow/IPipeTransportPowerHook.java +++ b/common/buildcraft/transport/pipe/flow/IPipeTransportPowerHook.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.pipe.flow; import net.minecraft.util.EnumFacing; diff --git a/common/buildcraft/transport/plug/FacadeStateManager.java b/common/buildcraft/transport/plug/FacadeStateManager.java index 988606648d..5bcb97ce38 100644 --- a/common/buildcraft/transport/plug/FacadeStateManager.java +++ b/common/buildcraft/transport/plug/FacadeStateManager.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.plug; import java.util.ArrayList; diff --git a/common/buildcraft/transport/statements/ActionExtractionPreset.java b/common/buildcraft/transport/statements/ActionExtractionPreset.java index c8fc7aa914..379f6034e1 100644 --- a/common/buildcraft/transport/statements/ActionExtractionPreset.java +++ b/common/buildcraft/transport/statements/ActionExtractionPreset.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.statements; import net.minecraftforge.fml.relauncher.Side; diff --git a/common/buildcraft/transport/statements/ActionParameterSignal.java b/common/buildcraft/transport/statements/ActionParameterSignal.java index 0073fbf6cf..8c9a40dd7f 100644 --- a/common/buildcraft/transport/statements/ActionParameterSignal.java +++ b/common/buildcraft/transport/statements/ActionParameterSignal.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.statements; import java.util.ArrayList; diff --git a/common/buildcraft/transport/statements/ActionPipeDirection.java b/common/buildcraft/transport/statements/ActionPipeDirection.java index 23034ff990..9e61b48aec 100644 --- a/common/buildcraft/transport/statements/ActionPipeDirection.java +++ b/common/buildcraft/transport/statements/ActionPipeDirection.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.statements; import java.util.Locale; diff --git a/common/buildcraft/transport/statements/ActionPipeSignal.java b/common/buildcraft/transport/statements/ActionPipeSignal.java index 140f0c1b16..84c2db5134 100644 --- a/common/buildcraft/transport/statements/ActionPipeSignal.java +++ b/common/buildcraft/transport/statements/ActionPipeSignal.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.statements; import java.util.Locale; diff --git a/common/buildcraft/transport/statements/ActionPowerPulsar.java b/common/buildcraft/transport/statements/ActionPowerPulsar.java index f69e1c3939..290969ad76 100644 --- a/common/buildcraft/transport/statements/ActionPowerPulsar.java +++ b/common/buildcraft/transport/statements/ActionPowerPulsar.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.statements; import net.minecraft.util.EnumFacing; diff --git a/common/buildcraft/transport/statements/TriggerParameterSignal.java b/common/buildcraft/transport/statements/TriggerParameterSignal.java index 8d58db6134..7c896452b7 100644 --- a/common/buildcraft/transport/statements/TriggerParameterSignal.java +++ b/common/buildcraft/transport/statements/TriggerParameterSignal.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.statements; import java.util.ArrayList; diff --git a/common/buildcraft/transport/statements/TriggerPipeSignal.java b/common/buildcraft/transport/statements/TriggerPipeSignal.java index e9b54b2e5a..71a9797409 100644 --- a/common/buildcraft/transport/statements/TriggerPipeSignal.java +++ b/common/buildcraft/transport/statements/TriggerPipeSignal.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.statements; import java.util.Locale; diff --git a/common/buildcraft/transport/stripes/StripesHandlerEntityInteract.java b/common/buildcraft/transport/stripes/StripesHandlerEntityInteract.java index befcd435de..9b4699544d 100644 --- a/common/buildcraft/transport/stripes/StripesHandlerEntityInteract.java +++ b/common/buildcraft/transport/stripes/StripesHandlerEntityInteract.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.stripes; import java.util.Collections; diff --git a/common/buildcraft/transport/stripes/StripesHandlerMinecartDestroy.java b/common/buildcraft/transport/stripes/StripesHandlerMinecartDestroy.java index e9020ebf2c..59771af496 100644 --- a/common/buildcraft/transport/stripes/StripesHandlerMinecartDestroy.java +++ b/common/buildcraft/transport/stripes/StripesHandlerMinecartDestroy.java @@ -3,6 +3,7 @@ * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ */ + package buildcraft.transport.stripes; import java.util.Collections; From 9ab713afeae08447cc38d0208b58f7f451bdaea9 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Thu, 29 Jun 2017 16:23:45 +0300 Subject: [PATCH 63/89] Remove casts --- common/buildcraft/builders/filling/IParameter.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/common/buildcraft/builders/filling/IParameter.java b/common/buildcraft/builders/filling/IParameter.java index 59b03af429..70542f84b4 100644 --- a/common/buildcraft/builders/filling/IParameter.java +++ b/common/buildcraft/builders/filling/IParameter.java @@ -16,16 +16,20 @@ import buildcraft.lib.net.PacketBufferBC; public interface IParameter { + String name(); + + int ordinal(); + default String getParameterName() { return EnumParameter.getForClass(getClass()).name().toLowerCase(Locale.ROOT); } default String getName() { - return ((Enum) this).name().toLowerCase(Locale.ROOT); + return name().toLowerCase(Locale.ROOT); } default int getOrdinal() { - return ((Enum) this).ordinal(); + return ordinal(); } static void toBytes(ByteBuf buf, IParameter parameter) { From 3e586932ea7fdefae0b56d50432aead8515ec23e Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Thu, 29 Jun 2017 17:08:40 +0300 Subject: [PATCH 64/89] Stairs, fix #2796 --- .../builders/filling/EnumParameterFacing.java | 22 ++++++++ .../filling/EnumParameterPattern.java | 3 +- .../buildcraft/builders/filling/Filling.java | 39 +++++++++++++ .../builders/filling/FillingStairs.java | 56 +++++++++++++++++++ .../builders/filling/IParameter.java | 3 +- common/buildcraft/lib/misc/DrawingUtil.java | 4 +- 6 files changed, 123 insertions(+), 4 deletions(-) create mode 100644 common/buildcraft/builders/filling/EnumParameterFacing.java create mode 100644 common/buildcraft/builders/filling/FillingStairs.java diff --git a/common/buildcraft/builders/filling/EnumParameterFacing.java b/common/buildcraft/builders/filling/EnumParameterFacing.java new file mode 100644 index 0000000000..85d569bd64 --- /dev/null +++ b/common/buildcraft/builders/filling/EnumParameterFacing.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.builders.filling; + +import net.minecraft.util.EnumFacing; + +public enum EnumParameterFacing implements IParameter { + WEST(EnumFacing.WEST), + EAST(EnumFacing.EAST), + NORTH(EnumFacing.NORTH), + SOUTH(EnumFacing.SOUTH); + + public final EnumFacing facing; + + EnumParameterFacing(EnumFacing facing) { + this.facing = facing; + } +} diff --git a/common/buildcraft/builders/filling/EnumParameterPattern.java b/common/buildcraft/builders/filling/EnumParameterPattern.java index 34ca4e3f73..6cc527bca9 100644 --- a/common/buildcraft/builders/filling/EnumParameterPattern.java +++ b/common/buildcraft/builders/filling/EnumParameterPattern.java @@ -7,6 +7,7 @@ package buildcraft.builders.filling; public enum EnumParameterPattern implements IParameter { + STAIRS, TRIANGLE, SQUARE, PENTAGON, @@ -15,6 +16,4 @@ public enum EnumParameterPattern implements IParameter { CIRCLE, FRAME, SPHERE - // TODO: TILT - // TODO?: FLATTEN } diff --git a/common/buildcraft/builders/filling/Filling.java b/common/buildcraft/builders/filling/Filling.java index 14e982b89e..824faf8e86 100644 --- a/common/buildcraft/builders/filling/Filling.java +++ b/common/buildcraft/builders/filling/Filling.java @@ -89,6 +89,11 @@ public static Class getNextParameterClass(List return EnumParameterPattern.class; } EnumParameterPattern parameterPattern = (EnumParameterPattern) parameters.get(0); + if (parameterPattern == EnumParameterPattern.STAIRS) { + if (parameters.size() == 1) { + return EnumParameterFacing.class; + } + } if (parameterPattern == EnumParameterPattern.TRIANGLE) { if (parameters.size() == 1) { return EnumParameterType.class; @@ -221,8 +226,42 @@ public static boolean[][][] generateFillingPlanByFunctionInAxis(BlockPos size, } } + public static boolean[][][] generateFillingPlanByFunctionInFacing(BlockPos size, + EnumFacing facing, + BiConsumer function) { + Point2i flatSize; + switch (facing.getAxis()) { + case X: + flatSize = new Point2i(size.getZ(), size.getY()); + break; + case Z: + flatSize = new Point2i(size.getX(), size.getY()); + break; + default: + throw new UnsupportedOperationException(); + } + boolean[][] flatFillingPlan = new boolean[flatSize.x][flatSize.y]; + function.accept(flatSize, flatFillingPlan); + switch (facing) { + case WEST: + return generateFillingPlanByFunction(size, pos -> flatFillingPlan[pos.getZ()][pos.getY()]); + case EAST: + return generateFillingPlanByFunction(size, pos -> flatFillingPlan[size.getZ() - 1 - pos.getZ()][pos.getY()]); + case NORTH: + return generateFillingPlanByFunction(size, pos -> flatFillingPlan[pos.getX()][pos.getY()]); + case SOUTH: + return generateFillingPlanByFunction(size, pos -> flatFillingPlan[size.getX() - 1 - pos.getX()][pos.getY()]); + default: + throw new UnsupportedOperationException(); + } + } + public static boolean[][][] getFillingPlan(BlockPos size, List parameters) { EnumParameterPattern parameterPattern = (EnumParameterPattern) parameters.get(0); + if (parameterPattern == EnumParameterPattern.STAIRS) { + EnumParameterFacing parameterFacing = (EnumParameterFacing) parameters.get(1); + return FillingStairs.get(size, parameterFacing); + } if (parameterPattern == EnumParameterPattern.TRIANGLE) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); EnumParameterAxis parameterAxis = (EnumParameterAxis) parameters.get(2); diff --git a/common/buildcraft/builders/filling/FillingStairs.java b/common/buildcraft/builders/filling/FillingStairs.java new file mode 100644 index 0000000000..bb46505343 --- /dev/null +++ b/common/buildcraft/builders/filling/FillingStairs.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.builders.filling; + +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; + +import buildcraft.lib.misc.DrawingUtil; +import buildcraft.lib.misc.MathUtil; + +public class FillingStairs { + public static boolean[][][] get(BlockPos size, + EnumParameterFacing parameterFacing) { + EnumFacing side; + switch (parameterFacing.facing) { + case WEST: + side = EnumFacing.SOUTH; + break; + case EAST: + side = EnumFacing.NORTH; + break; + case NORTH: + side = EnumFacing.EAST; + break; + case SOUTH: + side = EnumFacing.WEST; + break; + default: + throw new UnsupportedOperationException(); + } + return Filling.generateFillingPlanByFunctionInFacing(size, side, (flatSize, flatFillingPlan) -> { + DrawingUtil.drawLine( + 0, + 0, + flatSize.x - 1, + flatSize.y - 1, + (x, y) -> + flatFillingPlan + [MathUtil.clamp(x, 0, flatSize.x - 1)] + [MathUtil.clamp(y, 0, flatSize.y - 1)] + = true + ); + DrawingUtil.fill( + flatFillingPlan, + flatSize.x - 1, + 0, + flatSize.x, + flatSize.y + ); + }); + } +} diff --git a/common/buildcraft/builders/filling/IParameter.java b/common/buildcraft/builders/filling/IParameter.java index 70542f84b4..81dd5652a1 100644 --- a/common/buildcraft/builders/filling/IParameter.java +++ b/common/buildcraft/builders/filling/IParameter.java @@ -54,7 +54,8 @@ static IParameter readFromNBT(NBTTagCompound nbt) { enum EnumParameter { PATTERN(EnumParameterPattern.class), TYPE(EnumParameterType.class), - AXIS(EnumParameterAxis.class); + AXIS(EnumParameterAxis.class), + FACING(EnumParameterFacing.class); public final Class clazz; diff --git a/common/buildcraft/lib/misc/DrawingUtil.java b/common/buildcraft/lib/misc/DrawingUtil.java index e2c8d0f96a..c64165318f 100644 --- a/common/buildcraft/lib/misc/DrawingUtil.java +++ b/common/buildcraft/lib/misc/DrawingUtil.java @@ -81,7 +81,9 @@ public static void drawLine(int x1, int y1, int x2, int y2, BiConsumer Math.abs(x2 - x1) || + Math.abs(currentY - y1) > Math.abs(y2 - y1)) { break; } if (error * 2 > -dx) { From a492ceff031a5607f7819ea694716fe14a9346c6 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Thu, 29 Jun 2017 18:58:57 +0300 Subject: [PATCH 65/89] Icons --- .../textures/filling/axis/x.png | Bin 0 -> 506 bytes .../textures/filling/axis/y.png | Bin 0 -> 511 bytes .../textures/filling/axis/z.png | Bin 0 -> 500 bytes .../textures/filling/facing/east.png | Bin 0 -> 217 bytes .../textures/filling/facing/north.png | Bin 0 -> 213 bytes .../textures/filling/facing/south.png | Bin 0 -> 216 bytes .../textures/filling/facing/west.png | Bin 0 -> 214 bytes .../textures/filling/pattern/circle.png | Bin 0 -> 252 bytes .../textures/filling/pattern/frame.png | Bin 0 -> 337 bytes .../textures/filling/pattern/hexagon.png | Bin 0 -> 249 bytes .../textures/filling/pattern/octagon.png | Bin 0 -> 253 bytes .../textures/filling/pattern/pentagon.png | Bin 0 -> 257 bytes .../textures/filling/pattern/sphere.png | Bin 0 -> 549 bytes .../textures/filling/pattern/square.png | Bin 0 -> 202 bytes .../textures/filling/pattern/stairs.png | Bin 0 -> 239 bytes .../textures/filling/pattern/triangle.png | Bin 0 -> 245 bytes .../textures/filling/type/empty.png | Bin 0 -> 433 bytes .../textures/filling/type/filled.png | Bin 0 -> 431 bytes .../buildcraft/builders/filling/Filling.java | 16 ++++++------- .../builders/gui/GuiFillingPlanner.java | 21 ++++++++++++------ 20 files changed, 22 insertions(+), 15 deletions(-) create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/axis/x.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/axis/y.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/axis/z.png create mode 100755 buildcraft_resources/assets/buildcraftbuilders/textures/filling/facing/east.png create mode 100755 buildcraft_resources/assets/buildcraftbuilders/textures/filling/facing/north.png create mode 100755 buildcraft_resources/assets/buildcraftbuilders/textures/filling/facing/south.png create mode 100755 buildcraft_resources/assets/buildcraftbuilders/textures/filling/facing/west.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/circle.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/frame.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/hexagon.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/octagon.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/pentagon.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/sphere.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/square.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/stairs.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/triangle.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/type/empty.png create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/filling/type/filled.png diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/axis/x.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/axis/x.png new file mode 100644 index 0000000000000000000000000000000000000000..a54963dea36b0af672bead0c63faeffdcee90821 GIT binary patch literal 506 zcmVWFU8GbZ8()Nlj2>E@cM*00CY}L_t(I%e9lwN&-<7 z#(y`aW(I={Tu6&h3@nhsxQn1aAoM70dY~R5=q+XufeS0Jg$*L8giI8TIkm_EPm9zX zM=Ge!>MqXjJNNrI2mZAjG$7ArBYD=8N%&qLEXDrS*A%cb1@

    80e wnYqe_VZ`9kex%cBLWFU8GbZ8()Nlj2>E@cM*00Co3L_t(I%e9lsO2beP zhQA{xrbVG~S6ygp7g`Xdl7-*}0zQfheIOq}@GT-pp^K`ZiyA~wkrGf$X>?%&9T%FI zw8bveS)GCT=JN9&_}36*T#1e!twx2n*H_BrGEo#!Tt3SbzO@~KAVB(kf=-9k?FRrR z;)3a^DeT>2>2|wA@J(}x=jSK1*1QBS37lz=&*!;4KTze`p$x*4lLn@lBWIed?L6Xw z$Y6sgim0q#1C9bWX_AI7N_BBT98hY!g03Kl@7cH@F5?BwtbKpE0x}xBZd87TlZk?) z&jIi~o2%3LB+r}@Ppf*i%9$qCLS0aNY2ql~v+4ETF|@&K_59lh0-S&>UaqKEFsoEg zE&nNO815^pP(T~T@apYW4d1ir+-(jy(f4d_noEEy7w%k!n@A_g> literal 0 HcmV?d00001 diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/axis/z.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/axis/z.png new file mode 100644 index 0000000000000000000000000000000000000000..01317953610db8e2e6ff580523a1a7712e1cdef1 GIT binary patch literal 500 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`Y)RhkE)4%caKYZ?lYt_f1s;*b z3=G`DAk4@xYmNj^kiEpy*OmPtn=HSs@ruZlg+L+M%#er@=ltB<)VvZPmw~~#C^fMp zHASI3vm`^o-P1Q9MK6_|fq^l?)5S5w;`G+Z2fdjB1={!bnoecnwee6t>%gknQ_iu* z;l=;DSSJ2y3N3m{5fM6~>vmL~U|rt4Zr8d5!Lu(9{;vI;R%gur&(vg-chax+Fx}%R zHfpoaKB|;^dC1wpqH^^k3qGUS4|&?>#O`O<@SK~EpD$qhwjQ^|0(VwE|M}<70TW-g za|xX6LPs7K?&^0{j;@>JTTyTCWFn<3)>~9}*}eHh8q@jDCt|lS9*)?}f1vlw-i!&a zVzy|zTQ4AHons!NjA5*|r#*W7*EZ*olYVWg z=fxnmo#BxI+WtA-hI8vCdM#}d zsP0Xu)9j4sEbyH@k&bzJy3VcsjKbLh*2~7ZpIK|)q literal 0 HcmV?d00001 diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/facing/east.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/facing/east.png new file mode 100755 index 0000000000000000000000000000000000000000..3a64248e6729eaeaf20b9c079bb1db9c50cd86af GIT binary patch literal 217 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!73?$#)eFPFv4DbnY?e6Y2H#bjCPOh)7*VorS zaNvNP2;+YShNgN3F)=ZqDvrdQNkEFRB*-tA!Qt7BG$1F<)5S5QA};jAM&4!z9=C_n z)k^s;E!peABfzb;VG{%Ql22UQ8H^QnE>836ah-hq&-}WEAg-PH69u-fTJ@OO%69gH znLpH`qM6p$guSqR;G9tQU24a9rTM>@brLq@&yd_uxK;h%Ja6`bGh(krj$SMU+Q{JP L>gTe~DWM4fkk(7+ literal 0 HcmV?d00001 diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/facing/north.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/facing/north.png new file mode 100755 index 0000000000000000000000000000000000000000..b8a7c32cb73164add5e10f5d6f78e5a618badd77 GIT binary patch literal 213 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!73?$#)eFPFv4DbnY?e6Y2H#bjCPOh)7*Vor? zs%JQG;J|+d200N%F)=Zqs_QpCivuafk|4ie28U-i(tw;KPZ!6Kia6hsihK{x@;c(j9V^pTuMWU019E+Q#7N>gTe~ HDWM4fSqDs! literal 0 HcmV?d00001 diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/facing/south.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/facing/south.png new file mode 100755 index 0000000000000000000000000000000000000000..b330c6d0cceb678874dbd6f210126c5e1bc552c8 GIT binary patch literal 216 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!73?$#)eFPFv4DbnY?e6Y2H#bjCPOh)7*VorS zaNvNP2;+YS1~Df&uo4;m>C55Y;Ww*$>D|_xz zaMhoOn;!D2UssyXboH)xLj2jhr>t8Xny+N)o@(Ft<#LAndGYVBMGjURpE?EP3Qt!* Jmvv4FO#q4GP80wD literal 0 HcmV?d00001 diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/facing/west.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/facing/west.png new file mode 100755 index 0000000000000000000000000000000000000000..13b404add9ed0c23c00cfd1f66607c8a5bfdf152 GIT binary patch literal 214 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!73?$#)eFPFv4DbnY?e6Y2H#bjCPOh)7*VorS zaNvNP2xC({!+!<_F)=Zqs?~?yg7h$!1o;IsI6S+N2IM4rx;TbZ#KoT2$lGAR<8pEF zLJ!x5HZu>N23Fw+0|&7Mr*wQ8p6D%3n%!6YaXwFMkKnzTC$6ZZ-LqPdew(kS&$;m4 z_T*3JnRymXb)D#{qIt__%Q9|C>YeLV5zm`|5sb$RZ6i@S?9XS_h9fPNZmeEX>M*MII0e0~_4`kX!V;c}hX z2QJPFcLOh)Nu{wd?!}o>oQgKaf(NAa{yXHY*mG+? YL*3CD*H*PTKS4h8boFyt=akR{07xx&zyJUM literal 0 HcmV?d00001 diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/hexagon.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/hexagon.png new file mode 100644 index 0000000000000000000000000000000000000000..c7eff85b8da4e11dd4fcdba0c879fa4782fdae98 GIT binary patch literal 249 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`Y)RhkE(|k4FwP~c5h%i0;1OBO zz`!jG!i)^F=12eq*-JcqUD+S9$@0reu30j>1t=t&84^+AoS&PUnpXnkGB7w7r6!i7 zrYMwWmSiZnd-?{X=%um)#bZ5P978Nlzn#3Bm%)(3`K^ZZ#{V4iI!i9rDs;LOAKmFZ zOI&Q&XNyviZosV9V{cdFDr{I>t@8jpwBk#Cc2{d0qcD=rjCUEU~;c;l>eW jfz8|-7!7Tg{yN9Zx1t=t&84^+AoS&PUnpXnkGB7w7r6!i7 zrYMwWmSiZnd-?{X=%um)#S=YU978Nlzn$#O*I>ZG`rPzh$8Y&Y|A>{s4cs}nzi zbHaj-gynr^1?3GhL({^3pLwGhae(3ByIt(6jNzW@9tY+w=~*M`nYg*`py~zou(vFy n4lNd)(wJ_3AzH#=_xl>A#kF#~KBn(#0=dG|)z4*}Q$iB}BZ5*P literal 0 HcmV?d00001 diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/pentagon.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/pentagon.png new file mode 100644 index 0000000000000000000000000000000000000000..761d20f251a067fcc93f46734c6bdcb9775abe1e GIT binary patch literal 257 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`Y)RhkE(|k4FwP~c5h%i0;1OBO zz`!jG!i)^F=12eq*-JcqUD+S9$@0renXWx$2NaUc42dXl&d<$F%_{+N85o?4QWHy3 zQxwWGOEMJPJ$(aG^itV@;;Ei4jv*GOw@!BCJD|Y9(yIUQzxtcm+th__buCP?+%>aM z*wv%&+zTxh2L_)_TNRr8I}fi+C|f<>wLlK$YkXtAZ<1m3W7 rrUsjp<0JQ7>tFxjywTKECD(s4y(zcYDEwYa1LP7WFU8GbZ8()Nlj2>E@cM*00D_fL_t(I%cYY|ZX+QO zMqd@sXRwdpouxkTM9O*EH}ERa%q2dT(8%x zwNOe$OFQD|);9 z=j|=E6tpO{D76+^X|%eqERAJZXsuC8dLBxFD)k%Gl)#`Huu=+LME9( zMi3E%CtdMxmliY^<_B;OvNAek_siq5800000NkvXXu0mjfps(Kn literal 0 HcmV?d00001 diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/square.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/square.png new file mode 100644 index 0000000000000000000000000000000000000000..4c6544d38a326a8113fe0368841f6392849b14b1 GIT binary patch literal 202 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`Y)RhkE(|k4FwP~c5h%i0;1OBO zz`!jG!i)^F=12eq*-JcqUD+S9$@0reJFWV)0w^S#84^+AoS&PUnpXnkGB7w7r6!i7 zrYMwWmSiZnd-?{X=%um)#q~U0978NlC;$2X-=0~up|!EG@!^}Bn^R^c<>Z_>al}DU l!ZhJZLm;z4!^BH(co;OQxTM!Sd-expq^GN&%Q~loCII*|I|~2+ literal 0 HcmV?d00001 diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/stairs.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/stairs.png new file mode 100644 index 0000000000000000000000000000000000000000..2e543cd4f4bedc41f5087447ab64fa871d4ebc69 GIT binary patch literal 239 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`Y)RhkE(|k4FwP~c5h%i0;1OBO zz`!jG!i)^F=12eq*-JcqUD+S9$@0s}+&P!e4HS~i42dXl&d<$F%_{+N85o?4QWHy3 zQxwWGOEMJPJ$(aG^itV@;=!ISjv*GOmtNj2%AmmEeDTG<)rP`hReu&ZdDO>GU$pAP znoR*NQ}{}JSkq+q-dKoi*kE07c-;Z+dS?4SJQW{I9~@0nXzF(m(Pw1qXXs{Jkn;Wx Y!_kYTYt3vDQ$Y55y85}Sb4q9e00u8dtN;K2 literal 0 HcmV?d00001 diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/triangle.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/pattern/triangle.png new file mode 100644 index 0000000000000000000000000000000000000000..4af670d6ff217bf41cebf5d4ae4328e9b0b18e67 GIT binary patch literal 245 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`Y)RhkE(|k4FwP~c5h%i0;1OBO zz`!jG!i)^F=12eq*-JcqUD+S9$@0q?X`33d1BGNWLn2C?^K)}k^GbkR1_tM%)Wnk1 z6ovB4k_-iRPv3wPy;P9GNKY5X5R21WCwuZSC~z=O{a?Q}f0a1@x(3E-BgL0IDq)jU zg)X)+a5PMx8M{E_Hk)!~ dgJW;qb2d2@)3yFfm&bx^_jL7hS?83{1OOytN8$hg literal 0 HcmV?d00001 diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/type/empty.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/type/empty.png new file mode 100644 index 0000000000000000000000000000000000000000..469ab14f3d0c5ba38e333a6d105fe675821066a1 GIT binary patch literal 433 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`Y)RhkE)4%caKYZ?lYt_f1s;*b z3=G`DAk4@xYmNj^kiEpy*OmPtn=HSIp48mUhCm_N%#er@=ltB<)VvZPmw~~#C^fMp zHASI3vm`^o-P1Q9MK6_|fq_xf)5S5w;`G|d8@-tgMUL&Ca$)ykzVNEUmJv2q5#sEE zB^MSp{ogkGg5&P6i+raNTU*p*);?hUC6n{`D$A<1{Bo5a?tS zZ`j^0ERp=D;o#SIQ4W!H3Z6pZAMEzIXlJfvbxCY7=!$8$#^opwwYi3qp>p2ho%P9# zd%XCY58Mp2pYP1km?q=w(Rq0DMX&qw8jAaNII%SZ#njrqHgUCGVg0E7r_b$wX*Eol W51KS_2~5A9p5< zKX!iMtVfk{QQ3F)-i~>?_3a|Ipw^MS^uwNb;5!m-P^Hk z)v^04T0=knery=^`cuR1)oYhpoVF{JSuXM6W0~XSOuZvsnoCqSF418-Qn*Fr_E#%M zfeSxM=k0cq?2Gpc^t!kq_t3)$Wy|C5u{(7zonxDRKlkk}iDd`>o&5a2epzX~alBt{ VQA&Bz^b}CIdAj OCTAGON_POINTS = Arrays.asList( - new Point2d(1, 0.5), - new Point2d(0.8535533905932737, 0.8535533905932737), - new Point2d(0.5, 1), - new Point2d(0.14644660940672627, 0.8535533905932737), - new Point2d(0, 0.5), - new Point2d(0.14644660940672616, 0.14644660940672627), - new Point2d(0.5, 0), - new Point2d(0.8535533905932737, 0.14644660940672616) + new Point2d(0.9619397662556434, 0.6913417161825449), + new Point2d(0.6913417161825449, 0.9619397662556434), + new Point2d(0.30865828381745514, 0.9619397662556434), + new Point2d(0.03806023374435663, 0.6913417161825449), + new Point2d(0.038060233744356575, 0.3086582838174552), + new Point2d(0.30865828381745486, 0.03806023374435674), + new Point2d(0.691341716182545, 0.038060233744356686), + new Point2d(0.9619397662556433, 0.3086582838174548) ); static { diff --git a/common/buildcraft/builders/gui/GuiFillingPlanner.java b/common/buildcraft/builders/gui/GuiFillingPlanner.java index 620184ed6a..ac5866dc41 100644 --- a/common/buildcraft/builders/gui/GuiFillingPlanner.java +++ b/common/buildcraft/builders/gui/GuiFillingPlanner.java @@ -9,8 +9,10 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.IntStream; +import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; +import buildcraft.lib.client.sprite.RawSprite; import buildcraft.lib.gui.GuiBC8; import buildcraft.lib.gui.GuiIcon; import buildcraft.lib.gui.button.GuiButtonSmall; @@ -68,19 +70,24 @@ protected void drawBackgroundLayer(float partialTicks) { @Override protected void drawForegroundLayer() { + GlStateManager.enableAlpha(); iterateParameters((i, x, y, width, height, parameter) -> new GuiIcon( + new RawSprite( new ResourceLocation( - "buildcraftbuilders:textures/filling_planner/" + - parameter.getParameterName() + - "/" + - parameter.getName() + - ".png" + "buildcraftbuilders:textures/filling/" + + parameter.getParameterName() + + "/" + + parameter.getName() + + ".png" ), 0, 0, - 16, - 16 + width, + height, + (width + height) / 2 + ), + (width + height) / 2 ).drawAt(x, y) ); iterateParameters((i, x, y, width, height, parameter) -> { From 4d762b8edfde8d37ca6a41e557ad7b413e511c89 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Thu, 29 Jun 2017 19:24:52 +0300 Subject: [PATCH 66/89] Fix stairs, triangle and exceptions while addon loading --- .../buildcraft/builders/filling/Filling.java | 19 +++--- .../builders/filling/FillingStairs.java | 40 +++++++++---- .../builders/filling/FillingTriangle.java | 58 +++++++++++++++++++ .../core/marker/volume/VolumeBox.java | 2 +- 4 files changed, 98 insertions(+), 21 deletions(-) create mode 100644 common/buildcraft/builders/filling/FillingTriangle.java diff --git a/common/buildcraft/builders/filling/Filling.java b/common/buildcraft/builders/filling/Filling.java index 92cc4ccf1d..ff05bf4041 100644 --- a/common/buildcraft/builders/filling/Filling.java +++ b/common/buildcraft/builders/filling/Filling.java @@ -27,11 +27,6 @@ @SuppressWarnings("WeakerAccess") public class Filling { private static List itemBlocks = new ArrayList<>(); - private static final List TRIANGLE_POINTS = Arrays.asList( - new Point2d(1, 0.5), - new Point2d(0.25, 0.9330127018922194), - new Point2d(0.25, 0.06698729810778076) - ); private static final List PENTAGON_POINTS = Arrays.asList( new Point2d(1, 0.5), new Point2d(0.6545084971874737, 0.9755282581475768), @@ -91,6 +86,9 @@ public static Class getNextParameterClass(List EnumParameterPattern parameterPattern = (EnumParameterPattern) parameters.get(0); if (parameterPattern == EnumParameterPattern.STAIRS) { if (parameters.size() == 1) { + return EnumParameterType.class; + } + if (parameters.size() == 2) { return EnumParameterFacing.class; } } @@ -99,7 +97,7 @@ public static Class getNextParameterClass(List return EnumParameterType.class; } if (parameters.size() == 2) { - return EnumParameterAxis.class; + return EnumParameterFacing.class; } } if (parameterPattern == EnumParameterPattern.SQUARE) { @@ -259,13 +257,14 @@ public static boolean[][][] generateFillingPlanByFunctionInFacing(BlockPos size, public static boolean[][][] getFillingPlan(BlockPos size, List parameters) { EnumParameterPattern parameterPattern = (EnumParameterPattern) parameters.get(0); if (parameterPattern == EnumParameterPattern.STAIRS) { - EnumParameterFacing parameterFacing = (EnumParameterFacing) parameters.get(1); - return FillingStairs.get(size, parameterFacing); + EnumParameterType parameterType = (EnumParameterType) parameters.get(1); + EnumParameterFacing parameterFacing = (EnumParameterFacing) parameters.get(2); + return FillingStairs.get(size, parameterType, parameterFacing); } if (parameterPattern == EnumParameterPattern.TRIANGLE) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); - EnumParameterAxis parameterAxis = (EnumParameterAxis) parameters.get(2); - return FillingPolygon.get(size, parameterType, parameterAxis, TRIANGLE_POINTS); + EnumParameterFacing parameterFacing = (EnumParameterFacing) parameters.get(2); + return FillingTriangle.get(size, parameterType, parameterFacing); } if (parameterPattern == EnumParameterPattern.SQUARE) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); diff --git a/common/buildcraft/builders/filling/FillingStairs.java b/common/buildcraft/builders/filling/FillingStairs.java index bb46505343..ef22bc43ea 100644 --- a/common/buildcraft/builders/filling/FillingStairs.java +++ b/common/buildcraft/builders/filling/FillingStairs.java @@ -6,6 +6,8 @@ package buildcraft.builders.filling; +import java.util.function.BiConsumer; + import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -14,6 +16,7 @@ public class FillingStairs { public static boolean[][][] get(BlockPos size, + EnumParameterType parameterType, EnumParameterFacing parameterFacing) { EnumFacing side; switch (parameterFacing.facing) { @@ -33,24 +36,41 @@ public static boolean[][][] get(BlockPos size, throw new UnsupportedOperationException(); } return Filling.generateFillingPlanByFunctionInFacing(size, side, (flatSize, flatFillingPlan) -> { + BiConsumer drawPixel = (x, y) -> + flatFillingPlan + [MathUtil.clamp(x, 0, flatSize.x - 1)] + [MathUtil.clamp(y, 0, flatSize.y - 1)] + = true; DrawingUtil.drawLine( 0, 0, flatSize.x - 1, - flatSize.y - 1, - (x, y) -> - flatFillingPlan - [MathUtil.clamp(x, 0, flatSize.x - 1)] - [MathUtil.clamp(y, 0, flatSize.y - 1)] - = true + 0, + drawPixel ); - DrawingUtil.fill( - flatFillingPlan, + DrawingUtil.drawLine( + flatSize.x - 1, + 0, flatSize.x - 1, + flatSize.y - 1, + drawPixel + ); + DrawingUtil.drawLine( 0, - flatSize.x, - flatSize.y + 0, + flatSize.x - 1, + flatSize.y - 1, + drawPixel ); + if (parameterType == EnumParameterType.FILLED) { + DrawingUtil.fill( + flatFillingPlan, + flatSize.x - 2, + 1, + flatSize.x, + flatSize.y + ); + } }); } } diff --git a/common/buildcraft/builders/filling/FillingTriangle.java b/common/buildcraft/builders/filling/FillingTriangle.java new file mode 100644 index 0000000000..40eb58c2d0 --- /dev/null +++ b/common/buildcraft/builders/filling/FillingTriangle.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.builders.filling; + +import java.util.function.BiConsumer; + +import net.minecraft.util.math.BlockPos; + +import buildcraft.lib.misc.DrawingUtil; +import buildcraft.lib.misc.MathUtil; + +public class FillingTriangle { + public static boolean[][][] get(BlockPos size, + EnumParameterType parameterType, + EnumParameterFacing parameterFacing) { + return Filling.generateFillingPlanByFunctionInFacing(size, parameterFacing.facing, (flatSize, flatFillingPlan) -> { + BiConsumer drawPixel = (x, y) -> + flatFillingPlan + [MathUtil.clamp(x, 0, flatSize.x - 1)] + [MathUtil.clamp(y, 0, flatSize.y - 1)] + = true; + DrawingUtil.drawLine( + 0, + 0, + flatSize.x - 1, + 0, + drawPixel + ); + DrawingUtil.drawLine( + 0, + 0, + flatSize.x / 2, + flatSize.y - 1, + drawPixel + ); + DrawingUtil.drawLine( + flatSize.x - 1, + 0, + flatSize.x % 2 == 0 ? flatSize.x / 2 : flatSize.x / 2 + 1, + flatSize.y - 1, + drawPixel + ); + if (parameterType == EnumParameterType.FILLED) { + DrawingUtil.fill( + flatFillingPlan, + flatSize.x / 2, + flatSize.y / 2, + flatSize.x, + flatSize.y + ); + } + }); + } +} diff --git a/common/buildcraft/core/marker/volume/VolumeBox.java b/common/buildcraft/core/marker/volume/VolumeBox.java index a8c9d04387..cba9bef897 100644 --- a/common/buildcraft/core/marker/volume/VolumeBox.java +++ b/common/buildcraft/core/marker/volume/VolumeBox.java @@ -73,7 +73,7 @@ public VolumeBox(NBTTagCompound nbt) { addon.readFromNBT(addonsEntryTag.getCompoundTag("addonData")); EnumAddonSlot slot = NBTUtilBC.readEnum(addonsEntryTag.getTag("slot"), EnumAddonSlot.class); addons.put(slot, addon); - } catch (InstantiationException | IllegalAccessException e) { + } catch (Exception e) { e.printStackTrace(); } }); From 6d795100ced6c8ba953182a9ff816804eee6eec1 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Fri, 30 Jun 2017 00:45:39 +0300 Subject: [PATCH 67/89] Filler without filling planner, fix #3588 --- .../textures/gui/filler.png | Bin 1228 -> 3073 bytes .../textures/gui/filling_planner.png | Bin 316 -> 2250 bytes .../buildcraft/builders/BCBuildersProxy.java | 7 +- .../builders/addon/AddonFillingPlanner.java | 40 +-- .../builders/block/BlockFiller.java | 6 + .../builders/container/ContainerFiller.java | 39 ++- .../container/ContainerFillingPlanner.java | 48 ++- .../builders/container/IContainerFilling.java | 25 ++ .../buildcraft/builders/filling/Filling.java | 34 +++ common/buildcraft/builders/gui/GuiFiller.java | 56 ---- .../buildcraft/builders/gui/GuiFilling.java | 214 ++++++++++++++ .../builders/gui/GuiFillingPlanner.java | 139 --------- .../builders/snapshot/SnapshotBuilder.java | 10 +- .../builders/tile/TileArchitectTable.java | 14 +- .../buildcraft/builders/tile/TileFiller.java | 279 +++++++++++++++--- .../lib/gui/button/GuiSpriteButton.java | 8 +- .../transport/gui/GuiEmzuliPipe_BC8.java | 4 +- 17 files changed, 635 insertions(+), 288 deletions(-) create mode 100644 common/buildcraft/builders/container/IContainerFilling.java delete mode 100644 common/buildcraft/builders/gui/GuiFiller.java create mode 100644 common/buildcraft/builders/gui/GuiFilling.java delete mode 100644 common/buildcraft/builders/gui/GuiFillingPlanner.java diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/gui/filler.png b/buildcraft_resources/assets/buildcraftbuilders/textures/gui/filler.png index 5f3763a23cea28be17fee4a7dc45844973db2c9c..c5e0070031015a3ce2e2ea48f6d3c166d0c05eb9 100755 GIT binary patch literal 3073 zcmb7G3pA8l8{Q)%x@b8eB~m9RO>shWa!+X(oQC6f8TXJ%6Drr4p$;8K?#CrE6O&s= z-+Y%_TKNipZ9s6_uD(+XFID+ zvMRCwfK7-~mM8#V&?gMYNJ9-eq|_g3q)%SNZrcX7mJm76STe%W+%f#s^k~od9RgMQT(8lm-B-OH-B@&V{$WM! z+NK~2q2|ctz=9Iiyx0CK!6=5ZffSvom!&Xp{Ni*$+z8$x+Yol(2Ab(Ru>O;Dh-&?8g z;c=g2atQf0hu0L%9&QesJ!DDAgGcf>+f2Qc&oh}!S69~;EEcQPLVe@$m-Us?(?JMS znPd72ro=4*@PBW`bn_GBqa<6?) z4|ZJ@K=7@LP#5O1{rx{g5Ry|;qVDsJs>o8=gVikf=d-Dnnbt*v!Vk1;$1=w=%&Qfw zv1xj(uG@zXZTmB=?+u<)OD41zUQaU1tnrXl1IJwcE+a3LS4)a^#a125KWhvF zme0wU(WdVat{xuA2UlNo-@L%gf(#TB5B_U}$sh*Nd)j7-Od_=8hitG0oskm2Ff=4Y zqpQYIE3?+2impg=dE%|iSz2=Dbqq6y^4ga^zkNK?PstWuY|g9|dR#r$FSa?>6iLuz z^L?#w#@Kt-MTHp|3Pb1gBM6#ZH9l^i&rrx3m_v>E4b%(|PBVg`09s#4h znlgN02P@=Bf?|*PHfE)T`SX|LkWhn5^*@A?(HE*uO!lOiZajW8S+`F}B9RCj%OYYl;T@KGln}BPpS5Tm=*p$l*@qL%B+G zg^8MxwfeLakBYnxkv3^JVjH(9XSBY?&>9*7aPbdwIGS%qV88*+Q!yi>pD%AxR8p#= z(d>y^7hIg3-)J^%@pS6l)lyw_Qe8m(V2Emt3c27WD>2dDwQgl>rY@l>EK2a`nU9~} z36V&&u-%*pFS*3!a&J-bb*`#`Z1bqOd39|01-ED8suVoFg7iL~Dx9SqvNR@2+}S^Q zCigU7^{%>%A2aKSQ8G9#KeB6uqAKkQhR#sH>@M)8u z>B76-!wTT6OE_Zu7E+f(y)GAH#-DY^tVa0q?lF!KyXud-H~ld%N?WNG)J3xb$y-a@ zuoPS&X^*F%WuTf>&pgQC4&?#PnILXN1p$~L8J$N)g^S1L{7aSE(4AM@Ft^G0*<41$ zW}ig-ipcbrN=5uGn%IXh)vh{RxHecx9nd(^{QE`T7~AHRGewJ8@576hjmg@R;IjN; zBB;oJZj37+s2vL$HW0q7by;u`Z5~?_ES$|l8&0~df3-v>=HXYD2YSDgEI=Eq8sS_i zlQ?G|{{yTtY95Y5VzZ~T3VBmNo|ztS>%u@KhNgfyxfRq0yyjY6cPMDGY;NGG6dFOYZV0R2}8^^DQSid`-}|*oLNM z1U2!d!`}5gcv)WraY-2dEl9*$D1#Em`P4DI#!@TyFrD~pw0a}*;TtFo2ECMC2R1^R z*H5Ay<>c9e?soyZ0Lm|498kk(TZCw{7BCUqE!C#JN>ml}^hbwIH&I3TT}{#CJLu;V z&YnLsR?B}X5f^HP6_#7}s2e#mwXoZxS0B{wj3bQ;{cC#O(^GyabG*zQvxN$L_)2Ei z$4J&a{^9Ckr}F&f**i-(dFCQ!`AtCX{wCRLKkuML74SS)PL($()>5zZE&3X=x13>S zsU(@T7am~NJ5D{sVJFp{W+RfuG-Z-brn+h)+$K%!D5)Lvm{abh4uKaKRIt z3GTw0fKMjS4R~=rbG0nKW-+8#2S~9l!eZN&?MHf#QOuk~i_EdKADbK!SgmJpYWQ9F zkjV`|&oBQ=dCW6CJ&CWNUt`*y&KsSFS9T_x91Sz82*mY5bBrVA&lC!MI$#eP8%r}Y zGrQTpnvf_)rPpspYWo`NHgRguwKdA=U#7+kq1Bq0Ef7;)`jgN6XdbgQ!p=9 z3_NGdhFF1ZH0;?AfP{F@j{(380CfQVG?4sTwk}Q_;Cnh zj?5E%0RE2WYaV5QheQkjI&nENmc;7W>u(YHGLkp4S&E zV-w64w%;)6OfZAa66tp-6l1RLP46kty(3jh0rM%NZi_-}qx3(c{*wY&tBp8e#qtWV zpL7?oI!4GZTzYHtS-pZmz~%O_`ZUk0K_qPYW|AR~5;56g2_Sdxljska5_yHAG$ml~ ze@igCE%6^|2-73Cri!%$!7po7J}qWPu9)=#TI7&j=r@@DAIuK16Mtfsdium$OQ+8S-0c|?9W8>oy`Z_;0ZVHcS(;0lp1-ofW`Wt9j zSy|4F>wc0td(Wx7+VWs_*E#{yy$VgXP!leUY6?ti?DD>(SHc=If%dp9m_*K67%4k`1u0DuPe7cov%GKNb?x8Tlw`~R literal 1228 zcmeAS@N?(olHy`uVBq!ia0y~yU<5K58911MRQ8&P5Fm9sz$e5NNGInlO~_tU)3!G< zdDj2`|A8WP9sBe1^Z%!&*0k-*&CSir%PTA_%*n~AZrxi@P_Xyd|FE#IhOPrKX>%hY zA}X5pWM*bI^&D*MK3H16t8K#JW5h$q$DUPXw|A!+1c6M-QA(_(^~otbxb^CI5;^uIk$XUVa<-Rva)5%mL+5@G&eVoNSYa! zF+Vna-pAS>VL;C?mIV0)GdMiEk;cHlJm1sBF{C2y$&{mg+J*wIn>9DgR_r;<(?9d$ z|NSpQOV^}axujvd`E|Jay*a&0t5bGff1OzV!gk)>aHW!Vb&&(c505{*DRpdHd6xZ| z51fn$ZX?1N$6^7eSt8eMZd-WeI5*- zCfABg|0``S@LXD;1u)bRS_ z4!2UEw_O+(^{jfG$?6bZ9~kp39~ca_r@|yneOAxccz5TTyubr_>o0lC3Ovn@Gt$)x z94Gb}6+7IhR}$$w<>4V=E>>Rjc>kX`hMZkV(J_o-FWVQN3JuzCeBkVfZ9ABHj67Fw zyFK|=J;R3>2ZrbSn1Bfd1q7tc&Fo}*5HG;M;8*tI1{;F_3&RZVn1jzw{QqCsxS4aC z`j^QKechFe?>Pk&92yuHnOHb*Gi1KKy}`mDz}B#!*Do>srOdnilbDx;ay-$|<-cTe z(!HT#_q4aqjU8gHo&E;OpkVOf7bweuz@tQ;ZSt-sIHs^d_y|%&5h#q{LRlh;>BXpm z2kIIWFub@yegTIh%nrEv2BjrfMW_4+Ds>RO#_WZmWz~n&<9#a`7@Q>9(sr&&IK2OO z@WBJhg%|9vdA~7eU|`}<022=W3=>}Io@JQu__t#9ueaw7K?WUC_`Q7F5x)$F4It0) XEs&gT>Ymzr7vvmIS3j3^P6joMIQM_v{?vyOQg#Tc_}ZOq1=U*~%Mis!zs`}*G3_qy-T{rP-ft~)0%0Hwdp zd>a4&`o2Ei!2qBIZnc0d+MtR2wKf(s+UNXG-hk%&e9Wx52YR+%@6Qb{tF70x^lhVwmr?C7Sm_{p0wduS^tm0y;z89E5oZBPt3}s;U6CudRt6SBeeA`Q) z5UN-ARNCbd{VWWdUcEATxc^LUM5771Se~bOu1uyw?zxHUzM}G0&{E%`uF=uau1Og; zEZSlXE~Bw1$9A+tB(Zstv9_J!G<@wU-_LJIoOV7TAwfi-^Tl+5;X&tU<5j^C$J+7a z6a59m$=a5d7BB#I)U_4taL7Js+*C7P9KLY5Vz8ny)Cg(V60r|tcuM&;lxdfnqZEZ_ z48st65lJ&Vwu6d8XD@)5E{{d38@lMdUj9SB2Ii>$#&Z-?gU@=@ztYc#3-N zN$2BusgBtI1USo6DAH_vcYr}zN=(!R#vt zrxYM_d{abJRQ{xa(OG=_@1#i0hDySk=hRejFN)s?!e(B=^5E<$yIdd6x4{2hlE8qj zK`u5cNi#Du6X$FmR2;)lj3z8Ey^-{krL>zpbcoJ}^(mS~TrQ3o%CA=GrkIuu)QTEg&U*4%WU!IrdW3Oj$@f&)qpa z0R-kwqiZUR`_-uZb=$Z<@vJ@hjLYL3EPhAEs-SCgx z+)7YN`w@b7H+54r8yW1EnZm<(MFZ~J9ztt7{z-6T77fMa7$jv&an zp^3@zX%5&Qr|;rSGTX|ou*#5jxsJn5Iox`omDRbKk$|Jzi}ByCA&rn`ybT2_JG)iE zq%IyFaP}u+4;8@bkyY7E${^Vw1PISY;~1qHAh3&^AXHIlQ68qe6whp@eV^NeqUE({ z%|}whP_4M_pTfuLo}RSC#O&q zXhm~ZT__=P<6pOX4K~zu^}G5PfRZ<$CUh52Slv6AxGPnH$^g=N46rEqTD$@sG4Z0;Utg>`Jj*YX6 zY%UG&l|&k2Lh8fV-LtWln)QqJ&d#q`V+9(gXyY+?nZX)sf?Wi~P}G9O=z%q^S!Ug; zSf^9d-QYgaj|Z-9C_@?YdFGSS4$44E6aqTAKKQ%ql{z!|wWP%Mzxr=!Uw{9FRcecH zTL{DG7Z;1(+%|X*7BQ^0bNfV7HD}(tI3|e3GbL^*6m|#lJJzzO-NE*Gm3HUlIB53= z8qp}sp@IzNYQ;nUp%D2reg`wkurbsmp5nbwsQjKo>3A}Yr2T|vZ#!#kmE5Slx;S~5 z;sQK>u5~s&J$?GP25kG9(Gk%c&+Zn2^!et)s?hsG^YHQWG)nL3#z$tvugA)Nnp`k$ zVxF;>eu|>dJU#75SL6;sw3_uF-Un5sZw7QJzhL;wu@xg!cLr44a;tnHC%Ub9Za zyoPpsZ~$scafq;aa5j{AeRx+Qf5wW+iJ0i1-nQeisfx*agxADL|*_N-s+1!teD5SGOSt;n#e z3RXqtZhI8tM?uc)@goPo{}^z!6(dmAdD%9;MZacbjOXe8*u2>%cARN!(z{78v@1i) n&tWU;8&enjmH+PstV;tZ=NYPp+B;5v7w3x%@P2me?2Z2dWAG>} delta 290 zcmX>lxQA(iL_G^L0|Udln605eN;JSH#5KPt*WBDZG&HokyBjEW?AWpY|NlE2KKud5 zVJr#q3ubV5b|VeMN%D4gVd!9$^#F1>3p^r=85p>QL70(Y)*K0-AbW|YuPggQMphSRc?%w&&VYYF8tE@}K z`d_El-XQhktkQ^1@7Bi}&;9 zx`_hC7#NvY{zM;m{CjnMsnpfk0SBy(F}J0j5#ZM-_HsDA(BNrMB+wl&F!>ETzj(t6 Yey`(y6H5BOIfBGJUHx3vIVCg!0Fi}by8r+H diff --git a/common/buildcraft/builders/BCBuildersProxy.java b/common/buildcraft/builders/BCBuildersProxy.java index 34d0c54680..1bb84d31db 100644 --- a/common/buildcraft/builders/BCBuildersProxy.java +++ b/common/buildcraft/builders/BCBuildersProxy.java @@ -31,8 +31,7 @@ import buildcraft.builders.gui.GuiArchitectTable; import buildcraft.builders.gui.GuiBuilder; import buildcraft.builders.gui.GuiElectronicLibrary; -import buildcraft.builders.gui.GuiFiller; -import buildcraft.builders.gui.GuiFillingPlanner; +import buildcraft.builders.gui.GuiFilling; import buildcraft.builders.gui.GuiReplacer; import buildcraft.builders.tile.TileArchitectTable; import buildcraft.builders.tile.TileBuilder; @@ -127,7 +126,7 @@ public Object getClientGuiElement(int id, EntityPlayer player, World world, int if (id == BCBuildersGuis.FILLER.ordinal()) { if (tile instanceof TileFiller) { TileFiller filler = (TileFiller) tile; - return new GuiFiller(new ContainerFiller(player, filler)); + return new GuiFilling(new ContainerFiller(player, filler)); } } if (id == BCBuildersGuis.ARCHITECT.ordinal()) { @@ -143,7 +142,7 @@ public Object getClientGuiElement(int id, EntityPlayer player, World world, int } } if (id == BCBuildersGuis.FILLING_PLANNER.ordinal()) { - return new GuiFillingPlanner(new ContainerFillingPlanner(player)); + return new GuiFilling(new ContainerFillingPlanner(player)); } return null; } diff --git a/common/buildcraft/builders/addon/AddonFillingPlanner.java b/common/buildcraft/builders/addon/AddonFillingPlanner.java index 5ffb2911f9..c21d276c42 100644 --- a/common/buildcraft/builders/addon/AddonFillingPlanner.java +++ b/common/buildcraft/builders/addon/AddonFillingPlanner.java @@ -14,8 +14,6 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.Rotation; -import net.minecraft.util.math.BlockPos; import buildcraft.lib.misc.NBTUtilBC; @@ -30,25 +28,17 @@ import buildcraft.core.marker.volume.ISingleAddon; public class AddonFillingPlanner extends Addon implements ISingleAddon { - public List parameters = new ArrayList<>(); + public final List parameters = new ArrayList<>(); public boolean inverted; public Template.BuildingInfo buildingInfo; - public boolean[][][] getFillingPlan() { - BlockPos size = box.box.size(); - boolean[][][] fillingPlan = Filling.getFillingPlan(size, parameters); - if (inverted) { - fillingPlan = Filling.invertFillingPlan(size, fillingPlan); - } - return fillingPlan; - } - public void updateBuildingInfo() { - Template template = new Template(); - template.size = box.box.size(); - template.offset = BlockPos.ORIGIN; - template.data = getFillingPlan(); - buildingInfo = template.new BuildingInfo(box.box.min(), Rotation.NONE); + buildingInfo = Filling.createBuildingInfo( + box.box.min(), + box.box.size(), + parameters, + inverted + ); } @Override @@ -64,15 +54,7 @@ public IFastAddonRenderer getRenderer() { @Override public void onAdded() { - while (true) { - Class nextParameterClass = Filling.getNextParameterClass(parameters); - if (nextParameterClass != null) { - // noinspection ConstantConditions - parameters.add(nextParameterClass.getEnumConstants()[0]); - } else { - break; - } - } + parameters.addAll(Filling.initParameters()); updateBuildingInfo(); } @@ -90,12 +72,16 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { .map(parameter -> IParameter.writeToNBT(new NBTTagCompound(), parameter)) ) ); + nbt.setBoolean("inverted", inverted); return nbt; } @Override public void readFromNBT(NBTTagCompound nbt) { - NBTUtilBC.readCompoundList(nbt.getTag("parameters")).map(IParameter::readFromNBT).forEach(parameters::add); + NBTUtilBC.readCompoundList(nbt.getTag("parameters")) + .map(IParameter::readFromNBT) + .forEach(parameters::add); + inverted = nbt.getBoolean("inverted"); updateBuildingInfo(); } diff --git a/common/buildcraft/builders/block/BlockFiller.java b/common/buildcraft/builders/block/BlockFiller.java index d95f416947..4950d006c8 100644 --- a/common/buildcraft/builders/block/BlockFiller.java +++ b/common/buildcraft/builders/block/BlockFiller.java @@ -64,6 +64,12 @@ public TileEntity createNewTileEntity(World world, int meta) { @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { + TileEntity tile = world.getTileEntity(pos); + if (tile instanceof TileFiller) { + if (!((TileFiller) tile).isValid()) { + return false; + } + } if (!world.isRemote) { BCBuildersGuis.FILLER.openGUI(player, pos); } diff --git a/common/buildcraft/builders/container/ContainerFiller.java b/common/buildcraft/builders/container/ContainerFiller.java index 1a5a33e373..79a955b9ab 100644 --- a/common/buildcraft/builders/container/ContainerFiller.java +++ b/common/buildcraft/builders/container/ContainerFiller.java @@ -6,6 +6,8 @@ package buildcraft.builders.container; +import java.util.List; + import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; @@ -15,17 +17,18 @@ import buildcraft.lib.gui.slot.SlotBase; import buildcraft.builders.filling.Filling; +import buildcraft.builders.filling.IParameter; import buildcraft.builders.tile.TileFiller; -public class ContainerFiller extends ContainerBCTile { +public class ContainerFiller extends ContainerBCTile implements IContainerFilling { public ContainerFiller(EntityPlayer player, TileFiller tile) { super(player, tile); - addFullPlayerInventory(153); + addFullPlayerInventory(108); for (int sy = 0; sy < 3; sy++) { for (int sx = 0; sx < 9; sx++) { - addSlotToContainer(new SlotBase(tile.invResources, sx + sy * 9, 8 + sx * 18, 85 + sy * 18) { + addSlotToContainer(new SlotBase(tile.invResources, sx + sy * 9, sx * 18 + 8, sy * 18 + 40) { @Override public boolean isItemValid(@Nonnull ItemStack stack) { return Filling.getItemBlocks().contains(stack.getItem()); @@ -35,6 +38,36 @@ public boolean isItemValid(@Nonnull ItemStack stack) { } } + @Override + public boolean isInverted() { + return tile.isInverted(); + } + + @Override + public void setInverted(boolean value) { + tile.sendInverted(value); + } + + @Override + public List getParameters() { + return tile.getParameters(); + } + + @Override + public void setParameters(List value) { + tile.sendParameters(value); + } + + @Override + public boolean isCanExcavate() { + return tile.isCanExcavate(); + } + + @Override + public void setCanExcavate(boolean value) { + tile.sendCanExcavate(value); + } + @Override public boolean canInteractWith(EntityPlayer player) { return true; diff --git a/common/buildcraft/builders/container/ContainerFillingPlanner.java b/common/buildcraft/builders/container/ContainerFillingPlanner.java index 5e772a9e7a..0487af7c7d 100644 --- a/common/buildcraft/builders/container/ContainerFillingPlanner.java +++ b/common/buildcraft/builders/container/ContainerFillingPlanner.java @@ -11,6 +11,8 @@ import java.util.List; import java.util.stream.IntStream; +import com.google.common.collect.ImmutableList; + import org.apache.commons.lang3.tuple.Pair; import net.minecraft.entity.player.EntityPlayer; @@ -29,13 +31,13 @@ import buildcraft.core.marker.volume.VolumeBox; import buildcraft.core.marker.volume.WorldSavedDataVolumeBoxes; -public class ContainerFillingPlanner extends ContainerBC_Neptune { +public class ContainerFillingPlanner extends ContainerBC_Neptune implements IContainerFilling { private static final IdAllocator IDS = ContainerBC_Neptune.IDS.makeChild("filling_planner"); private static final int ID_DATA = IDS.allocId("DATA"); public AddonFillingPlanner addon; - public List parameters = new ArrayList<>(); - public boolean inverted; + private List parameters = new ArrayList<>(); + private boolean inverted; public ContainerFillingPlanner(EntityPlayer player) { super(player); @@ -52,7 +54,7 @@ public IdAllocator getIdAllocator() { return IDS; } - public void sendDataToServer() { + private void sendDataToServer() { sendMessage(ID_DATA, buffer -> { buffer.writeInt(parameters.size()); parameters.forEach(parameter -> IParameter.toBytes(buffer, parameter)); @@ -66,9 +68,12 @@ public void readMessage(int id, PacketBufferBC buffer, Side side, MessageContext if (side == Side.SERVER) { if (id == ID_DATA) { parameters.clear(); - IntStream.range(0, buffer.readInt()).mapToObj(i -> IParameter.fromBytes(buffer)).forEach(parameters::add); + IntStream.range(0, buffer.readInt()) + .mapToObj(i -> IParameter.fromBytes(buffer)) + .forEach(parameters::add); inverted = buffer.readBoolean(); - addon.parameters = parameters; + addon.parameters.clear(); + addon.parameters.addAll(parameters); addon.inverted = inverted; addon.updateBuildingInfo(); WorldSavedDataVolumeBoxes.get(player.world).markDirty(); @@ -76,6 +81,37 @@ public void readMessage(int id, PacketBufferBC buffer, Side side, MessageContext } } + @Override + public boolean isInverted() { + return inverted; + } + + @Override + public void setInverted(boolean value) { + inverted = value; + sendDataToServer(); + } + + @Override + public List getParameters() { + return ImmutableList.copyOf(parameters); + } + + @Override + public void setParameters(List value) { + parameters.clear(); + parameters.addAll(value); + } + + @Override + public boolean isCanExcavate() { + return true; + } + + @Override + public void setCanExcavate(boolean value) { + } + @Override public boolean canInteractWith(EntityPlayer player) { return true; diff --git a/common/buildcraft/builders/container/IContainerFilling.java b/common/buildcraft/builders/container/IContainerFilling.java new file mode 100644 index 0000000000..a7b01e09a7 --- /dev/null +++ b/common/buildcraft/builders/container/IContainerFilling.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.builders.container; + +import java.util.List; + +import buildcraft.builders.filling.IParameter; + +public interface IContainerFilling { + boolean isInverted(); + + void setInverted(boolean value); + + List getParameters(); + + void setParameters(List value); + + boolean isCanExcavate(); + + void setCanExcavate(boolean value); +} diff --git a/common/buildcraft/builders/filling/Filling.java b/common/buildcraft/builders/filling/Filling.java index ff05bf4041..8960ba7bf2 100644 --- a/common/buildcraft/builders/filling/Filling.java +++ b/common/buildcraft/builders/filling/Filling.java @@ -17,13 +17,18 @@ import javax.vecmath.Point2d; import javax.vecmath.Point2i; +import com.google.common.collect.ImmutableList; + import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemBlockSpecial; import net.minecraft.util.EnumFacing; +import net.minecraft.util.Rotation; import net.minecraft.util.math.BlockPos; +import buildcraft.builders.snapshot.Template; + @SuppressWarnings("WeakerAccess") public class Filling { private static List itemBlocks = new ArrayList<>(); @@ -156,6 +161,35 @@ public static Class getNextParameterClass(List return null; } + public static List initParameters() { + List parameters = new ArrayList<>(); + while (true) { + Class nextParameterClass = Filling.getNextParameterClass(parameters); + if (nextParameterClass != null) { + // noinspection ConstantConditions + parameters.add(nextParameterClass.getEnumConstants()[0]); + } else { + break; + } + } + return ImmutableList.copyOf(parameters); + } + + public static Template.BuildingInfo createBuildingInfo(BlockPos basePos, + BlockPos size, + List parameters, + boolean inverted) { + Template template = new Template(); + template.size = size; + template.offset = BlockPos.ORIGIN; + boolean[][][] fillingPlan = Filling.getFillingPlan(size, parameters); + if (inverted) { + fillingPlan = Filling.invertFillingPlan(size, fillingPlan); + } + template.data = fillingPlan; + return template.new BuildingInfo(basePos, Rotation.NONE); + } + public static boolean[][][] generateFillingPlanByFunction(BlockPos size, Function function) { boolean[][][] fillingPlan = new boolean[size.getX()][size.getY()][size.getZ()]; diff --git a/common/buildcraft/builders/gui/GuiFiller.java b/common/buildcraft/builders/gui/GuiFiller.java deleted file mode 100644 index 95a5950fce..0000000000 --- a/common/buildcraft/builders/gui/GuiFiller.java +++ /dev/null @@ -1,56 +0,0 @@ -/* Copyright (c) 2016 SpaceToad and the BuildCraft team - * - * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not - * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ -package buildcraft.builders.gui; - -import net.minecraft.util.ResourceLocation; - -import buildcraft.lib.gui.GuiBC8; -import buildcraft.lib.gui.GuiIcon; -import buildcraft.lib.gui.button.GuiButtonSmall; -import buildcraft.lib.gui.button.IButtonBehaviour; -import buildcraft.lib.gui.elem.ToolTip; - -import buildcraft.builders.container.ContainerFiller; - -public class GuiFiller extends GuiBC8 { - private static final ResourceLocation TEXTURE_BASE = - new ResourceLocation("buildcraftbuilders:textures/gui/filler.png"); - private static final int SIZE_X = 176, SIZE_Y = 241; - private static final GuiIcon ICON_GUI = new GuiIcon(TEXTURE_BASE, 0, 0, SIZE_X, SIZE_Y); - - public GuiFiller(ContainerFiller container) { - super(container); - xSize = SIZE_X; - ySize = SIZE_Y; - - ledgersRight.ledgers.add(new LedgerCounters(ledgersRight, container.tile)); - } - - @Override - public void initGui() { - super.initGui(); - buttonList.add( - new GuiButtonSmall( - this, - 0, - rootElement.getX() + (xSize - 100) / 2, - rootElement.getY() + 60, - 100, - "Can Excavate" - ) - .setToolTip(ToolTip.createLocalized("gui.filler.canExcavate")) - .setBehaviour(IButtonBehaviour.TOGGLE) - .setActive(container.tile.canExcavate()) - .registerListener((button, buttonId, buttonKey) -> - container.tile.sendCanExcavate(button.isButtonActive()) - ) - ); - } - - @Override - protected void drawBackgroundLayer(float partialTicks) { - ICON_GUI.drawAt(rootElement); - } -} diff --git a/common/buildcraft/builders/gui/GuiFilling.java b/common/buildcraft/builders/gui/GuiFilling.java new file mode 100644 index 0000000000..f4d509f4c6 --- /dev/null +++ b/common/buildcraft/builders/gui/GuiFilling.java @@ -0,0 +1,214 @@ +/* Copyright (c) 2016 SpaceToad and the BuildCraft team + * + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +package buildcraft.builders.gui; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.IntStream; + +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.util.ResourceLocation; + +import buildcraft.lib.client.sprite.RawSprite; +import buildcraft.lib.gui.ContainerBC_Neptune; +import buildcraft.lib.gui.GuiBC8; +import buildcraft.lib.gui.GuiIcon; +import buildcraft.lib.gui.button.GuiSpriteButton; +import buildcraft.lib.gui.button.IButtonBehaviour; +import buildcraft.lib.gui.elem.ToolTip; + +import buildcraft.builders.container.ContainerFiller; +import buildcraft.builders.container.ContainerFillingPlanner; +import buildcraft.builders.container.IContainerFilling; +import buildcraft.builders.filling.Filling; +import buildcraft.builders.filling.IParameter; + +public class GuiFilling extends GuiBC8 { + private static final ResourceLocation FILLING_PLANNER_TEXTURE_BASE = + new ResourceLocation("buildcraftbuilders:textures/gui/filling_planner.png"); + private static final int FILLING_PLANNER_SIZE_X = 176, FILLING_PLANNER_SIZE_Y = 42; + private static final GuiIcon FILLING_PLANNER_ICON_GUI = new GuiIcon( + FILLING_PLANNER_TEXTURE_BASE, + 0, + 0, + FILLING_PLANNER_SIZE_X, + FILLING_PLANNER_SIZE_Y + ); + private static final ResourceLocation FILLER_TEXTURE_BASE = + new ResourceLocation("buildcraftbuilders:textures/gui/filler.png"); + private static final int FILLER_SIZE_X = 176, FILLER_SIZE_Y = 241; + private static final GuiIcon FILLER_ICON_GUI = new GuiIcon( + FILLER_TEXTURE_BASE, + 0, + 0, + FILLER_SIZE_X, + FILLER_SIZE_Y + ); + private final ResourceLocation textureBase; + private final GuiIcon iconGui; + + public GuiFilling(ContainerBC_Neptune container) { + super(container); + if (container instanceof ContainerFillingPlanner) { + xSize = FILLING_PLANNER_SIZE_X; + ySize = FILLING_PLANNER_SIZE_Y; + textureBase = FILLING_PLANNER_TEXTURE_BASE; + iconGui = FILLING_PLANNER_ICON_GUI; + } else if (container instanceof ContainerFiller) { + xSize = FILLER_SIZE_X; + ySize = FILLER_SIZE_Y; + textureBase = FILLER_TEXTURE_BASE; + iconGui = FILLER_ICON_GUI; + } else { + throw new IllegalArgumentException(); + } + } + + @Override + public void initGui() { + super.initGui(); + if (container instanceof ContainerFiller) { + buttonList.add( + new GuiSpriteButton( + this, + 0, + rootElement.getX() + 130, + rootElement.getY() + 18, + 16, + 16, + new GuiIcon(textureBase, 192, 0, 16, 16), + new GuiIcon(textureBase, 208, 0, 16, 16), + new GuiIcon(textureBase, 192, 16, 16, 16), + new GuiIcon(textureBase, 208, 16, 16, 16) + ) + .setToolTip(ToolTip.createLocalized("gui.filler.excavate")) + .setActive(((IContainerFilling) container).isCanExcavate()) + .registerListener((button, buttonId, buttonKey) -> { + boolean value = !((IContainerFilling) container).isCanExcavate(); + ((IContainerFilling) container).setCanExcavate(value); + ((GuiSpriteButton) button).setActive(value); + }) + ); + } + buttonList.add( + new GuiSpriteButton( + this, + 1, + rootElement.getX() + 152, + rootElement.getY() + 18, + 16, + 16, + new GuiIcon(textureBase, 224, 0, 16, 16), + new GuiIcon(textureBase, 240, 0, 16, 16), + new GuiIcon(textureBase, 224, 16, 16, 16), + new GuiIcon(textureBase, 240, 16, 16, 16) + ) + .setToolTip(ToolTip.createLocalized("gui.filler.inverted")) + .setActive(((IContainerFilling) container).isInverted()) + .registerListener((button, buttonId, buttonKey) -> { + boolean value = !((IContainerFilling) container).isInverted(); + ((IContainerFilling) container).setInverted(value); + ((GuiSpriteButton) button).setActive(value); + }) + ); + } + + private void iterateParameters(List parameters, IParameterIterator iterator) { + for (int i = 0; i < parameters.size(); i++) { + IParameter parameter = parameters.get(i); + iterator.call(i, rootElement.getX() + 8 + i * 18, rootElement.getY() + 18, 16, 16, parameter); + } + } + + @Override + protected void drawBackgroundLayer(float partialTicks) { + iconGui.drawAt(rootElement); + } + + @Override + protected void drawForegroundLayer() { + GlStateManager.enableAlpha(); + List parameters = ((IContainerFilling) container).getParameters(); + iterateParameters(parameters, (i, x, y, width, height, parameter) -> + new GuiIcon( + new RawSprite( + new ResourceLocation( + "buildcraftbuilders:textures/filling/" + + parameter.getParameterName() + + "/" + + parameter.getName() + + ".png" + ), + 0, + 0, + width, + height, + (width + height) / 2 + ), + (width + height) / 2 + ).drawAt(x, y) + ); + iterateParameters(parameters, (i, x, y, width, height, parameter) -> { + if (mouse.getX() >= x && mouse.getX() < x + width && mouse.getY() >= y && mouse.getY() < y + height) { + drawHoveringText( + Collections.singletonList(parameter.getParameterName() + ": " + parameter.getName()), + mouse.getX(), + mouse.getY() + ); + } + }); + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + AtomicBoolean found = new AtomicBoolean(false); + List parameters = ((IContainerFilling) container).getParameters(); + iterateParameters(parameters, (i, x, y, width, height, parameter) -> { + if (mouseX >= x && mouseX < x + width && mouseY >= y && mouseY < y + height) { + IParameter[] values = parameter.getClass().getEnumConstants(); + parameters.set( + i, + values[(parameter.getOrdinal() + values.length + (mouseButton == 1 ? -1 : 1)) % values.length] + ); + int j = i + 1; + while (true) { + Class nextParameterClass = Filling.getNextParameterClass( + parameters.subList( + 0, + Math.min(j, parameters.size()) + ) + ); + if (j < parameters.size()) { + if (parameters.get(j).getClass().equals(nextParameterClass)) { + j++; + continue; + } else { + IntStream.range(j, parameters.size()) + .forEach(k -> parameters.remove(parameters.size() - 1)); + } + } + if (nextParameterClass != null) { + parameters.add(nextParameterClass.getEnumConstants()[0]); + j++; + } else { + break; + } + } + ((IContainerFilling) container).setParameters(parameters); + found.set(true); + } + }); + if (!found.get()) { + super.mouseClicked(mouseX, mouseY, mouseButton); + } + } + + @FunctionalInterface + private interface IParameterIterator { + void call(int i, int x, int y, int width, int height, IParameter parameter); + } +} diff --git a/common/buildcraft/builders/gui/GuiFillingPlanner.java b/common/buildcraft/builders/gui/GuiFillingPlanner.java deleted file mode 100644 index ac5866dc41..0000000000 --- a/common/buildcraft/builders/gui/GuiFillingPlanner.java +++ /dev/null @@ -1,139 +0,0 @@ -/* Copyright (c) 2016 SpaceToad and the BuildCraft team - * - * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not - * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ -package buildcraft.builders.gui; - -import java.io.IOException; -import java.util.Collections; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.stream.IntStream; - -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.util.ResourceLocation; - -import buildcraft.lib.client.sprite.RawSprite; -import buildcraft.lib.gui.GuiBC8; -import buildcraft.lib.gui.GuiIcon; -import buildcraft.lib.gui.button.GuiButtonSmall; -import buildcraft.lib.gui.button.IButtonBehaviour; -import buildcraft.lib.gui.elem.ToolTip; - -import buildcraft.builders.container.ContainerFillingPlanner; -import buildcraft.builders.filling.Filling; -import buildcraft.builders.filling.IParameter; - -public class GuiFillingPlanner extends GuiBC8 { - private static final ResourceLocation TEXTURE_BASE = new ResourceLocation("buildcraftbuilders:textures/gui/filling_planner.png"); - private static final int SIZE_X = 176, SIZE_Y = 42; - private static final GuiIcon ICON_GUI = new GuiIcon(TEXTURE_BASE, 0, 0, SIZE_X, SIZE_Y); - - public GuiFillingPlanner(ContainerFillingPlanner container) { - super(container); - xSize = SIZE_X; - ySize = SIZE_Y; - } - - @Override - public void initGui() { - super.initGui(); - buttonList.add( - new GuiButtonSmall( - this, - 0, - rootElement.getX() + 7, - rootElement.getY() + 38, - 100, - "Inverted" - ) - .setToolTip(ToolTip.createLocalized("gui.filling_planner.inverted")) - .setBehaviour(IButtonBehaviour.TOGGLE) - .setActive(container.inverted) - .registerListener((button, buttonId, buttonKey) -> { - container.inverted = button.isButtonActive(); - container.sendDataToServer(); - }) - ); - } - - private void iterateParameters(IParameterIterator iterator) { - for (int i = 0; i < container.parameters.size(); i++) { - IParameter parameter = container.parameters.get(i); - iterator.call(i, rootElement.getX() + 8 + i * 18, rootElement.getY() + 18, 16, 16, parameter); - } - } - - @Override - protected void drawBackgroundLayer(float partialTicks) { - ICON_GUI.drawAt(rootElement); - } - - @Override - protected void drawForegroundLayer() { - GlStateManager.enableAlpha(); - iterateParameters((i, x, y, width, height, parameter) -> - new GuiIcon( - new RawSprite( - new ResourceLocation( - "buildcraftbuilders:textures/filling/" + - parameter.getParameterName() + - "/" + - parameter.getName() + - ".png" - ), - 0, - 0, - width, - height, - (width + height) / 2 - ), - (width + height) / 2 - ).drawAt(x, y) - ); - iterateParameters((i, x, y, width, height, parameter) -> { - if (mouse.getX() >= x && mouse.getX() < x + width && mouse.getY() >= y && mouse.getY() < y + height) { - drawHoveringText(Collections.singletonList(parameter.getParameterName() + ": " + parameter.getName()), mouse.getX(), mouse.getY()); - } - }); - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { - AtomicBoolean found = new AtomicBoolean(false); - iterateParameters((i, x, y, width, height, parameter) -> { - if (mouseX >= x && mouseX < x + width && mouseY >= y && mouseY < y + height) { - IParameter[] values = parameter.getClass().getEnumConstants(); - container.parameters.set(i, values[(parameter.getOrdinal() + values.length + (mouseButton == 1 ? -1 : 1)) % values.length]); - int j = i + 1; - while (true) { - Class nextParameterClass = Filling.getNextParameterClass(container.parameters.subList(0, Math.min(j, container.parameters.size()))); - if (j < container.parameters.size()) { - if (container.parameters.get(j).getClass().equals(nextParameterClass)) { - j++; - continue; - } else { - IntStream.range(j, container.parameters.size()).forEach(k -> container.parameters.remove(container.parameters.size() - 1)); - } - } - if (nextParameterClass != null) { - container.parameters.add(nextParameterClass.getEnumConstants()[0]); - j++; - } else { - break; - } - } - container.sendDataToServer(); - found.set(true); - } - }); - container.addon.updateBuildingInfo(); - if (!found.get()) { - super.mouseClicked(mouseX, mouseY, mouseButton); - } - } - - @FunctionalInterface - private interface IParameterIterator { - void call(int i, int x, int y, int width, int height, IParameter parameter); - } -} diff --git a/common/buildcraft/builders/snapshot/SnapshotBuilder.java b/common/buildcraft/builders/snapshot/SnapshotBuilder.java index 912a8a4449..8105037b98 100644 --- a/common/buildcraft/builders/snapshot/SnapshotBuilder.java +++ b/common/buildcraft/builders/snapshot/SnapshotBuilder.java @@ -324,10 +324,12 @@ public boolean tick() { } tile.getWorldBC().profiler.startSection("scan"); - for (int i = 0; i < 10; i++) { - BlockPos blockPos = toCheck.pollFirst(); - check(blockPos); - toCheck.addLast(blockPos); + if (!toCheck.isEmpty()) { + for (int i = 0; i < 10; i++) { + BlockPos blockPos = toCheck.pollFirst(); + check(blockPos); + toCheck.addLast(blockPos); + } } tile.getWorldBC().profiler.endSection(); diff --git a/common/buildcraft/builders/tile/TileArchitectTable.java b/common/buildcraft/builders/tile/TileArchitectTable.java index 30a6f5284e..5b88ae5198 100644 --- a/common/buildcraft/builders/tile/TileArchitectTable.java +++ b/common/buildcraft/builders/tile/TileArchitectTable.java @@ -98,7 +98,7 @@ public IdAllocator getIdAllocator() { @Override protected void onSlotChange(IItemHandlerModifiable handler, int slot, @Nonnull ItemStack before, - @Nonnull ItemStack after) { + @Nonnull ItemStack after) { super.onSlotChange(handler, slot, before, after); if (handler == invSnapshotIn) { if (invSnapshotOut.getStackInSlot(0).isEmpty() && after.getItem() instanceof ItemSnapshot) { @@ -123,9 +123,15 @@ public void onPlacedBy(EntityLivingBase placer, ItemStack stack) { box.setMin(volumeBox.box.min()); box.setMax(volumeBox.box.max()); isValid = true; - volumeBox.locks.add(new Lock(new Lock.Cause.CauseBlock(pos, blockState.getBlock()), - new Lock.Target.TargetResize(), new Lock.Target.TargetUsedByMachine( - Lock.Target.TargetUsedByMachine.EnumType.STRIPES_READ))); + volumeBox.locks.add( + new Lock( + new Lock.Cause.CauseBlock(pos, blockState.getBlock()), + new Lock.Target.TargetResize(), + new Lock.Target.TargetUsedByMachine( + Lock.Target.TargetUsedByMachine.EnumType.STRIPES_READ + ) + ) + ); volumeBoxes.markDirty(); sendNetworkUpdate(NET_BOX); } else if (tile instanceof IAreaProvider) { diff --git a/common/buildcraft/builders/tile/TileFiller.java b/common/buildcraft/builders/tile/TileFiller.java index 6db60dd4af..f5c9d096ab 100644 --- a/common/buildcraft/builders/tile/TileFiller.java +++ b/common/buildcraft/builders/tile/TileFiller.java @@ -7,7 +7,11 @@ package buildcraft.builders.tile; import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.UUID; +import java.util.stream.IntStream; import javax.annotation.Nonnull; @@ -15,6 +19,7 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import net.minecraft.util.math.AxisAlignedBB; @@ -26,6 +31,7 @@ import net.minecraftforge.fml.relauncher.SideOnly; import buildcraft.api.core.EnumPipePart; +import buildcraft.api.core.IAreaProvider; import buildcraft.api.inventory.IItemTransactor; import buildcraft.api.mj.MjAPI; import buildcraft.api.mj.MjBattery; @@ -34,6 +40,7 @@ import buildcraft.lib.block.BlockBCBase_Neptune; import buildcraft.lib.misc.NBTUtilBC; +import buildcraft.lib.misc.data.Box; import buildcraft.lib.misc.data.IdAllocator; import buildcraft.lib.mj.MjBatteryReciver; import buildcraft.lib.net.MessageManager; @@ -45,10 +52,12 @@ import buildcraft.builders.addon.AddonFillingPlanner; import buildcraft.builders.filling.Filling; +import buildcraft.builders.filling.IParameter; import buildcraft.builders.snapshot.ITileForTemplateBuilder; import buildcraft.builders.snapshot.SnapshotBuilder; import buildcraft.builders.snapshot.Template; import buildcraft.builders.snapshot.TemplateBuilder; +import buildcraft.core.marker.volume.ClientVolumeBoxes; import buildcraft.core.marker.volume.EnumAddonSlot; import buildcraft.core.marker.volume.Lock; import buildcraft.core.marker.volume.VolumeBox; @@ -56,23 +65,31 @@ public class TileFiller extends TileBC_Neptune implements ITickable, IDebuggable, ITileForTemplateBuilder { public static final IdAllocator IDS = TileBC_Neptune.IDS.makeChild("filler"); + public static final int NET_INVERTED = IDS.allocId("INVERTED"); + public static final int NET_PARAMETERS = IDS.allocId("PARAMETERS"); public static final int NET_CAN_EXCAVATE = IDS.allocId("CAN_EXCAVATE"); public final ItemHandlerSimple invResources = - itemManager.addInvHandler( - "resources", - new ItemHandlerSimple( - 27, - (slot, stack) -> Filling.getItemBlocks().contains(stack.getItem()), - StackInsertionFunction.getDefaultInserter(), - this::onSlotChange - ), - EnumAccess.INSERT, - EnumPipePart.VALUES - ); + itemManager.addInvHandler( + "resources", + new ItemHandlerSimple( + 27, + (slot, stack) -> Filling.getItemBlocks().contains(stack.getItem()), + StackInsertionFunction.getDefaultInserter(), + this::onSlotChange + ), + EnumAccess.INSERT, + EnumPipePart.VALUES + ); private final MjBattery battery = new MjBattery(1000 * MjAPI.MJ); private boolean canExcavate = true; - public AddonFillingPlanner addon; + private AddonFillingPlanner addon; + private final List parameters = new ArrayList<>(); + private boolean inverted; + private final Box box = new Box(); + private Template.BuildingInfo buildingInfo; + private List prevParameters; + private boolean prevInverted; public TemplateBuilder builder = new TemplateBuilder(this); public TileFiller() { @@ -87,29 +104,56 @@ public void onPlacedBy(EntityLivingBase placer, ItemStack stack) { } IBlockState blockState = world.getBlockState(pos); WorldSavedDataVolumeBoxes volumeBoxes = WorldSavedDataVolumeBoxes.get(world); - VolumeBox box = volumeBoxes.getBoxAt(pos.offset(blockState.getValue(BlockBCBase_Neptune.PROP_FACING).getOpposite())); - if (box != null) { - addon = (AddonFillingPlanner) box.addons - .values() - .stream() - .filter(AddonFillingPlanner.class::isInstance) - .findFirst() - .orElse(null); + BlockPos offsetPos = pos.offset(blockState.getValue(BlockBCBase_Neptune.PROP_FACING).getOpposite()); + VolumeBox volumeBox = volumeBoxes.getBoxAt(offsetPos); + TileEntity tile = world.getTileEntity(offsetPos); + if (volumeBox != null) { + addon = (AddonFillingPlanner) volumeBox.addons + .values() + .stream() + .filter(AddonFillingPlanner.class::isInstance) + .findFirst() + .orElse(null); if (addon != null) { - box.locks.add( - new Lock( - new Lock.Cause.CauseBlock(pos, blockState.getBlock()), - new Lock.Target.TargetResize(), - new Lock.Target.TargetAddon(addon.getSlot()), - new Lock.Target.TargetUsedByMachine( - Lock.Target.TargetUsedByMachine.EnumType.STRIPES_WRITE - ) + volumeBox.locks.add( + new Lock( + new Lock.Cause.CauseBlock(pos, blockState.getBlock()), + new Lock.Target.TargetAddon(addon.getSlot()), + new Lock.Target.TargetResize(), + new Lock.Target.TargetUsedByMachine( + Lock.Target.TargetUsedByMachine.EnumType.STRIPES_WRITE ) + ) ); volumeBoxes.markDirty(); + builder.updateSnapshot(); + } else { + box.reset(); + box.setMin(volumeBox.box.min()); + box.setMax(volumeBox.box.max()); + volumeBox.locks.add( + new Lock( + new Lock.Cause.CauseBlock(pos, blockState.getBlock()), + new Lock.Target.TargetResize(), + new Lock.Target.TargetUsedByMachine( + Lock.Target.TargetUsedByMachine.EnumType.STRIPES_WRITE + ) + ) + ); + volumeBoxes.markDirty(); + parameters.addAll(Filling.initParameters()); + updateBuildingInfo(); } + } else if (tile instanceof IAreaProvider) { + IAreaProvider provider = (IAreaProvider) tile; + box.reset(); + box.setMin(provider.min()); + box.setMax(provider.max()); + provider.removeFromWorld(); + parameters.addAll(Filling.initParameters()); + updateBuildingInfo(); } - builder.updateSnapshot(); + sendNetworkUpdate(NET_RENDER_DATA); } @Override @@ -126,22 +170,90 @@ public void invalidate() { @Override public void update() { + if (!isValid()) { + return; + } battery.tick(getWorld(), getPos()); battery.addPowerChecking(64 * MjAPI.MJ, false); - if (addon != null || world.isRemote) { - builder.tick(); + if (!world.isRemote) { + if (prevParameters == null || + !Arrays.equals(prevParameters.toArray(), getParameters().toArray()) || + prevInverted != isInverted()) { + if (prevParameters != null) { + builder.cancel(); + } + builder.updateSnapshot(); + } } + builder.tick(); + prevParameters = getParameters(); + prevInverted = isInverted(); sendNetworkUpdate(NET_RENDER_DATA); // FIXME } + public boolean isValid() { + return addon != null || box.isInitialized(); + } + + private void updateBuildingInfo() { + buildingInfo = Filling.createBuildingInfo( + box.min(), + box.size(), + parameters, + inverted + ); + } + + public void sendInverted(boolean value) { + MessageManager.sendToServer(createMessage(NET_INVERTED, buffer -> buffer.writeBoolean(value))); + } + + public void sendParameters(List value) { + MessageManager.sendToServer(createMessage(NET_PARAMETERS, buffer -> { + buffer.writeInt(value.size()); + value.forEach(parameter -> IParameter.toBytes(buffer, parameter)); + })); + } + + public void sendCanExcavate(boolean value) { + MessageManager.sendToServer(createMessage(NET_CAN_EXCAVATE, buffer -> buffer.writeBoolean(value))); + } + + public boolean isInverted() { + return addon == null ? inverted : addon.inverted; + } + + public List getParameters() { + return addon == null ? parameters : addon.parameters; + } + + public boolean isCanExcavate() { + return canExcavate; + } + @Override public void writePayload(int id, PacketBufferBC buffer, Side side) { super.writePayload(id, buffer, side); if (side == Side.SERVER) { if (id == NET_RENDER_DATA) { + box.writeData(buffer); + buffer.writeBoolean(addon != null); + if (addon != null) { + buffer.writeUniqueId(addon.box.id); + buffer.writeEnumValue(addon.getSlot()); + } builder.writeToByteBuf(buffer); + writePayload(NET_INVERTED, buffer, side); + writePayload(NET_PARAMETERS, buffer, side); writePayload(NET_CAN_EXCAVATE, buffer, side); } + if (id == NET_PARAMETERS) { + buffer.writeInt(parameters.size()); + parameters.forEach(parameter -> IParameter.toBytes(buffer, parameter)); + } + if (id == NET_INVERTED) { + buffer.writeBoolean(addon == null ? inverted : addon.inverted); + } if (id == NET_CAN_EXCAVATE) { buffer.writeBoolean(canExcavate); } @@ -153,14 +265,72 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext super.readPayload(id, buffer, side, ctx); if (side == Side.CLIENT) { if (id == NET_RENDER_DATA) { + box.readData(buffer); + if (buffer.readBoolean()) { + UUID boxId = buffer.readUniqueId(); + VolumeBox volumeBox = world.isRemote + ? ClientVolumeBoxes.INSTANCE.boxes.stream() + .filter(localVolumeBox -> localVolumeBox.id.equals(boxId)) + .findFirst() + .orElse(null) + : WorldSavedDataVolumeBoxes.get(world).getBoxFromId(boxId); + addon = (AddonFillingPlanner) volumeBox + .addons + .get(buffer.readEnumValue(EnumAddonSlot.class)); + } builder.readFromByteBuf(buffer); + readPayload(NET_INVERTED, buffer, side, ctx); + readPayload(NET_PARAMETERS, buffer, side, ctx); readPayload(NET_CAN_EXCAVATE, buffer, side, ctx); } + if (id == NET_INVERTED) { + if (addon == null) { + inverted = buffer.readBoolean(); + } else { + buffer.readBoolean(); + } + } + if (id == NET_PARAMETERS) { + if (addon == null) { + parameters.clear(); + IntStream.range(0, buffer.readInt()) + .mapToObj(i -> IParameter.fromBytes(buffer)) + .forEach(parameters::add); + } else { + IntStream.range(0, buffer.readInt()).forEach(i -> IParameter.fromBytes(buffer)); + } + } if (id == NET_CAN_EXCAVATE) { canExcavate = buffer.readBoolean(); } } if (side == Side.SERVER) { + if (id == NET_INVERTED) { + if (addon == null) { + inverted = buffer.readBoolean(); + updateBuildingInfo(); + } else { + addon.inverted = buffer.readBoolean(); + addon.updateBuildingInfo(); + WorldSavedDataVolumeBoxes.get(world).markDirty(); + } + } + if (id == NET_PARAMETERS) { + if (addon == null) { + parameters.clear(); + IntStream.range(0, buffer.readInt()) + .mapToObj(i -> IParameter.fromBytes(buffer)) + .forEach(parameters::add); + updateBuildingInfo(); + } else { + addon.parameters.clear(); + IntStream.range(0, buffer.readInt()) + .mapToObj(i -> IParameter.fromBytes(buffer)) + .forEach(addon.parameters::add); + addon.updateBuildingInfo(); + WorldSavedDataVolumeBoxes.get(world).markDirty(); + } + } if (id == NET_CAN_EXCAVATE) { canExcavate = buffer.readBoolean(); sendNetworkUpdate(NET_CAN_EXCAVATE); @@ -168,10 +338,6 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext } } - public void sendCanExcavate(boolean newValue) { - MessageManager.sendToServer(createMessage(NET_CAN_EXCAVATE, buffer -> buffer.writeBoolean(newValue))); - } - // Read-write @Override @@ -183,6 +349,25 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { nbt.setTag("addonSlot", NBTUtilBC.writeEnum(addon.getSlot())); } nbt.setBoolean("canExcavate", canExcavate); + nbt.setTag( + "parameters", + NBTUtilBC.writeCompoundList( + parameters.stream() + .map(parameter -> IParameter.writeToNBT(new NBTTagCompound(), parameter)) + ) + ); + nbt.setBoolean("inverted", inverted); + nbt.setTag("box", box.writeToNBT()); + if (prevParameters != null) { + nbt.setTag( + "prevParameters", + NBTUtilBC.writeCompoundList( + prevParameters.stream() + .map(parameter -> IParameter.writeToNBT(new NBTTagCompound(), parameter)) + ) + ); + } + nbt.setBoolean("prevInverted", prevInverted); return nbt; } @@ -192,11 +377,27 @@ public void readFromNBT(NBTTagCompound nbt) { battery.deserializeNBT(nbt.getCompoundTag("battery")); if (nbt.hasKey("addonSlot")) { addon = (AddonFillingPlanner) WorldSavedDataVolumeBoxes.get(world) - .getBoxFromId(nbt.getUniqueId("addonBoxId")) - .addons - .get(NBTUtilBC.readEnum(nbt.getTag("addonSlot"), EnumAddonSlot.class)); + .getBoxFromId(nbt.getUniqueId("addonBoxId")) + .addons + .get(NBTUtilBC.readEnum(nbt.getTag("addonSlot"), EnumAddonSlot.class)); } canExcavate = nbt.getBoolean("canExcavate"); + NBTUtilBC.readCompoundList(nbt.getTag("parameters")) + .map(IParameter::readFromNBT) + .forEach(parameters::add); + inverted = nbt.getBoolean("inverted"); + box.initialize(nbt.getCompoundTag("box")); + if (nbt.hasKey("prevParameters")) { + prevParameters = new ArrayList<>(); + NBTUtilBC.readCompoundList(nbt.getTag("prevParameters")) + .map(IParameter::readFromNBT) + .forEach(prevParameters::add); + } + prevInverted = nbt.getBoolean("prevInverted"); + if (addon == null) { + updateBuildingInfo(); + } + builder.updateSnapshot(); } // Rendering @@ -255,7 +456,7 @@ public SnapshotBuilder getBuilder() { @Override public Template.BuildingInfo getTemplateBuildingInfo() { - return addon == null ? null : addon.buildingInfo; + return addon == null ? buildingInfo : addon.buildingInfo; } @Override diff --git a/common/buildcraft/lib/gui/button/GuiSpriteButton.java b/common/buildcraft/lib/gui/button/GuiSpriteButton.java index 0518afa5b2..717e05911b 100644 --- a/common/buildcraft/lib/gui/button/GuiSpriteButton.java +++ b/common/buildcraft/lib/gui/button/GuiSpriteButton.java @@ -22,7 +22,7 @@ public class GuiSpriteButton extends GuiAbstractButton { * @param y * @param buttonStates The states. 0 should be the default (enabled, not active and not hovered), 1 should be * active, [2 is hovered and 3 is active and hovered [4 is not enabled]] */ - public GuiSpriteButton(GuiBC8 gui, int buttonId, int x, int y, ISimpleDrawable... buttonStates) { + public GuiSpriteButton(GuiBC8 gui, int buttonId, int x, int y, int width, int height, ISimpleDrawable... buttonStates) { super(gui, buttonId, x, y, ""); switch (buttonStates.length) { case 0: { @@ -64,6 +64,8 @@ public GuiSpriteButton(GuiBC8 gui, int buttonId, int x, int y, ISimpleDrawabl throw new IllegalArgumentException("Too many button states! (" + buttonStates.length + ")"); } } + this.width = width; + this.height = height; } @Override @@ -78,12 +80,12 @@ public void drawButton(Minecraft mc, int mouseX, int mouseY) { if (enabled) { if (active) { - if (hovered) { + if (isMouseOver()) { drActiveHovered.drawAt(xPosition, yPosition); } else { drActive.drawAt(xPosition, yPosition); } - } else if (hovered) { + } else if (isMouseOver()) { drHovered.drawAt(xPosition, yPosition); } else { drEnabled.drawAt(xPosition, yPosition); diff --git a/common/buildcraft/transport/gui/GuiEmzuliPipe_BC8.java b/common/buildcraft/transport/gui/GuiEmzuliPipe_BC8.java index 0dcf72ebcc..56ca0b13c4 100644 --- a/common/buildcraft/transport/gui/GuiEmzuliPipe_BC8.java +++ b/common/buildcraft/transport/gui/GuiEmzuliPipe_BC8.java @@ -114,10 +114,8 @@ public final class GuiPaintButton extends GuiSpriteButton { private final SlotIndex index; public GuiPaintButton(GuiBC8 gui, int buttonId, int x, int y, SlotIndex index) { - super(gui, buttonId, x, y, ICON_BUTTON_UP, ICON_BUTTON_DOWN); + super(gui, buttonId, x, y, 20, 20, ICON_BUTTON_UP, ICON_BUTTON_DOWN); this.index = index; - this.width = 20; - this.height = 20; setBehaviour(IButtonBehaviour.DEFAULT); } From 0e96074cb50bb0c650bb34c92807cf087747ac59 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Fri, 30 Jun 2017 01:16:21 +0300 Subject: [PATCH 68/89] Fix parameters changing --- .../buildcraft/builders/container/ContainerFillingPlanner.java | 1 + common/buildcraft/builders/gui/GuiFilling.java | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/common/buildcraft/builders/container/ContainerFillingPlanner.java b/common/buildcraft/builders/container/ContainerFillingPlanner.java index 0487af7c7d..3611e49f75 100644 --- a/common/buildcraft/builders/container/ContainerFillingPlanner.java +++ b/common/buildcraft/builders/container/ContainerFillingPlanner.java @@ -101,6 +101,7 @@ public List getParameters() { public void setParameters(List value) { parameters.clear(); parameters.addAll(value); + sendDataToServer(); } @Override diff --git a/common/buildcraft/builders/gui/GuiFilling.java b/common/buildcraft/builders/gui/GuiFilling.java index f4d509f4c6..5ac82a7f05 100644 --- a/common/buildcraft/builders/gui/GuiFilling.java +++ b/common/buildcraft/builders/gui/GuiFilling.java @@ -5,6 +5,7 @@ package buildcraft.builders.gui; import java.io.IOException; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; @@ -166,7 +167,7 @@ protected void drawForegroundLayer() { @Override protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { AtomicBoolean found = new AtomicBoolean(false); - List parameters = ((IContainerFilling) container).getParameters(); + List parameters = new ArrayList<>(((IContainerFilling) container).getParameters()); iterateParameters(parameters, (i, x, y, width, height, parameter) -> { if (mouseX >= x && mouseX < x + width && mouseY >= y && mouseY < y + height) { IParameter[] values = parameter.getClass().getEnumConstants(); From ca673e592e6875f312bdafb16fa87971eb1d371b Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Fri, 30 Jun 2017 15:21:37 +0300 Subject: [PATCH 69/89] Robot rendering --- .../buildcraftbuilders/textures/robot.png | Bin 0 -> 629 bytes .../builders/BCBuildersSprites.java | 2 + .../client/render/RenderSnapshotBuilder.java | 98 ++++++++++-------- 3 files changed, 56 insertions(+), 44 deletions(-) create mode 100644 buildcraft_resources/assets/buildcraftbuilders/textures/robot.png diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/robot.png b/buildcraft_resources/assets/buildcraftbuilders/textures/robot.png new file mode 100644 index 0000000000000000000000000000000000000000..2ea68a8c53b2dc5402403dfbf7bb8ad14afe5232 GIT binary patch literal 629 zcmeAS@N?(olHy`uVBq!ia0vp^4j|0I1|(Ny7TyC=Y)RhkE)4%caKYZ?lYt_f1s;*b z3=G`DAk4@xYmNj^kiEpy*OmPtn;Z`Z6Jz_*(?B8F%#er@=ltB<)VvZPmw~~#C^fMp zHASI3vm`^o-P1Q9MK6_|fr0U+r;B4q#jUqj&gKaPN*w!Ge_Qc#?-db_!;5^i^~mx4?G@7#_wZCpmt@9d?9!RF&1B`;z$ME{1RCAiHRT_<^%#e6@|=FY-TL#K z?`KX{o`|Zuy!!cIO`K(z}>3<#5tOpKJ57{vKgx zm~i^3jicTC?>%!jtB0&Mo9ove^wN0c*GmyU|IJR-N*5LCWO36l+46J2*G7JZ2QQzg zG3amGW;5At-(KIvfyYgrbGAA;&z632`Xw_%(7x$1Z`KHOy400#>G^+-Z7qLN*_D>} z@p7NHhA}7HGckOu|9@uu(!i+WCcaK>hDCopUoEd<{xg?7Wd)`juTEQIoFI9Ud zR_cf;@A-0T^8Eeh3#y{jX6}*P5$A#%q&yH`_S8x*bP0l+XkK5;Ynk literal 0 HcmV?d00001 diff --git a/common/buildcraft/builders/BCBuildersSprites.java b/common/buildcraft/builders/BCBuildersSprites.java index 41b99e18eb..cbd0c3a6c9 100644 --- a/common/buildcraft/builders/BCBuildersSprites.java +++ b/common/buildcraft/builders/BCBuildersSprites.java @@ -11,9 +11,11 @@ public class BCBuildersSprites { public static final SpriteHolder FILLING_PLANNER; + public static final SpriteHolder ROBOT; static { FILLING_PLANNER = getHolder("addons/filling_planner"); + ROBOT = getHolder("robot"); } private static SpriteHolder getHolder(String suffix) { diff --git a/common/buildcraft/builders/client/render/RenderSnapshotBuilder.java b/common/buildcraft/builders/client/render/RenderSnapshotBuilder.java index ad5287e604..7eb46cf717 100644 --- a/common/buildcraft/builders/client/render/RenderSnapshotBuilder.java +++ b/common/buildcraft/builders/client/render/RenderSnapshotBuilder.java @@ -8,52 +8,54 @@ import java.util.Collections; +import javax.vecmath.Point3f; + import net.minecraft.client.renderer.VertexBuffer; -import net.minecraft.client.renderer.entity.RenderEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; +import buildcraft.lib.client.model.ModelUtil; import buildcraft.lib.client.render.ItemRenderUtil; import buildcraft.lib.client.render.laser.LaserData_BC8; import buildcraft.lib.client.render.laser.LaserRenderer_BC8; import buildcraft.lib.misc.MathUtil; import buildcraft.lib.misc.VecUtil; +import buildcraft.builders.BCBuildersSprites; import buildcraft.builders.snapshot.ITileForSnapshotBuilder; import buildcraft.builders.snapshot.SnapshotBuilder; import buildcraft.core.client.BuildCraftLaserManager; public class RenderSnapshotBuilder { public static void render( - SnapshotBuilder snapshotBuilder, - World world, - BlockPos tilePos, - double x, - double y, - double z, - float partialTicks, - VertexBuffer vb + SnapshotBuilder snapshotBuilder, + World world, + BlockPos tilePos, + double x, + double y, + double z, + float partialTicks, + VertexBuffer vb ) { for (SnapshotBuilder.PlaceTask placeTask : snapshotBuilder.clientPlaceTasks) { Vec3d prevPos = snapshotBuilder.prevClientPlaceTasks.stream() - .filter(renderTaskLocal -> renderTaskLocal.pos.equals(placeTask.pos)) - .map(snapshotBuilder::getPlaceTaskItemPos) - .findFirst() - .orElse(snapshotBuilder.getPlaceTaskItemPos(snapshotBuilder.new PlaceTask(tilePos, Collections.emptyList(), 0L))); + .filter(renderTaskLocal -> renderTaskLocal.pos.equals(placeTask.pos)) + .map(snapshotBuilder::getPlaceTaskItemPos) + .findFirst() + .orElse(snapshotBuilder.getPlaceTaskItemPos(snapshotBuilder.new PlaceTask(tilePos, Collections.emptyList(), 0L))); Vec3d pos = prevPos.add(snapshotBuilder.getPlaceTaskItemPos(placeTask).subtract(prevPos).scale(partialTicks)); for (ItemStack item : placeTask.items) { ItemRenderUtil.renderItemStack( - x - tilePos.getX() + pos.xCoord, - y - tilePos.getY() + pos.yCoord, - z - tilePos.getZ() + pos.zCoord, - item, - world.getCombinedLight(new BlockPos(pos), 0), - EnumFacing.SOUTH, - vb + x - tilePos.getX() + pos.xCoord, + y - tilePos.getY() + pos.yCoord, + z - tilePos.getZ() + pos.zCoord, + item, + world.getCombinedLight(new BlockPos(pos), 0), + EnumFacing.SOUTH, + vb ); } ItemRenderUtil.endItemBatch(); @@ -65,33 +67,41 @@ public static void render( robotPos = snapshotBuilder.prevRobotPos.add(robotPos.subtract(snapshotBuilder.prevRobotPos).scale(partialTicks)); } - RenderEntity.renderOffsetAABB( - new AxisAlignedBB( - robotPos.subtract(VecUtil.VEC_HALF), - robotPos.add(VecUtil.VEC_HALF) - ), - x - tilePos.getX(), - y - tilePos.getY(), - z - tilePos.getZ() - ); - vb.setTranslation(x - tilePos.getX(), y - tilePos.getY(), z - tilePos.getZ()); + int i = 0; + for (EnumFacing face : EnumFacing.VALUES) { + ModelUtil.createFace( + face, + new Point3f((float) robotPos.xCoord, (float) robotPos.yCoord, (float) robotPos.zCoord), + new Point3f(8 / 16F, 8 / 16F, 8 / 16F), + new ModelUtil.UvFaceData( + BCBuildersSprites.ROBOT.getInterpU((i * 8) / 64D), + BCBuildersSprites.ROBOT.getInterpV(0 / 64D), + BCBuildersSprites.ROBOT.getInterpU(((i + 1) * 8) / 64D), + BCBuildersSprites.ROBOT.getInterpV(8 / 64D) + ) + ) + .lighti(world.getCombinedLight(new BlockPos(robotPos), 0)) + .render(vb); + i++; + } + for (SnapshotBuilder.BreakTask breakTask : snapshotBuilder.clientBreakTasks) { LaserRenderer_BC8.renderLaserDynamic( - new LaserData_BC8( - BuildCraftLaserManager.POWERS[(int) Math.round( - MathUtil.clamp( - breakTask.power * 1D / breakTask.getTarget(), - 0D, - 1D - ) * (BuildCraftLaserManager.POWERS.length - 1) - )], - robotPos.subtract(new Vec3d(0, 0.4, 0)), - new Vec3d(breakTask.pos).add(VecUtil.VEC_HALF), - 1 / 16D - ), - vb + new LaserData_BC8( + BuildCraftLaserManager.POWERS[(int) Math.round( + MathUtil.clamp( + breakTask.power * 1D / breakTask.getTarget(), + 0D, + 1D + ) * (BuildCraftLaserManager.POWERS.length - 1) + )], + robotPos.subtract(new Vec3d(0, 0.47, 0)), + new Vec3d(breakTask.pos).add(VecUtil.VEC_HALF), + 1 / 16D + ), + vb ); } } From 9dd9e2e48b1dcd7b8ed3bf842169eaf4cf50d9ea Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Fri, 30 Jun 2017 17:56:30 +0300 Subject: [PATCH 70/89] Fix #3680 --- common/buildcraft/builders/tile/TileQuarry.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/common/buildcraft/builders/tile/TileQuarry.java b/common/buildcraft/builders/tile/TileQuarry.java index fe47559418..0451919b2b 100644 --- a/common/buildcraft/builders/tile/TileQuarry.java +++ b/common/buildcraft/builders/tile/TileQuarry.java @@ -218,6 +218,9 @@ public void onPlacedBy(EntityLivingBase placer, ItemStack stack) { } private boolean canNotMine(BlockPos blockPos) { + if (world.getBlockState(blockPos).getBlockHardness(world, blockPos) < 0) { + return true; + } Fluid fluid = BlockUtil.getFluidWithFlowing(world, blockPos); return fluid != null && fluid.getViscosity() > 1000; } @@ -635,7 +638,7 @@ protected boolean finish() { EntityPlayer fake = BuildCraftAPI.fakePlayerProvider.getFakePlayer((WorldServer) world, getOwner(), pos); IBlockState state = world.getBlockState(breakPos); - if (state.getBlockHardness(world, breakPos) < 0) { + if (canNotMine(breakPos)) { return true; } From 4abdbc68217b48932e04c60a31b39bfc57639869 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Fri, 30 Jun 2017 20:36:25 +0300 Subject: [PATCH 71/89] Fix quarry breacking animation --- .../builders/client/render/RenderQuarry.java | 19 +- .../buildcraft/builders/tile/TileQuarry.java | 293 ++++++++++++------ common/buildcraft/lib/misc/NBTUtilBC.java | 2 +- 3 files changed, 217 insertions(+), 97 deletions(-) diff --git a/common/buildcraft/builders/client/render/RenderQuarry.java b/common/buildcraft/builders/client/render/RenderQuarry.java index 118871a692..a6c5528d0e 100644 --- a/common/buildcraft/builders/client/render/RenderQuarry.java +++ b/common/buildcraft/builders/client/render/RenderQuarry.java @@ -104,13 +104,24 @@ public void renderTileEntityAt(TileQuarry tile, double x, double y, double z, fl profiler.startSection("laser"); if (tile.currentTask != null && tile.currentTask instanceof TileQuarry.TaskBreakBlock) { - TileQuarry.TaskBreakBlock currentTask1 = (TileQuarry.TaskBreakBlock) tile.currentTask; - BlockPos pos = currentTask1.breakPos; + TileQuarry.TaskBreakBlock taskBreakBlock = (TileQuarry.TaskBreakBlock) tile.currentTask; + BlockPos pos = taskBreakBlock.breakPos; if (tile.drillPos == null) { - LaserRenderer_BC8.renderLaserStatic(new LaserData_BC8(LASER, VecUtil.convertCenter(tile.getPos()), VecUtil.convertCenter(pos), 1 / 16D)); + LaserRenderer_BC8.renderLaserStatic( + new LaserData_BC8( + LASER, + VecUtil.convertCenter(tile.getPos()), + VecUtil.convertCenter(pos), + 1 / 16D + ) + ); } else { - yOffset = (double) currentTask1.getPower() / currentTask1.getTarget(); + long power = (long) ( + taskBreakBlock.prevClientPower + + (taskBreakBlock.clientPower - taskBreakBlock.prevClientPower) * (double) partialTicks + ); + yOffset = (double) power / taskBreakBlock.getTarget(); if (yOffset < 0.9) { yOffset = 1 - yOffset / 0.9; } else { diff --git a/common/buildcraft/builders/tile/TileQuarry.java b/common/buildcraft/builders/tile/TileQuarry.java index 0451919b2b..a07425bc25 100644 --- a/common/buildcraft/builders/tile/TileQuarry.java +++ b/common/buildcraft/builders/tile/TileQuarry.java @@ -11,21 +11,19 @@ import java.util.Arrays; import java.util.Collections; import java.util.Comparator; -import java.util.HashMap; import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.function.BiFunction; +import java.util.function.Function; import java.util.function.Predicate; +import javax.annotation.Nonnull; + import com.google.common.collect.ImmutableList; -import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; @@ -247,6 +245,9 @@ public void update() { if (world.isRemote) { prevClientDrillPos = clientDrillPos; clientDrillPos = drillPos; + if (currentTask != null) { + currentTask.clientTick(); + } return; } recentPowerAverage.tick(); @@ -257,6 +258,7 @@ public void update() { BlockPos min = frameBox.min(); BlockPos max = frameBox.max(); + /* if (drillPos != null) { Map entityPoses = new HashMap<>(); @@ -272,7 +274,6 @@ public void update() { entityPoses.put(new BlockPos(drillPos.xCoord + 0.5, max.getY(), z), EnumFacing.Axis.Z); } - /* List allEntities = world.getEntitiesWithinAABB( EntityQuarryFrame.class, miningBox.getBoundingBox().union(frameBox.getBoundingBox()).expandXyz(1) @@ -293,8 +294,8 @@ public void update() { } } }); - */ } + */ if (currentTask != null) { long maxToExtract = MjAPI.MJ * 10; @@ -404,14 +405,22 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { nbt.setTag("box", miningBox.writeToNBT()); nbt.setTag("frame", frameBox.writeToNBT()); if (boxIterator != null) { - nbt.setTag("box_iterator", boxIterator.writeToNbt()); + nbt.setTag("boxIterator", boxIterator.writeToNbt()); } - nbt.setTag("mj_battery", battery.serializeNBT()); + nbt.setTag("battery", battery.serializeNBT()); if (currentTask != null) { - nbt.setTag("currentTask", EnumTaskType.writeToNbt(currentTask)); + nbt.setByte( + "currentTaskId", + (byte) Arrays.stream(EnumTaskType.values()) + .filter(type -> type.clazz == currentTask.getClass()) + .findFirst() + .orElse(null) + .ordinal() + ); + nbt.setTag("currentTaskData", currentTask.serializeNBT()); } if (drillPos != null) { - nbt.setTag("drill_pos", NBTUtilBC.writeVec3d(drillPos)); + nbt.setTag("drillPos", NBTUtilBC.writeVec3d(drillPos)); } return nbt; } @@ -421,28 +430,41 @@ public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); miningBox.initialize(nbt.getCompoundTag("box")); frameBox.initialize(nbt.getCompoundTag("frame")); - boxIterator = BoxIterator.readFromNbt(nbt.getCompoundTag("box_iterator")); - battery.deserializeNBT(nbt.getCompoundTag("mj_battery")); - + boxIterator = BoxIterator.readFromNbt(nbt.getCompoundTag("boxIterator")); + battery.deserializeNBT(nbt.getCompoundTag("battery")); if (nbt.hasKey("currentTask")) { - NBTTagCompound nbtTask = nbt.getCompoundTag("currentTask"); - currentTask = EnumTaskType.readFromNbt(this, nbtTask); + currentTask = EnumTaskType.values()[(int) nbt.getByte("currentTaskId")].supplier.apply(this); + currentTask.readFromNBT(nbt.getCompoundTag("currentTaskData")); } else { currentTask = null; } - drillPos = NBTUtilBC.readVec3d(nbt.getTag("drill_pos")); + drillPos = NBTUtilBC.readVec3d(nbt.getTag("drillPos")); } @Override public void writePayload(int id, PacketBufferBC buffer, Side side) { super.writePayload(id, buffer, side); - if (id == NET_RENDER_DATA) { - frameBox.writeData(buffer); - miningBox.writeData(buffer); - - buffer.writeBoolean(drillPos != null); - if (drillPos != null) { - MessageUtil.writeVec3d(buffer, drillPos); + if (side == Side.SERVER) { + if (id == NET_RENDER_DATA) { + frameBox.writeData(buffer); + miningBox.writeData(buffer); + buffer.writeBoolean(drillPos != null); + if (drillPos != null) { + MessageUtil.writeVec3d(buffer, drillPos); + } + buffer.writeBoolean(currentTask != null); + if (currentTask != null) { + buffer.writeByte( + (byte) Arrays.stream(EnumTaskType.values()) + .filter(type -> type.clazz == currentTask.getClass()) + .findFirst() + .orElse(null) + .ordinal() + ); + for (int i = 0; i < 2; i++) { + currentTask.toBytes(buffer); + } + } } } } @@ -450,18 +472,34 @@ public void writePayload(int id, PacketBufferBC buffer, Side side) { @Override public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext ctx) throws IOException { super.readPayload(id, buffer, side, ctx); - if (id == NET_RENDER_DATA) { - frameBox.readData(buffer); - miningBox.readData(buffer); - - if (buffer.readBoolean()) { - drillPos = MessageUtil.readVec3d(buffer); - } else { - drillPos = null; + if (side == Side.CLIENT) { + if (id == NET_RENDER_DATA) { + frameBox.readData(buffer); + miningBox.readData(buffer); + if (buffer.readBoolean()) { + drillPos = MessageUtil.readVec3d(buffer); + } else { + drillPos = null; + } + if (buffer.readBoolean()) { + int taskId = buffer.readByte(); + Task task = EnumTaskType.values()[taskId].supplier.apply(this); + task.fromBytes(buffer); + if (currentTask == null || !currentTask.equals(task)) { + currentTask = task; + Task tempTask = EnumTaskType.values()[taskId].supplier.apply(this); + tempTask.fromBytes(buffer); + } else { + currentTask.fromBytes(buffer); + } + } else { + currentTask = null; + } } } } + @SuppressWarnings("UnnecessaryLocalVariable") public Iterable getCollisionBoxes() { if (!frameBox.isInitialized() || drillPos == null) { return ImmutableList.of(); @@ -509,6 +547,7 @@ public void getDebugInfo(List left, List right, EnumFacing side) left.add("drill = " + drillPos); } + @Nonnull @Override @SideOnly(Side.CLIENT) public AxisAlignedBB getRenderBoundingBox() { @@ -522,48 +561,51 @@ public double getMaxRenderDistanceSquared() { } private enum EnumTaskType { - BREAK_BLOCK((quarry, nbt) -> quarry.new TaskBreakBlock(nbt)), - ADD_FRAME((quarry, nbt) -> quarry.new TaskAddFrame(nbt)), - MOVE_DRILL((quarry, nbt) -> quarry.new TaskMoveDrill(nbt)); + BREAK_BLOCK(TaskBreakBlock.class, quarry -> quarry.new TaskBreakBlock()), + ADD_FRAME(TaskAddFrame.class, quarry -> quarry.new TaskAddFrame()), + MOVE_DRILL(TaskMoveDrill.class, quarry -> quarry.new TaskMoveDrill()); - public static final EnumTaskType[] VALUES = values(); + public final Class clazz; + public final Function supplier; - public final BiFunction constructor; - - EnumTaskType(BiFunction constructor) { - this.constructor = constructor; - } - - public static Task readFromNbt(TileQuarry quarry, NBTTagCompound nbt) { - int idx = nbt.getByte("task_idx"); - return VALUES[idx].constructor.apply(quarry, nbt.getCompoundTag("task")); - } - - public static NBTTagCompound writeToNbt(Task task) { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setByte("task_idx", (byte) task.getType().ordinal()); - nbt.setTag("task", task.serializeNBT()); - return nbt; + EnumTaskType(Class clazz, Function supplier) { + this.clazz = clazz; + this.supplier = supplier; } } private abstract class Task { protected long power; + public long clientPower; + public long prevClientPower; + @SuppressWarnings("WeakerAccess") public Task() { } - public Task(NBTTagCompound nbt) { - power = nbt.getLong("power"); - } - public NBTTagCompound serializeNBT() { NBTTagCompound nbt = new NBTTagCompound(); nbt.setLong("power", power); return nbt; } - public abstract EnumTaskType getType(); + public void readFromNBT(NBTTagCompound nbt) { + power = nbt.getLong("power"); + } + + public void toBytes(PacketBufferBC buffer) { + buffer.writeLong(power); + } + + public void fromBytes(PacketBufferBC buffer) { + power = buffer.readLong(); + } + + @SuppressWarnings("WeakerAccess") + public void clientTick() { + prevClientPower = clientPower; + clientPower = power; + } public abstract long getTarget(); @@ -581,6 +623,7 @@ public final long getPower() { /** * @return True if this task has been completed, or cancelled. */ + @SuppressWarnings("WeakerAccess") public final boolean addPower(long microJoules) { power += microJoules; if (power >= getTarget()) { @@ -595,27 +638,40 @@ public final boolean addPower(long microJoules) { } public class TaskBreakBlock extends Task { - public final BlockPos breakPos; + public BlockPos breakPos = BlockPos.ORIGIN; - TaskBreakBlock(BlockPos pos) { - this.breakPos = pos; + @SuppressWarnings("WeakerAccess") + public TaskBreakBlock() { } - public TaskBreakBlock(NBTTagCompound nbt) { - super(nbt); - breakPos = NBTUtilBC.readBlockPos(nbt.getTag("pos")); + @SuppressWarnings("WeakerAccess") + public TaskBreakBlock(BlockPos pos) { + this.breakPos = pos; } @Override public NBTTagCompound serializeNBT() { NBTTagCompound nbt = super.serializeNBT(); - nbt.setTag("pos", NBTUtilBC.writeBlockPos(breakPos)); + nbt.setTag("breakPos", NBTUtilBC.writeBlockPos(breakPos)); return nbt; } @Override - public EnumTaskType getType() { - return EnumTaskType.BREAK_BLOCK; + public void readFromNBT(NBTTagCompound nbt) { + super.readFromNBT(nbt); + breakPos = NBTUtilBC.readBlockPos(nbt.getTag("breakPos")); + } + + @Override + public void toBytes(PacketBufferBC buffer) { + super.toBytes(buffer); + buffer.writeBlockPos(breakPos); + } + + @Override + public void fromBytes(PacketBufferBC buffer) { + super.fromBytes(buffer); + breakPos = buffer.readBlockPos(); } @Override @@ -674,30 +730,51 @@ protected boolean finish() { return false; } } + + @Override + public boolean equals(Object o) { + return this == o || + !(o == null || getClass() != o.getClass()) && + breakPos.equals(((TaskBreakBlock) o).breakPos); + + } } public class TaskAddFrame extends Task { - public final BlockPos framePos; + public BlockPos framePos = BlockPos.ORIGIN; - TaskAddFrame(BlockPos framePos) { - this.framePos = framePos; + @SuppressWarnings("WeakerAccess") + public TaskAddFrame() { } - public TaskAddFrame(NBTTagCompound nbt) { - super(nbt); - framePos = NBTUtilBC.readBlockPos(nbt.getTag("pos")); + @SuppressWarnings("WeakerAccess") + public TaskAddFrame(BlockPos framePos) { + this.framePos = framePos; } @Override public NBTTagCompound serializeNBT() { NBTTagCompound nbt = super.serializeNBT(); - nbt.setTag("pos", NBTUtilBC.writeBlockPos(framePos)); + nbt.setTag("framePos", NBTUtilBC.writeBlockPos(framePos)); return nbt; } @Override - public EnumTaskType getType() { - return EnumTaskType.ADD_FRAME; + public void readFromNBT(NBTTagCompound nbt) { + super.readFromNBT(nbt); + framePos = NBTUtilBC.readBlockPos(nbt.getTag("framePos")); + } + + @Override + public void toBytes(PacketBufferBC buffer) { + super.toBytes(buffer); + buffer.writeBlockPos(framePos); + } + + @Override + public void fromBytes(PacketBufferBC buffer) { + super.fromBytes(buffer); + framePos = buffer.readBlockPos(); } @Override @@ -717,21 +794,28 @@ protected boolean finish() { } return true; } + + @Override + public boolean equals(Object o) { + return this == o || + !(o == null || getClass() != o.getClass()) && + framePos.equals(((TaskAddFrame) o).framePos); + + } } private class TaskMoveDrill extends Task { - final Vec3d from; - final Vec3d to; + public Vec3d from = Vec3d.ZERO; + public Vec3d to = Vec3d.ZERO; - TaskMoveDrill(Vec3d from, Vec3d to) { - this.from = from; - this.to = to; + @SuppressWarnings("WeakerAccess") + public TaskMoveDrill() { } - public TaskMoveDrill(NBTTagCompound nbt) { - super(nbt); - from = NBTUtilBC.readVec3d(nbt.getTag("from")); - to = NBTUtilBC.readVec3d(nbt.getTag("to")); + @SuppressWarnings("WeakerAccess") + public TaskMoveDrill(Vec3d from, Vec3d to) { + this.from = from; + this.to = to; } @Override @@ -743,8 +827,24 @@ public NBTTagCompound serializeNBT() { } @Override - public EnumTaskType getType() { - return EnumTaskType.MOVE_DRILL; + public void readFromNBT(NBTTagCompound nbt) { + super.readFromNBT(nbt); + from = NBTUtilBC.readVec3d(nbt.getTag("from")); + to = NBTUtilBC.readVec3d(nbt.getTag("to")); + } + + @Override + public void toBytes(PacketBufferBC buffer) { + super.toBytes(buffer); + MessageUtil.writeVec3d(buffer, from); + MessageUtil.writeVec3d(buffer, to); + } + + @Override + public void fromBytes(PacketBufferBC buffer) { + super.fromBytes(buffer); + from = MessageUtil.readVec3d(buffer); + to = MessageUtil.readVec3d(buffer); } @Override @@ -752,11 +852,11 @@ public long getTarget() { return (long) (from.distanceTo(to) * 20 * MjAPI.MJ); } + /* private void moveEntities(Vec3d oldDrillPos) { if (drillPos.yCoord < oldDrillPos.yCoord) { return; } - /* List moved = new ArrayList<>(); for (EntityQuarryFrame entityQuarryFrame : world.getEntitiesWithinAABB( EntityQuarryFrame.class, @@ -776,23 +876,32 @@ private void moveEntities(Vec3d oldDrillPos) { } } } - */ } + */ @Override protected boolean onReceivePower() { - Vec3d oldDrillPos = drillPos; +// Vec3d oldDrillPos = drillPos; drillPos = from.scale(1 - power / (double) getTarget()).add(to.scale(power / (double) getTarget())); - moveEntities(oldDrillPos); +// moveEntities(oldDrillPos); return false; } @Override protected boolean finish() { - Vec3d oldDrillPos = drillPos; +// Vec3d oldDrillPos = drillPos; drillPos = to; - moveEntities(oldDrillPos); +// moveEntities(oldDrillPos); return true; } + + @Override + public boolean equals(Object o) { + return this == o || + !(o == null || getClass() != o.getClass()) && + from.equals(((TaskMoveDrill) o).from) && + to.equals(((TaskMoveDrill) o).to); + + } } } diff --git a/common/buildcraft/lib/misc/NBTUtilBC.java b/common/buildcraft/lib/misc/NBTUtilBC.java index 43589454f9..75f691ee36 100644 --- a/common/buildcraft/lib/misc/NBTUtilBC.java +++ b/common/buildcraft/lib/misc/NBTUtilBC.java @@ -117,7 +117,7 @@ public static NBTTagCompound writeBlockPosAsCompound(BlockPos pos) { } public static BlockPos readBlockPos(NBTBase base) { - if (base == null) return null; + if (base == null) return BlockPos.ORIGIN; switch (base.getId()) { case Constants.NBT.TAG_INT_ARRAY: { int[] array = ((NBTTagIntArray) base).getIntArray(); From 6df4093e35ee8746f32bd3ecb547758cd803e7be Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Fri, 30 Jun 2017 21:56:23 +0300 Subject: [PATCH 72/89] Fix nullable readBlockPos --- common/buildcraft/lib/misc/data/Box.java | 4 ++-- common/buildcraft/lib/misc/data/BoxIterator.java | 6 +++--- common/buildcraft/silicon/tile/TileLaser.java | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/common/buildcraft/lib/misc/data/Box.java b/common/buildcraft/lib/misc/data/Box.java index 1ccd3c77ea..5e2975d608 100644 --- a/common/buildcraft/lib/misc/data/Box.java +++ b/common/buildcraft/lib/misc/data/Box.java @@ -97,8 +97,8 @@ public void initialize(NBTTagCompound nbt) { min = new BlockPos(nbt.getInteger("xMin"), nbt.getInteger("yMin"), nbt.getInteger("zMin")); max = new BlockPos(nbt.getInteger("xMax"), nbt.getInteger("yMax"), nbt.getInteger("zMax")); } else { - min = NBTUtilBC.readBlockPos(nbt.getTag("min")); - max = NBTUtilBC.readBlockPos(nbt.getTag("max")); + min = nbt.hasKey("min") ? NBTUtilBC.readBlockPos(nbt.getTag("min")) : null; + max = nbt.hasKey("max") ? NBTUtilBC.readBlockPos(nbt.getTag("max")) : null; } extendToEncompassBoth(min, max); } diff --git a/common/buildcraft/lib/misc/data/BoxIterator.java b/common/buildcraft/lib/misc/data/BoxIterator.java index 4e488afac5..cdaca7e90a 100644 --- a/common/buildcraft/lib/misc/data/BoxIterator.java +++ b/common/buildcraft/lib/misc/data/BoxIterator.java @@ -48,12 +48,12 @@ private BoxIterator(BlockPos min, BlockPos max, boolean invert, boolean repeat, } public static BoxIterator readFromNbt(NBTTagCompound nbt) { - BlockPos min = NBTUtilBC.readBlockPos(nbt.getTag("min")); - BlockPos max = NBTUtilBC.readBlockPos(nbt.getTag("max")); + BlockPos min = nbt.hasKey("min") ? NBTUtilBC.readBlockPos(nbt.getTag("min")) : null; + BlockPos max = nbt.hasKey("max") ? NBTUtilBC.readBlockPos(nbt.getTag("max")) : null; boolean invert = nbt.getBoolean("invert"); boolean repeat = false; AxisOrder order = AxisOrder.readNbt(nbt.getCompoundTag("order")); - BlockPos current = NBTUtilBC.readBlockPos(nbt.getTag("current")); + BlockPos current = nbt.hasKey("current") ? NBTUtilBC.readBlockPos(nbt.getTag("current")) : null; if (min == null || max == null || order == null) { return null; } diff --git a/common/buildcraft/silicon/tile/TileLaser.java b/common/buildcraft/silicon/tile/TileLaser.java index bd201063bf..e47611565e 100644 --- a/common/buildcraft/silicon/tile/TileLaser.java +++ b/common/buildcraft/silicon/tile/TileLaser.java @@ -184,7 +184,7 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); battery.deserializeNBT(nbt.getCompoundTag("mj_battery")); - targetPos = NBTUtilBC.readBlockPos(nbt.getTag("target_pos")); + targetPos = nbt.hasKey("target_pos") ? NBTUtilBC.readBlockPos(nbt.getTag("target_pos")) : null; laserPos = NBTUtilBC.readVec3d(nbt.getTag("laser_pos")); avgPower.readFromNbt(nbt, "average_power"); } From 97ce381945677730642d8d7d1643caf9b54b2940 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Sat, 1 Jul 2017 14:48:01 +0100 Subject: [PATCH 73/89] Temp work on stuffs. Also includes the correct fix for BuildCraft/BuildCraft#3696 --- BuildCraftAPI | 2 +- .../snapshot/ITileForBlueprintBuilder.java | 2 +- .../buildcraft/builders/tile/TileBuilder.java | 45 +++----- common/buildcraft/energy/BCEnergyFluids.java | 2 +- common/buildcraft/energy/BCEnergyRecipes.java | 30 ++--- .../energy/tile/TileEngineIron_BC8.java | 7 +- .../client/render/RenderDistiller.java | 16 +-- ...ange.java => RenderHeatExchangeStart.java} | 2 +- .../factory/tile/TileAutoWorkbenchFluids.java | 6 +- .../factory/tile/TileDistiller_BC8.java | 92 +++++++++++++--- .../factory/tile/TileHeatExchangeEnd.java | 19 +--- .../factory/tile/TileHeatExchangeStart.java | 104 ++++++++++-------- common/buildcraft/factory/tile/TilePump.java | 15 +-- common/buildcraft/factory/tile/TileTank.java | 16 +-- .../lib/chunkload/IChunkLoadingTile.java | 2 +- .../lib/compat/DefaultBlockAccessor.java | 4 +- .../buildcraft/lib/fluid/FluidSmoother.java | 5 + common/buildcraft/lib/fluid/Tank.java | 26 ++--- common/buildcraft/lib/fluid/TankManager.java | 35 +++--- .../lib/recipe/RefineryRecipeRegistry.java | 25 ++--- .../buildcraft/lib/tile/TileBC_Neptune.java | 73 +++++++----- .../transport/BCTransportConfig.java | 2 +- .../client/render/PipeFlowRendererFluids.java | 10 +- .../factory/tile/TileFloodGate.java | 12 +- .../test/lib/fluid/TankManagerTester.java | 2 +- .../ComplexRefineryRecipeManager.java | 8 +- 26 files changed, 288 insertions(+), 274 deletions(-) rename common/buildcraft/factory/client/render/{RenderHeatExchange.java => RenderHeatExchangeStart.java} (77%) diff --git a/BuildCraftAPI b/BuildCraftAPI index a061e443e9..b8144f90fa 160000 --- a/BuildCraftAPI +++ b/BuildCraftAPI @@ -1 +1 @@ -Subproject commit a061e443e9bd518c9c4f554da51e3d16308b1878 +Subproject commit b8144f90fa742bb16d94341e907dc09d98473795 diff --git a/common/buildcraft/builders/snapshot/ITileForBlueprintBuilder.java b/common/buildcraft/builders/snapshot/ITileForBlueprintBuilder.java index 2cc197aa60..267efb8a95 100644 --- a/common/buildcraft/builders/snapshot/ITileForBlueprintBuilder.java +++ b/common/buildcraft/builders/snapshot/ITileForBlueprintBuilder.java @@ -16,5 +16,5 @@ public interface ITileForBlueprintBuilder extends ITileForSnapshotBuilder { IItemTransactor getInvResources(); - TankManager getTankManager(); + TankManager getTankManager(); } diff --git a/common/buildcraft/builders/tile/TileBuilder.java b/common/buildcraft/builders/tile/TileBuilder.java index bcca88f735..9efb46dacd 100644 --- a/common/buildcraft/builders/tile/TileBuilder.java +++ b/common/buildcraft/builders/tile/TileBuilder.java @@ -81,30 +81,15 @@ public class TileBuilder extends TileBC_Neptune public static final int NET_CAN_EXCAVATE = IDS.allocId("CAN_EXCAVATE"); public static final int NET_SNAPSHOT_TYPE = IDS.allocId("SNAPSHOT_TYPE"); - public final ItemHandlerSimple invSnapshot = itemManager.addInvHandler( - "snapshot", - 1, - EnumAccess.BOTH, - EnumPipePart.VALUES - ); - public final ItemHandlerSimple invResources = itemManager.addInvHandler( - "resources", - 27, - EnumAccess.BOTH, - EnumPipePart.VALUES - ); - private final TankManager tankManager = new TankManager<>(); + public final ItemHandlerSimple invSnapshot; + public final ItemHandlerSimple invResources; private final MjBattery battery = new MjBattery(1000 * MjAPI.MJ); private boolean canExcavate = true; - /** - * Stores the real path - just a few block positions. - */ + /** Stores the real path - just a few block positions. */ public List path = null; - /** - * Stores the real path plus all possible block positions inbetween. - */ + /** Stores the real path plus all possible block positions inbetween. */ private List basePoses = new ArrayList<>(); private int currentBasePosIndex = 0; private Snapshot snapshot = null; @@ -118,6 +103,8 @@ public class TileBuilder extends TileBC_Neptune private boolean isDone = false; public TileBuilder() { + invSnapshot = itemManager.addInvHandler("snapshot", 1, EnumAccess.BOTH, EnumPipePart.VALUES); + invResources = itemManager.addInvHandler("resources", 27, EnumAccess.BOTH, EnumPipePart.VALUES); for (int i = 1; i <= 4; i++) { tankManager.add(new Tank("fluid" + i, Fluid.BUCKET_VOLUME * 8, this)); } @@ -131,10 +118,8 @@ public IdAllocator getIdAllocator() { } @Override - protected void onSlotChange(IItemHandlerModifiable itemHandler, - int slot, - @Nonnull ItemStack before, - @Nonnull ItemStack after) { + protected void onSlotChange(IItemHandlerModifiable itemHandler, int slot, @Nonnull ItemStack before, + @Nonnull ItemStack after) { if (itemHandler == invSnapshot) { if (!world.isRemote) { currentBasePosIndex = 0; @@ -233,8 +218,10 @@ public void onPlacedBy(EntityLivingBase placer, ItemStack stack) { public void update() { battery.tick(getWorld(), getPos()); battery.addPowerChecking(64 * MjAPI.MJ, false); - if (getBuilder() != null) { - if (isDone = getBuilder().tick()) { + SnapshotBuilder builder = getBuilder(); + if (builder != null) { + isDone = builder.tick(); + if (isDone) { if (currentBasePosIndex < basePoses.size() - 1) { currentBasePosIndex++; if (currentBasePosIndex >= basePoses.size()) { @@ -349,12 +336,10 @@ public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); if (nbt.hasKey("path")) { path = NBTUtilBC.readCompoundList(nbt.getTagList("path", Constants.NBT.TAG_COMPOUND)) - .map(NBTUtil::getPosFromTag) - .collect(Collectors.toList()); + .map(NBTUtil::getPosFromTag).collect(Collectors.toList()); } basePoses = NBTUtilBC.readCompoundList(nbt.getTagList("basePoses", Constants.NBT.TAG_COMPOUND)) - .map(NBTUtil::getPosFromTag) - .collect(Collectors.toList()); + .map(NBTUtil::getPosFromTag).collect(Collectors.toList()); canExcavate = nbt.getBoolean("canExcavate"); } @@ -440,7 +425,7 @@ public IItemTransactor getInvResources() { } @Override - public TankManager getTankManager() { + public TankManager getTankManager() { return tankManager; } } diff --git a/common/buildcraft/energy/BCEnergyFluids.java b/common/buildcraft/energy/BCEnergyFluids.java index 196a7cfcf0..579bd4142c 100644 --- a/common/buildcraft/energy/BCEnergyFluids.java +++ b/common/buildcraft/energy/BCEnergyFluids.java @@ -54,7 +54,7 @@ public static void preInit() { { 1200, 4000, 3, 4, 0x10_0F_10, 0x42_10_42 },// Residue { 850, 1800, 3, 6, 0xA0_8F_1F, 0x42_35_20 },// Heavy Oil { 950, 1600, 3, 5, 0x87_6E_77, 0x42_24_24 },// Dense Oil - { 750, 1400, 2, 8, 0xE4_BF_78, 0xA4_8F_00 },// Distilled Oil + { 750, 1400, 2, 8, 0xE4_AF_78, 0xB4_7F_00 },// Distilled Oil { 600, 800, 2, 7, 0xFF_AF_3F, 0xE0_7F_00 },// Dense Fuel { 700, 1000, 2, 7, 0xF2_A7_00, 0xC4_87_00 },// Mixed Heavy Fuels { 400, 600, 1, 8, 0xFF_FF_30, 0xE4_CF_00 },// Light Fuel diff --git a/common/buildcraft/energy/BCEnergyRecipes.java b/common/buildcraft/energy/BCEnergyRecipes.java index 8e2eb2f3eb..c70bef65f7 100644 --- a/common/buildcraft/energy/BCEnergyRecipes.java +++ b/common/buildcraft/energy/BCEnergyRecipes.java @@ -116,22 +116,22 @@ public static void init() { addDistillation(dense_residue, dense, residue, 2, 12 * MjAPI.MJ); - addHeatExchange(BCEnergyFluids.crudeOil, 3); - addHeatExchange(BCEnergyFluids.oilDistilled, 2); - addHeatExchange(BCEnergyFluids.oilHeavy, 3); - addHeatExchange(BCEnergyFluids.fuelMixedLight, 2); - addHeatExchange(BCEnergyFluids.fuelMixedHeavy, 2); - addHeatExchange(BCEnergyFluids.oilDense, 3); - addHeatExchange(BCEnergyFluids.fuelGaseous, 1); - addHeatExchange(BCEnergyFluids.fuelLight, 1); - addHeatExchange(BCEnergyFluids.fuelDense, 2); - addHeatExchange(BCEnergyFluids.oilResidue, 6); + addHeatExchange(BCEnergyFluids.crudeOil); + addHeatExchange(BCEnergyFluids.oilDistilled); + addHeatExchange(BCEnergyFluids.oilHeavy); + addHeatExchange(BCEnergyFluids.fuelMixedLight); + addHeatExchange(BCEnergyFluids.fuelMixedHeavy); + addHeatExchange(BCEnergyFluids.oilDense); + addHeatExchange(BCEnergyFluids.fuelGaseous); + addHeatExchange(BCEnergyFluids.fuelLight); + addHeatExchange(BCEnergyFluids.fuelDense); + addHeatExchange(BCEnergyFluids.oilResidue); FluidStack water = new FluidStack(FluidRegistry.WATER, 10); - BuildcraftRecipeRegistry.refineryRecipes.addHeatableRecipe(water, null, 0, 1, 2); + BuildcraftRecipeRegistry.refineryRecipes.addHeatableRecipe(water, null, 0, 1); FluidStack lava = new FluidStack(FluidRegistry.LAVA, 5); - BuildcraftRecipeRegistry.refineryRecipes.addCoolableRecipe(lava, null, 4, 3, 5); + BuildcraftRecipeRegistry.refineryRecipes.addCoolableRecipe(lava, null, 4, 2); } } @@ -191,7 +191,7 @@ private static void addDistillation(FluidStack[] in, FluidStack[] outGas, FluidS BuildcraftRecipeRegistry.refineryRecipes.addDistillationRecipe(_in, _outGas, _outLiquid, mjCost); } - private static void addHeatExchange(BCFluid[] fluid, int ticks) { + private static void addHeatExchange(BCFluid[] fluid) { for (int i = 0; i < fluid.length - 1; i++) { BCFluid cool = fluid[i]; BCFluid hot = fluid[i + 1]; @@ -199,8 +199,8 @@ private static void addHeatExchange(BCFluid[] fluid, int ticks) { FluidStack hot_f = new FluidStack(hot, 10); int ch = cool.getHeatValue(); int hh = hot.getHeatValue(); - BuildcraftRecipeRegistry.refineryRecipes.addHeatableRecipe(cool_f, hot_f, ch, hh, ticks); - BuildcraftRecipeRegistry.refineryRecipes.addCoolableRecipe(hot_f, cool_f, hh, ch, ticks); + BuildcraftRecipeRegistry.refineryRecipes.addHeatableRecipe(cool_f, hot_f, ch, hh); + BuildcraftRecipeRegistry.refineryRecipes.addCoolableRecipe(hot_f, cool_f, hh, ch); } } } diff --git a/common/buildcraft/energy/tile/TileEngineIron_BC8.java b/common/buildcraft/energy/tile/TileEngineIron_BC8.java index fcfe8b9887..3b522f8b74 100644 --- a/common/buildcraft/energy/tile/TileEngineIron_BC8.java +++ b/common/buildcraft/energy/tile/TileEngineIron_BC8.java @@ -69,7 +69,6 @@ protected FluidGetResult map(ItemStack stack, int space) { } }; public final Tank tankResidue = new Tank("tankResidue", MAX_FLUID, this, this::isResidue); - private final TankManager tankManager = new TankManager<>(tankFuel, tankCoolant, tankResidue); private final IFluidHandlerAdv fluidHandler = new InternalFluidHandler(); private int penaltyCooling = 0; @@ -79,6 +78,8 @@ protected FluidGetResult map(ItemStack stack, int space) { private IFuel currentFuel; public TileEngineIron_BC8() { + tankManager.addAll(tankFuel, tankCoolant, tankResidue); + // TODO: Auto list of example fuels! tankFuel.helpInfo = new ElementHelpInfo(tankFuel.helpInfo.title, 0xFF_FF_33_33, Tank.DEFAULT_HELP_KEY, null, "buildcraft.help.tank.fuel"); @@ -98,7 +99,6 @@ public TileEngineIron_BC8() { @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); - nbt.setTag("tanks", tankManager.serializeNBT()); nbt.setInteger("penaltyCooling", penaltyCooling); nbt.setDouble("burnTime", burnTime); return nbt; @@ -107,7 +107,6 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); - tankManager.deserializeNBT(nbt.getCompoundTag("tanks")); penaltyCooling = nbt.getInteger("penaltyCooling"); burnTime = nbt.getDouble("burnTime"); } @@ -187,7 +186,7 @@ public boolean isBurning() { @Override protected void burn() { FluidStack fuel = this.tankFuel.getFluid(); - if (currentFuel == null) { + if (currentFuel == null || !currentFuel.getFluid().isFluidEqual(fuel)) { currentFuel = BuildcraftFuelRegistry.fuel.getFuel(fuel); } diff --git a/common/buildcraft/factory/client/render/RenderDistiller.java b/common/buildcraft/factory/client/render/RenderDistiller.java index 3e118d3f01..0c4376cdfa 100644 --- a/common/buildcraft/factory/client/render/RenderDistiller.java +++ b/common/buildcraft/factory/client/render/RenderDistiller.java @@ -32,6 +32,8 @@ import buildcraft.lib.client.model.MutableQuad; import buildcraft.lib.client.render.fluid.FluidRenderer; import buildcraft.lib.client.render.fluid.FluidSpriteType; +import buildcraft.lib.fluid.FluidSmoother; +import buildcraft.lib.fluid.FluidSmoother.SmoothedFluid; import buildcraft.lib.fluid.Tank; import buildcraft.lib.misc.VecUtil; @@ -107,9 +109,9 @@ public void renderTileEntityAt(TileDistiller_BC8 tile, double x, double y, doubl profiler.endSection(); profiler.endStartSection("fluid"); - renderTank(sizes.tankIn, tile.tankIn, combinedLight, vb); - renderTank(sizes.tankOutGas, tile.tankOutGas, combinedLight, vb); - renderTank(sizes.tankOutLiquid, tile.tankOutLiquid, combinedLight, vb); + renderTank(sizes.tankIn, tile.smoothedTankIn, combinedLight, partialTicks, vb); + renderTank(sizes.tankOutGas, tile.smoothedTankOutGas, combinedLight, partialTicks, vb); + renderTank(sizes.tankOutLiquid, tile.smoothedTankOutLiquid, combinedLight, partialTicks, vb); // buffer finish vb.setTranslation(0, 0, 0); @@ -124,15 +126,15 @@ public void renderTileEntityAt(TileDistiller_BC8 tile, double x, double y, doubl profiler.endSection(); } - private static void renderTank(Size size, Tank tank, int combinedLight, VertexBuffer vb) { - FluidStack fluid = tank.getFluidForRender(); + private static void renderTank(Size size, FluidSmoother tank, int combinedLight, float partialTicks, VertexBuffer vb) { + SmoothedFluid fluid = tank.getFluidForRender(partialTicks); if (fluid == null || fluid.amount <= 0) { return; } - int blockLight = fluid.getFluid().getLuminosity(fluid) & 0xF; + int blockLight = fluid.fluid.getFluid().getLuminosity(fluid.fluid) & 0xF; combinedLight |= blockLight << 4; FluidRenderer.vertex.lighti(combinedLight); - FluidRenderer.renderFluid(FluidSpriteType.STILL, fluid, tank.getCapacity(), size.min, size.max, vb, null); + FluidRenderer.renderFluid(FluidSpriteType.STILL, fluid.fluid, fluid.amount, tank.getCapacity(), size.min, size.max, vb, null); } static class TankRenderSizes { diff --git a/common/buildcraft/factory/client/render/RenderHeatExchange.java b/common/buildcraft/factory/client/render/RenderHeatExchangeStart.java similarity index 77% rename from common/buildcraft/factory/client/render/RenderHeatExchange.java rename to common/buildcraft/factory/client/render/RenderHeatExchangeStart.java index 9f2590e14f..43e0a24464 100644 --- a/common/buildcraft/factory/client/render/RenderHeatExchange.java +++ b/common/buildcraft/factory/client/render/RenderHeatExchangeStart.java @@ -4,7 +4,7 @@ import buildcraft.factory.tile.TileHeatExchangeStart; -public class RenderHeatExchange extends TileEntitySpecialRenderer { +public class RenderHeatExchangeStart extends TileEntitySpecialRenderer { @Override public void renderTileEntityAt(TileHeatExchangeStart tile, double x, double y, double z, float partialTicks, int destroyStage) { diff --git a/common/buildcraft/factory/tile/TileAutoWorkbenchFluids.java b/common/buildcraft/factory/tile/TileAutoWorkbenchFluids.java index ba01e2c2ba..3c7841c05f 100644 --- a/common/buildcraft/factory/tile/TileAutoWorkbenchFluids.java +++ b/common/buildcraft/factory/tile/TileAutoWorkbenchFluids.java @@ -17,22 +17,20 @@ import buildcraft.api.core.EnumPipePart; import buildcraft.lib.fluid.Tank; -import buildcraft.lib.fluid.TankManager; import buildcraft.lib.misc.CapUtil; public class TileAutoWorkbenchFluids extends TileAutoWorkbenchBase { private final Tank tank1 = new Tank("tank1", Fluid.BUCKET_VOLUME * 6, this); private final Tank tank2 = new Tank("tank2", Fluid.BUCKET_VOLUME * 6, this); - private final TankManager tankManager = new TankManager<>(tank1, tank2); public TileAutoWorkbenchFluids() { super(2, 2); + tankManager.addAll(tank1, tank2); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankManager, EnumPipePart.CENTER); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tank1, EnumPipePart.DOWN, EnumPipePart.NORTH, EnumPipePart.WEST); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tank2, EnumPipePart.UP, EnumPipePart.SOUTH, EnumPipePart.EAST); } - @Override @SideOnly(Side.CLIENT) public void getDebugInfo(List left, List right, EnumFacing side) { @@ -47,5 +45,3 @@ public boolean canWork() { return false; } } - - diff --git a/common/buildcraft/factory/tile/TileDistiller_BC8.java b/common/buildcraft/factory/tile/TileDistiller_BC8.java index 6cd3781841..8f8127b0d2 100644 --- a/common/buildcraft/factory/tile/TileDistiller_BC8.java +++ b/common/buildcraft/factory/tile/TileDistiller_BC8.java @@ -37,11 +37,13 @@ import buildcraft.lib.expression.node.value.NodeVariableBoolean; import buildcraft.lib.expression.node.value.NodeVariableLong; import buildcraft.lib.expression.node.value.NodeVariableString; +import buildcraft.lib.fluid.FluidSmoother; +import buildcraft.lib.fluid.FluidSmoother.IFluidDataSender; import buildcraft.lib.fluid.Tank; -import buildcraft.lib.fluid.TankManager; import buildcraft.lib.misc.CapUtil; import buildcraft.lib.misc.LocaleUtil; import buildcraft.lib.misc.data.AverageLong; +import buildcraft.lib.misc.data.IdAllocator; import buildcraft.lib.misc.data.ModelVariableData; import buildcraft.lib.mj.MjBatteryReciver; import buildcraft.lib.net.PacketBufferBC; @@ -57,6 +59,11 @@ public class TileDistiller_BC8 extends TileBC_Neptune implements ITickable, IDeb private static final NodeVariableLong MODEL_POWER_AVG; private static final NodeVariableLong MODEL_POWER_MAX; + public static final IdAllocator IDS = TileBC_Neptune.IDS.makeChild("Distiller"); + public static final int NET_TANK_IN = IDS.allocId("TANK_IN"); + public static final int NET_TANK_OUT_GAS = IDS.allocId("TANK_OUT_GAS"); + public static final int NET_TANK_OUT_LIQUID = IDS.allocId("TANK_OUT_LIQUID"); + static { MODEL_FUNC_CTX = DefaultContexts.createWithAll(); MODEL_FACING = MODEL_FUNC_CTX.putVariableString("facing"); @@ -67,13 +74,35 @@ public class TileDistiller_BC8 extends TileBC_Neptune implements ITickable, IDeb public static final long MAX_MJ_PER_TICK = 6 * MjAPI.MJ; - public final Tank tankIn = new Tank("in", 4 * Fluid.BUCKET_VOLUME, this); - public final Tank tankOutGas = new Tank("out_gas", 4 * Fluid.BUCKET_VOLUME, this, this::isDistillable); - public final Tank tankOutLiquid = new Tank("out_liquid", 4 * Fluid.BUCKET_VOLUME, this); - public final TankManager tankManager = new TankManager<>(tankIn, tankOutGas, tankOutLiquid); + private final Tank tankIn = new Tank("in", 4 * Fluid.BUCKET_VOLUME, this) { + @Override + public int fill(FluidStack resource, boolean doFill) { + IRefineryRecipeManager manager = BuildcraftRecipeRegistry.refineryRecipes; + IDistillationRecipe recipe = manager.getDistilationRegistry().getRecipeForInput(resource); + if (recipe == null) { + return 0; + } + // Quality-of-life change: Only accept full amounts of the input fluid, so + // we don't get small amounts left over + int amount = getFluidAmount() + resource.amount; + amount = Math.min(amount, getCapacity()); + amount = resource.amount - (amount % recipe.in().amount); + if (amount <= 0) { + return 0; + } + return super.fill(new FluidStack(resource, amount), doFill); + } + }; + private final Tank tankOutGas = new Tank("out_gas", 4 * Fluid.BUCKET_VOLUME, this); + private final Tank tankOutLiquid = new Tank("out_liquid", 4 * Fluid.BUCKET_VOLUME, this); private final MjBattery mjBattery = new MjBattery(1024 * MjAPI.MJ); + public final FluidSmoother smoothedTankIn = new FluidSmoother(createSender(NET_TANK_IN), tankIn); + public final FluidSmoother smoothedTankOutGas = new FluidSmoother(createSender(NET_TANK_OUT_GAS), tankOutGas); + public final FluidSmoother smoothedTankOutLiquid = + new FluidSmoother(createSender(NET_TANK_OUT_LIQUID), tankOutLiquid); + /** The model variables, used to keep track of the various state-based variables. */ public final ModelVariableData clientModelData = new ModelVariableData(); @@ -91,12 +120,20 @@ public TileDistiller_BC8() { tankOutGas.setCanFill(false); tankOutLiquid.setCanFill(false); + tankManager.add(tankIn); + tankManager.add(tankOutGas); + tankManager.add(tankOutLiquid); + caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankIn, EnumPipePart.HORIZONTALS); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankOutGas, EnumPipePart.UP); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankOutLiquid, EnumPipePart.DOWN); caps.addProvider(new MjCapabilityHelper(new MjBatteryReciver(mjBattery))); } + private IFluidDataSender createSender(int netId) { + return writer -> createAndSendMessage(netId, writer); + } + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); @@ -121,12 +158,20 @@ public void writePayload(int id, PacketBufferBC buffer, Side side) { super.writePayload(id, buffer, side); if (side == Side.SERVER) { if (id == NET_RENDER_DATA) { - tankManager.writeData(buffer); + writePayload(NET_TANK_IN, buffer, side); + writePayload(NET_TANK_OUT_GAS, buffer, side); + writePayload(NET_TANK_OUT_LIQUID, buffer, side); buffer.writeBoolean(isActive); powerAvgClient = powerAvg.getAverageLong(); final long div = MjAPI.MJ / 2; powerAvgClient = Math.round(powerAvgClient / (double) div) * div; buffer.writeLong(powerAvgClient); + } else if (id == NET_TANK_IN) { + smoothedTankIn.writeInit(buffer); + } else if (id == NET_TANK_OUT_GAS) { + smoothedTankOutGas.writeInit(buffer); + } else if (id == NET_TANK_OUT_LIQUID) { + smoothedTankOutLiquid.writeInit(buffer); } } } @@ -136,18 +181,26 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext super.readPayload(id, buffer, side, ctx); if (side == Side.CLIENT) { if (id == NET_RENDER_DATA) { - tankManager.readData(buffer); + readPayload(NET_TANK_IN, buffer, side, ctx); + readPayload(NET_TANK_OUT_GAS, buffer, side, ctx); + readPayload(NET_TANK_OUT_LIQUID, buffer, side, ctx); + + smoothedTankIn.resetSmoothing(getWorld()); + smoothedTankOutGas.resetSmoothing(getWorld()); + smoothedTankOutLiquid.resetSmoothing(getWorld()); + isActive = buffer.readBoolean(); powerAvgClient = buffer.readLong(); + } else if (id == NET_TANK_IN) { + smoothedTankIn.handleMessage(getWorld(), buffer); + } else if (id == NET_TANK_OUT_GAS) { + smoothedTankOutGas.handleMessage(getWorld(), buffer); + } else if (id == NET_TANK_OUT_LIQUID) { + smoothedTankOutLiquid.handleMessage(getWorld(), buffer); } } } - private boolean isDistillable(FluidStack fluid) { - IRefineryRecipeManager manager = BuildcraftRecipeRegistry.refineryRecipes; - return manager.getDistilationRegistry().getRecipeForInput(fluid) != null; - } - public static void setClientModelVariablesForItem() { DefaultContexts.RENDER_PARTIAL_TICKS.value = 1; MODEL_ACTIVE.value = false; @@ -177,17 +230,19 @@ public boolean onActivated(EntityPlayer player, EnumHand hand, EnumFacing facing @Override public void update() { + smoothedTankIn.tick(getWorld()); + smoothedTankOutGas.tick(getWorld()); + smoothedTankOutLiquid.tick(getWorld()); if (world.isRemote) { setClientModelVariables(1); clientModelData.tick(); return; } - long avgNow = powerAvg.getAverageLong(); powerAvg.tick(); - changedSinceNetUpdate |= avgNow / MjAPI.MJ != powerAvg.getAverageLong() / MjAPI.MJ; + changedSinceNetUpdate |= powerAvgClient != powerAvg.getAverageLong(); - currentRecipe = BuildcraftRecipeRegistry.refineryRecipes.getDistilationRegistry().getRecipeForInput(tankIn - .getFluid()); + currentRecipe = + BuildcraftRecipeRegistry.refineryRecipes.getDistilationRegistry().getRecipeForInput(tankIn.getFluid()); if (currentRecipe == null) { mjBattery.addPowerChecking(distillPower, false); distillPower = 0; @@ -219,7 +274,6 @@ public void update() { tankIn.drainInternal(reqIn, true); tankOutGas.fillInternal(outGas, true); tankOutLiquid.fillInternal(outLiquid, true); - changedSinceNetUpdate = true; } } else { mjBattery.addPowerChecking(distillPower, false); @@ -228,8 +282,10 @@ public void update() { } } - if (updateTracker.markTimeIfDelay(world)) { + if (changedSinceNetUpdate && updateTracker.markTimeIfDelay(world)) { + powerAvgClient = powerAvg.getAverageLong(); sendNetworkUpdate(NET_RENDER_DATA); + changedSinceNetUpdate = false; } } diff --git a/common/buildcraft/factory/tile/TileHeatExchangeEnd.java b/common/buildcraft/factory/tile/TileHeatExchangeEnd.java index 703bb1effb..9dd6fcc629 100644 --- a/common/buildcraft/factory/tile/TileHeatExchangeEnd.java +++ b/common/buildcraft/factory/tile/TileHeatExchangeEnd.java @@ -12,7 +12,6 @@ import javax.annotation.Nullable; import net.minecraft.block.state.IBlockState; -import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; @@ -29,7 +28,6 @@ import buildcraft.lib.block.BlockBCBase_Neptune; import buildcraft.lib.fluid.Tank; -import buildcraft.lib.fluid.TankManager; import buildcraft.lib.misc.CapUtil; import buildcraft.lib.net.PacketBufferBC; import buildcraft.lib.tile.TileBC_Neptune; @@ -39,12 +37,12 @@ public class TileHeatExchangeEnd extends TileBC_Neptune implements IDebuggable { public final Tank tankHeatableOut = new Tank("heatable_out", 2 * Fluid.BUCKET_VOLUME, this); public final Tank tankCoolableIn = new Tank("coolable_in", 2 * Fluid.BUCKET_VOLUME, this, this::isCoolant); - private final TankManager tankManager = new TankManager<>(tankHeatableOut, tankCoolableIn); public TileHeatExchangeEnd() { + tankManager.addAll(tankHeatableOut, tankCoolableIn); + tankHeatableOut.setCanFill(false); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankHeatableOut, EnumPipePart.UP); caps.addCapability(CapUtil.CAP_FLUIDS, this::getTankForSide, EnumPipePart.HORIZONTALS); - tankHeatableOut.setCanFill(false); } private boolean isCoolant(FluidStack fluid) { @@ -63,19 +61,6 @@ private IFluidHandler getTankForSide(EnumFacing side) { return tankCoolableIn; } - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbt) { - super.writeToNBT(nbt); - nbt.setTag("tanks", tankManager.serializeNBT()); - return nbt; - } - - @Override - public void readFromNBT(NBTTagCompound nbt) { - super.readFromNBT(nbt); - tankManager.deserializeNBT(nbt.getCompoundTag("tanks")); - } - @Override public void writePayload(int id, PacketBufferBC buffer, Side side) { super.writePayload(id, buffer, side); diff --git a/common/buildcraft/factory/tile/TileHeatExchangeStart.java b/common/buildcraft/factory/tile/TileHeatExchangeStart.java index c5da2953f8..0f315a0dd2 100644 --- a/common/buildcraft/factory/tile/TileHeatExchangeStart.java +++ b/common/buildcraft/factory/tile/TileHeatExchangeStart.java @@ -40,11 +40,10 @@ import buildcraft.lib.block.BlockBCBase_Neptune; import buildcraft.lib.fluid.Tank; -import buildcraft.lib.fluid.TankManager; import buildcraft.lib.misc.CapUtil; import buildcraft.lib.misc.FluidUtilBC; -import buildcraft.lib.misc.MathUtil; import buildcraft.lib.misc.VecUtil; +import buildcraft.lib.misc.data.IdAllocator; import buildcraft.lib.net.PacketBufferBC; import buildcraft.lib.tile.TileBC_Neptune; @@ -52,17 +51,27 @@ import buildcraft.factory.block.BlockHeatExchange; public class TileHeatExchangeStart extends TileBC_Neptune implements ITickable, IDebuggable { - public final Tank tankHeatableIn = new Tank("heatable_in", 2 * Fluid.BUCKET_VOLUME, this, this::isHeatant); - public final Tank tankCoolableOut = new Tank("coolable_out", 2 * Fluid.BUCKET_VOLUME, this); - private final TankManager tankManager = new TankManager<>(tankHeatableIn, tankCoolableOut); + + public static final IdAllocator IDS = TileBC_Neptune.IDS.makeChild("HeatExchangeStart"); + public static final int NET_TANK_HEATABLE_IN = IDS.allocId("TANK_HEATABLE_IN"); + public static final int NET_TANK_COOLABLE_OUT = IDS.allocId("TANK_COOLABLE_OUT"); + + private static final int[] FLUID_MULT = { 10, 16, 20 }; + + private final Tank tankHeatableIn = new Tank("heatable_in", 2 * Fluid.BUCKET_VOLUME, this, this::isHeatant); + private final Tank tankCoolableOut = new Tank("coolable_out", 2 * Fluid.BUCKET_VOLUME, this); private TileHeatExchangeEnd tileEnd; + private int middles; private int progress = 0; + private int heatProvided = 0; + private int coolingProvided = 0; public TileHeatExchangeStart() { + tankManager.addAll(tankHeatableIn, tankCoolableOut); + tankCoolableOut.setCanFill(false); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankHeatableIn, EnumPipePart.DOWN); caps.addCapability(CapUtil.CAP_FLUIDS, this::getTankForSide, EnumPipePart.HORIZONTALS); - tankCoolableOut.setCanFill(false); } private boolean isHeatant(FluidStack fluid) { @@ -84,14 +93,16 @@ private IFluidHandler getTankForSide(EnumFacing side) { @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); - nbt.setTag("tanks", tankManager.serializeNBT()); + nbt.setInteger("coolingProvided", coolingProvided); + nbt.setInteger("heatProvided", heatProvided); return nbt; } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); - tankManager.deserializeNBT(nbt.getCompoundTag("tanks")); + coolingProvided = nbt.getInteger("coolingProvided"); + heatProvided = nbt.getInteger("heatProvided"); } @Override @@ -138,7 +149,7 @@ private void findEnd() { } BlockHeatExchange block = (BlockHeatExchange) state.getBlock(); EnumFacing facing = state.getValue(BlockBCBase_Neptune.PROP_FACING); - int middles = 0; + middles = 0; BlockPos search = getPos(); for (int i = 0; i <= 3; i++) { search = search.offset(facing); @@ -183,10 +194,16 @@ private void craft() { ICoolableRecipe c_recipe = reg.getCoolableRegistry().getRecipeForInput(c_in.getFluid()); IHeatableRecipe h_recipe = reg.getHeatableRegistry().getRecipeForInput(h_in.getFluid()); if (h_recipe == null || c_recipe == null) { + if (progress > 0) { + progress--; + } return; } if (c_recipe.heatFrom() <= h_recipe.heatFrom()) { BCLog.logger.warn("Invalid heat values!"); + if (progress > 0) { + progress--; + } return; } int c_diff = c_recipe.heatFrom() - c_recipe.heatTo(); @@ -194,39 +211,46 @@ private void craft() { if (h_diff < 1 || c_diff < 1) { throw new IllegalStateException("Invalid recipe " + c_recipe + ", " + h_recipe); } - int c_mult = 1; - int h_mult = 1; - if (h_diff != c_diff) { - int lcm = MathUtil.findLowestCommonMultiple(c_diff, h_diff); - c_mult = lcm / c_diff; - h_mult = lcm / h_diff; - } - FluidStack c_in_f = mult(c_recipe.in(), c_mult); - FluidStack c_out_f = mult(c_recipe.out(), c_mult); - FluidStack h_in_f = mult(h_recipe.in(), h_mult); - FluidStack h_out_f = mult(h_recipe.out(), h_mult); + int mult = FLUID_MULT[middles - 1]; + boolean needs_c = heatProvided == 0; + boolean needs_h = coolingProvided == 0; + + FluidStack c_in_f = setAmount(c_recipe.in(), mult); + FluidStack c_out_f = setAmount(c_recipe.out(), mult); + FluidStack h_in_f = setAmount(h_recipe.in(), mult); + FluidStack h_out_f = setAmount(h_recipe.out(), mult); if (canFill(c_out, c_out_f) && canFill(h_out, h_out_f) && canDrain(c_in, c_in_f) && canDrain(h_in, h_in_f)) { progress++; - int lag = Math.max(c_recipe.ticks(), h_recipe.ticks()); + int lag = 30; if (progress >= lag) { - fill(c_out, c_out_f); - fill(h_out, h_out_f); - drain(c_in, c_in_f); - drain(h_in, h_in_f); progress = lag; - if (c_in_f.getFluid() == FluidRegistry.LAVA) { - // Output is at the other end - Vec3d from = VecUtil.convertCenter(getPos()); - EnumFacing dir = EnumFacing.SOUTH; - spewForth(from, dir, EnumParticleTypes.SMOKE_LARGE); + heatProvided += c_diff - 1; + coolingProvided += h_diff - 1; + + if (needs_c) { + fill(c_out, c_out_f); + drain(c_in, c_in_f); + if (c_in_f.getFluid() == FluidRegistry.LAVA) { + // Output is here + Vec3d from = VecUtil.convertCenter(getPos()); + EnumFacing dir = EnumFacing.SOUTH; + spewForth(from, dir, EnumParticleTypes.SMOKE_LARGE); + } } - if (h_in_f.getFluid() == FluidRegistry.WATER) { - // Output is here - Vec3d from = VecUtil.convertCenter(tileEnd.getPos()); - EnumFacing dir = EnumFacing.UP; - spewForth(from, dir, EnumParticleTypes.CLOUD); + + if (needs_h) { + fill(h_out, h_out_f); + drain(h_in, h_in_f); + if (h_in_f.getFluid() == FluidRegistry.WATER) { + // Output is at the other end + Vec3d from = VecUtil.convertCenter(tileEnd.getPos()); + EnumFacing dir = EnumFacing.UP; + spewForth(from, dir, EnumParticleTypes.CLOUD); + } } } + } else if (progress > 0) { + progress--; } } @@ -261,17 +285,11 @@ private void output() { } } - private static FluidStack mult(FluidStack fluid, int mult) { + private static FluidStack setAmount(FluidStack fluid, int mult) { if (fluid == null) { return null; } - switch (mult) { - case 0: - case 1: - return fluid; - default: - return new FluidStack(fluid, fluid.amount * mult); - } + return new FluidStack(fluid, mult); } private static boolean canFill(Tank t, FluidStack fluid) { diff --git a/common/buildcraft/factory/tile/TilePump.java b/common/buildcraft/factory/tile/TilePump.java index 7014cdfb38..2db0748969 100644 --- a/common/buildcraft/factory/tile/TilePump.java +++ b/common/buildcraft/factory/tile/TilePump.java @@ -20,7 +20,6 @@ import com.google.common.collect.ImmutableList; -import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -56,6 +55,7 @@ public class TilePump extends TileMiner { public TilePump() { tank.setCanFill(false); + tankManager.add(tank); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tank, EnumPipePart.VALUES); } @@ -207,19 +207,6 @@ public void mine() { } } - @Override - public void readFromNBT(NBTTagCompound nbt) { - super.readFromNBT(nbt); - tank.deserializeNBT(nbt.getCompoundTag("tank")); - } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbt) { - super.writeToNBT(nbt); - nbt.setTag("tank", tank.serializeNBT()); - return nbt; - } - // Networking @Override diff --git a/common/buildcraft/factory/tile/TileTank.java b/common/buildcraft/factory/tile/TileTank.java index f1a79e7569..3a8a852748 100644 --- a/common/buildcraft/factory/tile/TileTank.java +++ b/common/buildcraft/factory/tile/TileTank.java @@ -54,6 +54,7 @@ public class TileTank extends TileBC_Neptune implements ITickable, IDebuggable, public final FluidSmoother smoothedTank = new FluidSmoother(w -> createAndSendMessage(NET_FLUID_DELTA, w), tank); public TileTank() { + tankManager.add(tank);// SAVING IS ALL SORTS OF BUGGED caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, this, EnumPipePart.VALUES); } @@ -120,21 +121,6 @@ public boolean onActivate(EntityPlayer player, EnumHand hand) { return true; } - // NBT - - @Override - public void readFromNBT(NBTTagCompound nbt) { - super.readFromNBT(nbt); - tank.deserializeNBT(nbt.getCompoundTag("tank")); - } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbt) { - super.writeToNBT(nbt); - nbt.setTag("tank", tank.serializeNBT()); - return nbt; - } - // Networking @Override diff --git a/common/buildcraft/lib/chunkload/IChunkLoadingTile.java b/common/buildcraft/lib/chunkload/IChunkLoadingTile.java index dd7e11d2d9..baf5f770cb 100644 --- a/common/buildcraft/lib/chunkload/IChunkLoadingTile.java +++ b/common/buildcraft/lib/chunkload/IChunkLoadingTile.java @@ -33,7 +33,7 @@ default LoadType getLoadType() { * * The default implementation returns neighbouring chunks if this block is on a chunk boundary. * - * @return A collection of all the additional chunks to load, not including the {@link ChunkPos} that this tile is + * @return A collection of all the additional chunks to load, optionally including the {@link ChunkPos} that this tile is * contained within. If the return value is null then only the chunk containing this block will be * chunkloaded. */ @Nullable diff --git a/common/buildcraft/lib/compat/DefaultBlockAccessor.java b/common/buildcraft/lib/compat/DefaultBlockAccessor.java index d29b1b4d44..4644be42f5 100644 --- a/common/buildcraft/lib/compat/DefaultBlockAccessor.java +++ b/common/buildcraft/lib/compat/DefaultBlockAccessor.java @@ -25,7 +25,7 @@ public enum DefaultBlockAccessor implements ISoftBlockAccessor { @Override @Nullable public TileEntity getTile(World world, BlockPos pos, boolean force) { - if (direct) { + if (direct | force) { if (force || world.isBlockLoaded(pos)) { return world.getTileEntity(pos); } @@ -41,7 +41,7 @@ public TileEntity getTile(World world, BlockPos pos, boolean force) { @Override public IBlockState getState(World world, BlockPos pos, boolean force) { - if (direct) { + if (direct | force) { if (force || world.isBlockLoaded(pos)) { return world.getBlockState(pos); } diff --git a/common/buildcraft/lib/fluid/FluidSmoother.java b/common/buildcraft/lib/fluid/FluidSmoother.java index afecaaaf78..d57f0ffefc 100644 --- a/common/buildcraft/lib/fluid/FluidSmoother.java +++ b/common/buildcraft/lib/fluid/FluidSmoother.java @@ -100,6 +100,11 @@ public SmoothedFluid getFluidForRender(double partialTicks) { return null; } + /** Delegate for {@link Tank#getCapacity()} - useful if this is the only object exposed for rendering. */ + public int getCapacity() { + return tank.getCapacity(); + } + @Override public void getDebugInfo(List left, List right, EnumFacing side) { if (data != null) { diff --git a/common/buildcraft/lib/fluid/Tank.java b/common/buildcraft/lib/fluid/Tank.java index 757b1684d2..431775e2c7 100644 --- a/common/buildcraft/lib/fluid/Tank.java +++ b/common/buildcraft/lib/fluid/Tank.java @@ -21,7 +21,6 @@ import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; -import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; @@ -43,7 +42,7 @@ /** Provides a useful implementation of a fluid tank that can save + load, and has a few helper funtions. * * Can optionally specify a filter to only allow a limited types of fluids in the tank. */ -public class Tank extends FluidTank implements IFluidHandlerAdv, INBTSerializable { +public class Tank extends FluidTank implements IFluidHandlerAdv { public static final String DEFAULT_HELP_KEY = "buildcraft.help.tank.generic"; public int colorRenderCache = 0xFFFFFF; @@ -106,36 +105,27 @@ public Fluid getFluidType() { return fluidStack != null ? fluidStack.getFluid() : null; } - @Override public NBTTagCompound serializeNBT() { - NBTTagCompound nbt = new NBTTagCompound(); - writeToNBT(nbt); - return nbt; - } - - @Override - public void deserializeNBT(NBTTagCompound nbt) { - readFromNBT(nbt); + return writeToNBT(new NBTTagCompound()); } @Override public final NBTTagCompound writeToNBT(NBTTagCompound nbt) { - NBTTagCompound tankData = new NBTTagCompound(); - super.writeToNBT(tankData); - writeTankToNBT(tankData); - nbt.setTag(name, tankData); + super.writeToNBT(nbt); + writeTankToNBT(nbt); return nbt; } @Override public final FluidTank readFromNBT(NBTTagCompound nbt) { if (nbt.hasKey(name)) { - // allow to read empty tanks - setFluid(null); - + // Old style of saving + loading NBTTagCompound tankData = nbt.getCompoundTag(name); super.readFromNBT(tankData); readTankFromNBT(tankData); + } else { + super.readFromNBT(nbt); + readTankFromNBT(nbt); } return this; } diff --git a/common/buildcraft/lib/fluid/TankManager.java b/common/buildcraft/lib/fluid/TankManager.java index fbe9f8933a..d6756b7c34 100644 --- a/common/buildcraft/lib/fluid/TankManager.java +++ b/common/buildcraft/lib/fluid/TankManager.java @@ -1,11 +1,14 @@ -/* Copyright (c) 2016 SpaceToad and the BuildCraft team +/* + * Copyright (c) 2016 SpaceToad and the BuildCraft team * * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not - * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ package buildcraft.lib.fluid; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import com.google.common.collect.ForwardingList; @@ -25,21 +28,25 @@ /** Provides a simple way to save+load and send+receive data for any number of tanks. This also attempts to fill all of * the tanks one by one via the {@link #fill(FluidStack, boolean)} and {@link #drain(FluidStack, boolean)} methods. */ -public class TankManager extends ForwardingList implements IFluidHandlerAdv, INBTSerializable { +public class TankManager extends ForwardingList implements IFluidHandlerAdv, INBTSerializable { - private List tanks = new ArrayList<>(); + private final List tanks = new ArrayList<>(); public TankManager() {} - public TankManager(T... tanks) { + public TankManager(Tank... tanks) { addAll(Arrays.asList(tanks)); } @Override - protected List delegate() { + protected List delegate() { return tanks; } + public void addAll(Tank... values) { + Collections.addAll(this, values); + } + @Override public int fill(FluidStack resource, boolean doFill) { int filled = 0; @@ -145,21 +152,7 @@ public NBTTagCompound serializeNBT() { @Override public void deserializeNBT(NBTTagCompound nbt) { for (Tank t : tanks) { - t.deserializeNBT(nbt.getCompoundTag(t.getTankName())); - } - } - - @Deprecated - public void writeToNBT(NBTTagCompound data) { - for (Tank tank : tanks) { - tank.writeToNBT(data); - } - } - - @Deprecated - public void readFromNBT(NBTTagCompound data) { - for (Tank tank : tanks) { - tank.readFromNBT(data); + t.readFromNBT(nbt.getCompoundTag(t.getTankName())); } } diff --git a/common/buildcraft/lib/recipe/RefineryRecipeRegistry.java b/common/buildcraft/lib/recipe/RefineryRecipeRegistry.java index b81e15f9ef..16eb2b12e3 100644 --- a/common/buildcraft/lib/recipe/RefineryRecipeRegistry.java +++ b/common/buildcraft/lib/recipe/RefineryRecipeRegistry.java @@ -29,13 +29,13 @@ public enum RefineryRecipeRegistry implements IRefineryRecipeManager { public final IRefineryRegistry coolableRegistry = new SingleRegistry<>(); @Override - public IHeatableRecipe createHeatingRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo, int ticks) { - return new HeatableRecipe(ticks, in, out, heatFrom, heatTo); + public IHeatableRecipe createHeatingRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo) { + return new HeatableRecipe(in, out, heatFrom, heatTo); } @Override - public ICoolableRecipe createCoolableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo, int ticks) { - return new CoolableRecipe(ticks, in, out, heatFrom, heatTo); + public ICoolableRecipe createCoolableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo) { + return new CoolableRecipe(in, out, heatFrom, heatTo); } @Override @@ -156,23 +156,16 @@ public long powerRequired() { } public static abstract class HeatExchangeRecipe extends RefineryRecipe implements IHeatExchangerRecipe { - private final int ticks; private final FluidStack out; private final int heatFrom, heatTo; - public HeatExchangeRecipe(int ticks, FluidStack in, FluidStack out, int heatFrom, int heatTo) { + public HeatExchangeRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo) { super(in); - this.ticks = ticks; this.out = out; this.heatFrom = heatFrom; this.heatTo = heatTo; } - @Override - public int ticks() { - return ticks; - } - @Override public FluidStack out() { return out; @@ -190,14 +183,14 @@ public int heatTo() { } public static class HeatableRecipe extends HeatExchangeRecipe implements IHeatableRecipe { - public HeatableRecipe(int ticks, FluidStack in, FluidStack out, int heatFrom, int heatTo) { - super(ticks, in, out, heatFrom, heatTo); + public HeatableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo) { + super(in, out, heatFrom, heatTo); } } public static class CoolableRecipe extends HeatExchangeRecipe implements ICoolableRecipe { - public CoolableRecipe(int ticks, FluidStack in, FluidStack out, int heatFrom, int heatTo) { - super(ticks, in, out, heatFrom, heatTo); + public CoolableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo) { + super(in, out, heatFrom, heatTo); } } } diff --git a/common/buildcraft/lib/tile/TileBC_Neptune.java b/common/buildcraft/lib/tile/TileBC_Neptune.java index 17ab4b42f6..516db7fb67 100644 --- a/common/buildcraft/lib/tile/TileBC_Neptune.java +++ b/common/buildcraft/lib/tile/TileBC_Neptune.java @@ -57,6 +57,7 @@ import buildcraft.lib.debug.IAdvDebugTarget; import buildcraft.lib.delta.DeltaManager; import buildcraft.lib.delta.DeltaManager.EnumDeltaMessage; +import buildcraft.lib.fluid.TankManager; import buildcraft.lib.migrate.BCVersion; import buildcraft.lib.misc.BlockUtil; import buildcraft.lib.misc.InventoryUtil; @@ -75,7 +76,7 @@ import buildcraft.lib.tile.item.ItemHandlerManager; public abstract class TileBC_Neptune extends TileEntity implements IPayloadReceiver, IAdvDebugTarget, IPlayerOwned { - public static final boolean DEBUG_PARTICLES = BCDebugging.shouldDebugLog("tile.debug.particles"); + public static final boolean DEBUG = BCDebugging.shouldDebugLog("tile.debug.network"); protected static final IdAllocator IDS = new IdAllocator("tile"); @@ -106,6 +107,7 @@ public abstract class TileBC_Neptune extends TileEntity implements IPayloadRecei protected final CapabilityHelper caps = new CapabilityHelper(); protected final ItemHandlerManager itemManager = caps.addProvider(new ItemHandlerManager(this::onSlotChange)); + protected final TankManager tankManager = new TankManager(); /** Handles all of the players that are currently using this tile (have a GUI open) */ private final Set usingPlayers = Sets.newIdentityHashSet(); @@ -171,7 +173,7 @@ public final IBlockState getOffsetState(Vec3i offset) { /** @param pos The absolute position of the {@link IBlockState} . */ public final IBlockState getLocalState(BlockPos pos) { - return BlockUtil.getBlockState(world, pos, isInThisChunk(pos)); + return BlockUtil.getBlockState(world, pos, true); } public final TileEntity getNeighbourTile(EnumFacing offset) { @@ -186,12 +188,7 @@ public final TileEntity getOffsetTile(Vec3i offset) { /** @param pos The absolute position of the {@link TileEntity} . */ public final TileEntity getLocalTile(BlockPos pos) { - return BlockUtil.getTileEntity(world, pos, isInThisChunk(pos)); - } - - private boolean isInThisChunk(BlockPos other) { - return pos.getX() >> 4 == other.getX() >> 4// - && pos.getZ() >> 4 == other.getZ() >> 4; + return BlockUtil.getTileEntity(world, pos, true); } // ################## @@ -298,8 +295,8 @@ public PermissionUtil.PermissionBlock getPermBlock() { } public boolean canEditOther(BlockPos other) { - return PermissionUtil.hasPermission(PermissionUtil.PERM_EDIT, getPermBlock(), PermissionUtil.createFrom(world, - other)); + return PermissionUtil.hasPermission(PermissionUtil.PERM_EDIT, getPermBlock(), + PermissionUtil.createFrom(world, other)); } public boolean canPlayerEdit(EntityPlayer player) { @@ -330,7 +327,7 @@ public final void redrawBlock() { IBlockState state = world.getBlockState(pos); world.notifyBlockUpdate(pos, state, state, 0); - if (DEBUG_PARTICLES) { + if (DEBUG) { double x = pos.getX() + 0.5; double y = pos.getY() + 0.5; double z = pos.getZ() + 0.5; @@ -440,22 +437,24 @@ public void handleUpdateTag(NBTTagCompound tag) { readPayload(id, new PacketBufferBC(buf), world.isRemote ? Side.CLIENT : Side.SERVER, null); // Make sure that we actually read the entire message rather than just discarding it MessageUtil.ensureEmpty(buf, world.isRemote, getClass() + ", id = " + getIdAllocator().getNameFor(id)); + spawnReceiveParticles(id); } catch (IOException e) { throw new RuntimeException(e); } - spawnReceiveParticles(); } - private void spawnReceiveParticles() { - if (DEBUG_PARTICLES) { + private void spawnReceiveParticles(int id) { + if (DEBUG) { + String name = getIdAllocator().getNameFor(id); + if (world != null) { double x = pos.getX() + 0.5; double y = pos.getY() + 0.5; double z = pos.getZ() + 0.5; - double dx = Math.random() - 0.5; - double dy = Math.random() - 1; - double dz = Math.random() - 0.5; - world.spawnParticle(EnumParticleTypes.DAMAGE_INDICATOR, x, y, z, dx, dy, dz); + double r = 0.01 + (id & 3) / 4.0; + double g = 0.01 + ((id / 4) & 3) / 4.0; + double b = 0.01 + ((id / 16) & 3) / 4.0; + world.spawnParticle(EnumParticleTypes.REDSTONE, x, y, z, r, g, b); } } } @@ -469,7 +468,7 @@ public final IMessage receivePayload(MessageContext ctx, PacketBufferBC buffer) MessageUtil.ensureEmpty(buffer, world.isRemote, getClass() + ", id = " + getIdAllocator().getNameFor(id)); if (ctx.side == Side.CLIENT) { - spawnReceiveParticles(); + spawnReceiveParticles(id); } return null; } @@ -513,12 +512,9 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext if (side == Side.CLIENT) { if (id == NET_RENDER_DATA) deltaManager.receiveDeltaData(false, EnumDeltaMessage.CURRENT_STATE, buffer); else if (id == NET_GUI_DATA) deltaManager.receiveDeltaData(true, EnumDeltaMessage.CURRENT_STATE, buffer); - else if (id == NET_REN_DELTA_SINGLE) deltaManager.receiveDeltaData(false, EnumDeltaMessage.ADD_SINGLE, - buffer); - else if (id == NET_GUI_DELTA_SINGLE) deltaManager.receiveDeltaData(true, EnumDeltaMessage.ADD_SINGLE, - buffer); - else if (id == NET_REN_DELTA_CLEAR) deltaManager.receiveDeltaData(false, EnumDeltaMessage.SET_VALUE, - buffer); + else if (id == NET_REN_DELTA_SINGLE) deltaManager.receiveDeltaData(false, EnumDeltaMessage.ADD_SINGLE, buffer); + else if (id == NET_GUI_DELTA_SINGLE) deltaManager.receiveDeltaData(true, EnumDeltaMessage.ADD_SINGLE, buffer); + else if (id == NET_REN_DELTA_CLEAR) deltaManager.receiveDeltaData(false, EnumDeltaMessage.SET_VALUE, buffer); else if (id == NET_GUI_DELTA_CLEAR) deltaManager.receiveDeltaData(true, EnumDeltaMessage.SET_VALUE, buffer); else if (id == NET_REDRAW) redrawBlock(); else if (id == NET_ADV_DEBUG) { @@ -536,10 +532,7 @@ else if (id == NET_ADV_DEBUG) { @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); - int version = nbt.getInteger("data-version"); - if (version != BCVersion.CURRENT.dataVersion) { - migrateOldNBT(version, nbt); - } + migrateOldNBT(nbt.getInteger("data-version"), nbt); deltaManager.readFromNBT(nbt.getCompoundTag("deltas")); if (nbt.hasKey("owner")) { owner = NBTUtil.readGameProfileFromNBT(nbt.getCompoundTag("owner")); @@ -550,9 +543,21 @@ public void readFromNBT(NBTTagCompound nbt) { if (nbt.hasKey("items", Constants.NBT.TAG_COMPOUND)) { itemManager.deserializeNBT(nbt.getCompoundTag("items")); } + if (nbt.hasKey("tanks",Constants.NBT.TAG_COMPOUND)) { + tankManager.deserializeNBT(nbt.getCompoundTag("tanks")); + } } - protected void migrateOldNBT(int version, NBTTagCompound nbt) {} + protected void migrateOldNBT(int version, NBTTagCompound nbt) { + // 7.99.0 -> 7.99.4 + // Most tiles with a single tank saved it under "tank" + NBTTagCompound tankComp = nbt.getCompoundTag("tank"); + if (!tankComp.hasNoTags()) { + NBTTagCompound tanks = new NBTTagCompound(); + tanks.setTag("tank", tankComp); + nbt.setTag("tanks", tanks); + } + } @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { @@ -566,7 +571,12 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { if (!items.hasNoTags()) { nbt.setTag("items", items); } + NBTTagCompound tanks = tankManager.serializeNBT(); + if (!tanks.hasNoTags()) { + nbt.setTag("tanks", tanks); + } + markDirty(); return nbt; } @@ -574,6 +584,9 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { protected void setWorldCreate(World world) { // The default impl doesn't actually set the world for some reason :/ setWorld(world); + if (hasWorld()) { + markDirty(); + } } // ################## diff --git a/common/buildcraft/transport/BCTransportConfig.java b/common/buildcraft/transport/BCTransportConfig.java index 7c07d29622..f2d699327d 100644 --- a/common/buildcraft/transport/BCTransportConfig.java +++ b/common/buildcraft/transport/BCTransportConfig.java @@ -94,9 +94,9 @@ public static void reloadConfig(EnumRestartRequirement restarted) { fluidTransfer(BCTransportPipes.clayFluid, baseFlowRate * 4, 10); fluidTransfer(BCTransportPipes.ironFluid, baseFlowRate * 4, 10); fluidTransfer(BCTransportPipes.quartzFluid, baseFlowRate * 4, 10); - fluidTransfer(BCTransportPipes.diaWoodFluid, baseFlowRate * 4, 10); fluidTransfer(BCTransportPipes.diamondFluid, baseFlowRate * 8, 10); + fluidTransfer(BCTransportPipes.diaWoodFluid, baseFlowRate * 8, 10); fluidTransfer(BCTransportPipes.goldFluid, baseFlowRate * 8, 2); powerTransfer(BCTransportPipes.cobblePower, basePowerRate, 16, false); diff --git a/common/buildcraft/transport/client/render/PipeFlowRendererFluids.java b/common/buildcraft/transport/client/render/PipeFlowRendererFluids.java index 863e62ae9c..ad3e5c825e 100644 --- a/common/buildcraft/transport/client/render/PipeFlowRendererFluids.java +++ b/common/buildcraft/transport/client/render/PipeFlowRendererFluids.java @@ -62,8 +62,9 @@ public void render(PipeFlowFluids flow, double x, double y, double z, float part fluidBuffer.begin(GL11.GL_QUADS, DefaultVertexFormats.BLOCK); fluidBuffer.setTranslation(x, y, z); + boolean gas = forRender.getFluid().isGaseous(forRender); boolean horizontal = false; - boolean vertical = flow.pipe.isConnected(EnumFacing.UP); + boolean vertical = flow.pipe.isConnected(gas ? EnumFacing.DOWN : EnumFacing.UP); for (EnumFacing face : EnumFacing.VALUES) { double size = ((Pipe) flow.pipe).getConnectedDist(face); @@ -121,9 +122,12 @@ public void render(PipeFlowFluids flow, double x, double y, double z, float part perc = Math.sqrt(perc); double minXZ = 0.5 - 0.24 * perc; double maxXZ = 0.5 + 0.24 * perc; + + double yMin = gas ? 0.26 : horizPos; + double yMax = gas ? 1 - horizPos : 0.74; - Vec3d min = new Vec3d(minXZ, horizPos, minXZ); - Vec3d max = new Vec3d(maxXZ, 0.74, maxXZ); + Vec3d min = new Vec3d(minXZ, yMin, minXZ); + Vec3d max = new Vec3d(maxXZ, yMax, maxXZ); min = min.add(offset); max = max.add(offset); diff --git a/common_old_license/buildcraft/factory/tile/TileFloodGate.java b/common_old_license/buildcraft/factory/tile/TileFloodGate.java index 1fd7848003..2536cef21d 100644 --- a/common_old_license/buildcraft/factory/tile/TileFloodGate.java +++ b/common_old_license/buildcraft/factory/tile/TileFloodGate.java @@ -42,7 +42,8 @@ import buildcraft.factory.client.render.AdvDebuggerFloodGate; public class TileFloodGate extends TileBC_Neptune implements ITickable, IDebuggable { - public static final EnumFacing[] SIDE_INDEXES = new EnumFacing[] { EnumFacing.DOWN, EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.WEST, EnumFacing.EAST }; + public static final EnumFacing[] SIDE_INDEXES = + new EnumFacing[] { EnumFacing.DOWN, EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.WEST, EnumFacing.EAST }; public static final int[] REBUILD_DELAYS = new int[] { 128, 256, 512, 1024, 2048, 4096, 8192, 16384 }; private boolean[] sidesBlocked = new boolean[5]; @@ -55,6 +56,7 @@ public class TileFloodGate extends TileBC_Neptune implements ITickable, IDebugga public final TreeMap> clientLayerQueues = new TreeMap<>(); public TileFloodGate() { + tankManager.add(tank); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tank, EnumPipePart.VALUES); } @@ -106,7 +108,8 @@ private void tryAddToQueue(BlockPos blockPos, Set visitedBlocks, Deque return; } if (visitedBlocks.add(currentPos)) { - if ((currentPos.getX() - pos.getX()) * (currentPos.getX() - pos.getX()) + (currentPos.getZ() - pos.getZ()) * (currentPos.getZ() - pos.getZ()) > 64 * 64) { + if ((currentPos.getX() - pos.getX()) * (currentPos.getX() - pos.getX()) + + (currentPos.getZ() - pos.getZ()) * (currentPos.getZ() - pos.getZ()) > 64 * 64) { return; } @@ -119,7 +122,8 @@ private void tryAddToQueue(BlockPos blockPos, Set visitedBlocks, Deque if (world.isAirBlock(currentPos) || block instanceof BlockFloodGate || isCurrentFluid) { blocksFound.add(currentPos); - if (world.isAirBlock(currentPos) || (isCurrentFluid && blockState.getValue(BlockLiquid.LEVEL) != 0)) { + if (world.isAirBlock(currentPos) + || (isCurrentFluid && blockState.getValue(BlockLiquid.LEVEL) != 0)) { getLayerQueue(currentPos.getY()).addLast(currentPos); } } @@ -200,7 +204,6 @@ public IDetachedRenderer getDebugRenderer() { @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); - tank.readFromNBT(nbt); for (int i = 0; i < sidesBlocked.length; i++) { nbt.setBoolean("sides_blocked_" + i, sidesBlocked[i]); } @@ -209,7 +212,6 @@ public void readFromNBT(NBTTagCompound nbt) { @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); - tank.writeToNBT(nbt); for (int i = 0; i < sidesBlocked.length; i++) { sidesBlocked[i] = nbt.getBoolean("sides_blocked_" + i); } diff --git a/src/test/java/buildcraft/test/lib/fluid/TankManagerTester.java b/src/test/java/buildcraft/test/lib/fluid/TankManagerTester.java index 5c60bec61f..414acb164b 100644 --- a/src/test/java/buildcraft/test/lib/fluid/TankManagerTester.java +++ b/src/test/java/buildcraft/test/lib/fluid/TankManagerTester.java @@ -13,7 +13,7 @@ public class TankManagerTester extends VanillaSetupBaseTester { @Test public void testSimpleMoving() { - TankManager manager = new TankManager<>(); + TankManager manager = new TankManager(); manager.add(new Tank("tank_1", 3, null)); Assert.assertEquals(2, manager.fill(new FluidStack(FluidRegistry.WATER, 2), true)); Assert.assertEquals(1, manager.fill(new FluidStack(FluidRegistry.WATER, 2), true)); diff --git a/src_old_license/buildcraft/factory/refining/ComplexRefineryRecipeManager.java b/src_old_license/buildcraft/factory/refining/ComplexRefineryRecipeManager.java index 9765edf7ac..84ca01903e 100644 --- a/src_old_license/buildcraft/factory/refining/ComplexRefineryRecipeManager.java +++ b/src_old_license/buildcraft/factory/refining/ComplexRefineryRecipeManager.java @@ -19,23 +19,23 @@ public enum ComplexRefineryRecipeManager implements IRefineryRecipeManager { private final ComplexRefineryRegistry distillationRegistry = new ComplexRefineryRegistry<>(); @Override - public IHeatableRecipe createHeatingRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo, int ticks) { + public IHeatableRecipe createHeatingRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo) { return new HeatableRecipe(ticks, in, out, heatFrom, heatTo); } @Override public IHeatableRecipe addHeatableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo, int ticks, boolean replaceExisting) { - return getHeatableRegistry().addRecipe(createHeatingRecipe(in, out, heatFrom, heatTo, ticks), replaceExisting); + return getHeatableRegistry().addRecipe(createHeatingRecipe(in, out, heatFrom, heatTo), replaceExisting); } @Override - public ICoolableRecipe createCoolableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo, int ticks) { + public ICoolableRecipe createCoolableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo) { return new CoolableRecipe(ticks, in, out, heatFrom, heatTo); } @Override public ICoolableRecipe addCoolableRecipe(FluidStack in, FluidStack out, int heatFrom, int heatTo, int ticks, boolean replaceExisting) { - return getCoolableRegistry().addRecipe(createCoolableRecipe(in, out, heatFrom, heatTo, ticks), replaceExisting); + return getCoolableRegistry().addRecipe(createCoolableRecipe(in, out, heatFrom, heatTo), replaceExisting); } @Override From 3f1a557dc8e09f652cd40d8716a7ab8ae385bb50 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Sat, 1 Jul 2017 14:55:45 +0100 Subject: [PATCH 74/89] Remove a few unessecary null checks. --- .../energy/tile/TileEngineIron_BC8.java | 44 ++++++++----------- 1 file changed, 19 insertions(+), 25 deletions(-) diff --git a/common/buildcraft/energy/tile/TileEngineIron_BC8.java b/common/buildcraft/energy/tile/TileEngineIron_BC8.java index 3b522f8b74..96462bf072 100644 --- a/common/buildcraft/energy/tile/TileEngineIron_BC8.java +++ b/common/buildcraft/energy/tile/TileEngineIron_BC8.java @@ -37,7 +37,6 @@ import buildcraft.lib.engine.EngineConnector; import buildcraft.lib.engine.TileEngineBase_BC8; import buildcraft.lib.fluid.Tank; -import buildcraft.lib.fluid.TankManager; import buildcraft.lib.fluid.TankProperties; import buildcraft.lib.gui.help.ElementHelpInfo; import buildcraft.lib.misc.CapUtil; @@ -134,7 +133,8 @@ public void writePayload(int id, PacketBufferBC buffer, Side side) { // TileEngineBase overrrides @Override - public boolean onActivated(EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { + public boolean onActivated(EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, + float hitZ) { ItemStack current = player.getHeldItem(hand); if (!current.isEmpty()) { if (EntityUtil.getWrenchHand(player) != null) { @@ -185,12 +185,12 @@ public boolean isBurning() { @Override protected void burn() { - FluidStack fuel = this.tankFuel.getFluid(); + final FluidStack fuel = this.tankFuel.getFluid(); if (currentFuel == null || !currentFuel.getFluid().isFluidEqual(fuel)) { currentFuel = BuildcraftFuelRegistry.fuel.getFuel(fuel); } - if (currentFuel == null) { + if (fuel == null || currentFuel == null) { return; } @@ -198,32 +198,26 @@ protected void burn() { if (isRedstonePowered) { lastPowered = true; - if (burnTime > 0 || (fuel != null && fuel.amount > 0)) { + if (burnTime > 0 || fuel.amount > 0) { if (burnTime > 0) { burnTime--; } if (burnTime <= 0) { - if (fuel != null) { - if (--fuel.amount <= 0) { - tankFuel.setFluid(null); - } - burnTime += currentFuel.getTotalBurningTime() / 1000.0; - - // If we also produce residue then put it out too - if (currentFuel instanceof IDirtyFuel) { - IDirtyFuel dirtyFuel = (IDirtyFuel) currentFuel; - residueAmount += dirtyFuel.getResidue().amount / 1000.0; - if (residueAmount >= 1) { - int residue = MathHelper.floor(residueAmount); - FluidStack residueFluid = dirtyFuel.getResidue().copy(); - residueFluid.amount = residue; - residueAmount -= tankResidue.fill(residueFluid, true); - } + if (--fuel.amount <= 0) { + tankFuel.setFluid(null); + } + burnTime += currentFuel.getTotalBurningTime() / 1000.0; + + // If we also produce residue then put it out too + if (currentFuel instanceof IDirtyFuel) { + IDirtyFuel dirtyFuel = (IDirtyFuel) currentFuel; + residueAmount += dirtyFuel.getResidue().amount / 1000.0; + if (residueAmount >= 1) { + int residue = MathHelper.floor(residueAmount); + FluidStack residueFluid = dirtyFuel.getResidue().copy(); + residueFluid.amount = residue; + residueAmount -= tankResidue.fill(residueFluid, true); } - } else { - currentFuel = null; - residueAmount = 0; - return; } } currentOutput = currentFuel.getPowerPerCycle(); // Comment out for constant power From d854ce25467101dbf0e7b3d138bfd0a009acf2db Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Sun, 2 Jul 2017 16:46:06 +0300 Subject: [PATCH 75/89] Fix quarry iterating --- .../builders/snapshot/SnapshotBuilder.java | 33 +-- .../buildcraft/builders/tile/TileQuarry.java | 257 ++++++++++++++---- common/buildcraft/lib/misc/NBTUtilBC.java | 1 - .../buildcraft/lib/misc/data/BoxIterator.java | 4 +- 4 files changed, 227 insertions(+), 68 deletions(-) diff --git a/common/buildcraft/builders/snapshot/SnapshotBuilder.java b/common/buildcraft/builders/snapshot/SnapshotBuilder.java index 8105037b98..211f149b3d 100644 --- a/common/buildcraft/builders/snapshot/SnapshotBuilder.java +++ b/common/buildcraft/builders/snapshot/SnapshotBuilder.java @@ -21,6 +21,7 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; +import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.collect.ImmutableMap; @@ -54,10 +55,10 @@ public abstract class SnapshotBuilder { protected final T tile; private final IWorldEventListener worldEventListener = new IWorldEventListener() { @Override - public void notifyBlockUpdate(World world, - BlockPos pos, - IBlockState oldState, - IBlockState newState, + public void notifyBlockUpdate(@Nonnull World world, + @Nonnull BlockPos pos, + @Nonnull IBlockState oldState, + @Nonnull IBlockState newState, int flags) { if (tile.getBuilder() == SnapshotBuilder.this) { check(pos); @@ -65,7 +66,7 @@ public void notifyBlockUpdate(World world, } @Override - public void notifyLightSet(BlockPos pos) { + public void notifyLightSet(@Nonnull BlockPos pos) { } @Override @@ -74,8 +75,8 @@ public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2 @Override public void playSoundToAllNearExcept(@Nullable EntityPlayer player, - SoundEvent soundIn, - SoundCategory category, + @Nonnull SoundEvent sound, + @Nonnull SoundCategory category, double x, double y, double z, @@ -84,7 +85,7 @@ public void playSoundToAllNearExcept(@Nullable EntityPlayer player, } @Override - public void playRecord(SoundEvent soundIn, BlockPos pos) { + public void playRecord(@Nonnull SoundEvent sound, @Nonnull BlockPos pos) { } @Override @@ -96,40 +97,40 @@ public void spawnParticle(int particleID, double xSpeed, double ySpeed, double zSpeed, - int... parameters) { + @Nonnull int... parameters) { } @Override public void spawnParticle(int id, boolean ignoreRange, - boolean p_190570_3_, + boolean minParticles, double x, double y, double z, double xSpeed, double ySpeed, double zSpeed, - int... parameters) { + @Nonnull int... parameters) { } @Override - public void onEntityAdded(Entity entityIn) { + public void onEntityAdded(@Nonnull Entity entity) { } @Override - public void onEntityRemoved(Entity entityIn) { + public void onEntityRemoved(@Nonnull Entity entity) { } @Override - public void broadcastSound(int soundID, BlockPos pos, int data) { + public void broadcastSound(int soundID, @Nonnull BlockPos pos, int data) { } @Override - public void playEvent(EntityPlayer player, int type, BlockPos blockPosIn, int data) { + public void playEvent(@Nullable EntityPlayer player, int type, @Nonnull BlockPos blockPos, int data) { } @Override - public void sendBlockBreakProgress(int breakerId, BlockPos pos, int progress) { + public void sendBlockBreakProgress(int breakerId, @Nonnull BlockPos pos, int progress) { } }; private final Queue breakTasks = new ArrayDeque<>(); diff --git a/common/buildcraft/builders/tile/TileQuarry.java b/common/buildcraft/builders/tile/TileQuarry.java index a07425bc25..be85f2e1ab 100644 --- a/common/buildcraft/builders/tile/TileQuarry.java +++ b/common/buildcraft/builders/tile/TileQuarry.java @@ -12,17 +12,23 @@ import java.util.Collections; import java.util.Comparator; import java.util.HashSet; +import java.util.LinkedList; import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; import java.util.function.Function; import java.util.function.Predicate; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import com.google.common.collect.ImmutableList; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -30,9 +36,13 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing.Axis; import net.minecraft.util.ITickable; +import net.minecraft.util.SoundCategory; +import net.minecraft.util.SoundEvent; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; +import net.minecraft.world.IWorldEventListener; +import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.MinecraftForge; @@ -52,7 +62,7 @@ import buildcraft.lib.block.BlockBCBase_Neptune; import buildcraft.lib.inventory.AutomaticProvidingTransactor; -import buildcraft.lib.inventory.ItemTransactorHelper; +import buildcraft.lib.inventory.TransactorEntityItem; import buildcraft.lib.inventory.filter.StackFilter; import buildcraft.lib.misc.BlockUtil; import buildcraft.lib.misc.BoundingBoxUtil; @@ -79,6 +89,14 @@ public class TileQuarry extends TileBC_Neptune implements ITickable, IDebuggable public final Box frameBox = new Box(); private final Box miningBox = new Box(); private BoxIterator boxIterator; + private final Set frameBoxPoses = new HashSet<>(); + private final LinkedList toCheck = new LinkedList<>(); + private final Set firstCheckedPoses = new HashSet<>(); + private boolean firstChecked = false; + private final Set frameBreakBlockPoses = new TreeSet<>( + Comparator.comparingDouble(pos::distanceSq) + ); + private final Set framePlaceFramePoses = new HashSet<>(); public Task currentTask = null; public Vec3d drillPos; public Vec3d clientDrillPos; @@ -87,6 +105,101 @@ public class TileQuarry extends TileBC_Neptune implements ITickable, IDebuggable * Recent power input, in MJ (not micro) */ private final AverageInt recentPowerAverage = new AverageInt(200); + private final IWorldEventListener worldEventListener = new IWorldEventListener() { + @Override + public void notifyBlockUpdate(@Nonnull World world, + @Nonnull BlockPos pos, + @Nonnull IBlockState oldState, + @Nonnull IBlockState newState, + int flags) { + if (frameBox.isInitialized() && miningBox.isInitialized()) { + if (frameBox.contains(pos)) { + check(pos); + } else if (miningBox.contains(pos)) { + if (!world.isAirBlock(pos) && boxIterator != null) { + BoxIterator tempBoxIterator = createBoxIterator(); + while (!Objects.equals(tempBoxIterator.getCurrent(), pos)) { + if (tempBoxIterator.advance() == null) { + return; + } + if (Objects.equals(tempBoxIterator.getCurrent(), boxIterator.getCurrent())) { + return; + } + } + boxIterator = tempBoxIterator; + } + } + } + } + + @Override + public void notifyLightSet(@Nonnull BlockPos pos) { + } + + @Override + public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2, int z2) { + } + + @Override + public void playSoundToAllNearExcept(@Nullable EntityPlayer player, + @Nonnull SoundEvent sound, + @Nonnull SoundCategory category, + double x, + double y, + double z, + float volume, + float pitch) { + } + + @Override + public void playRecord(@Nonnull SoundEvent sound, @Nonnull BlockPos pos) { + } + + @Override + public void spawnParticle(int particleID, + boolean ignoreRange, + double xCoord, + double yCoord, + double zCoord, + double xSpeed, + double ySpeed, + double zSpeed, + @Nonnull int... parameters) { + } + + @Override + public void spawnParticle(int id, + boolean ignoreRange, + boolean minParticles, + double x, + double y, + double z, + double xSpeed, + double ySpeed, + double zSpeed, + @Nonnull int... parameters) { + } + + @Override + public void onEntityAdded(@Nonnull Entity entity) { + } + + @Override + public void onEntityRemoved(@Nonnull Entity entity) { + } + + @Override + public void broadcastSound(int soundID, @Nonnull BlockPos pos, int data) { + } + + @Override + public void playEvent(@Nullable EntityPlayer player, int type, @Nonnull BlockPos blockPos, int data) { + } + + @Override + public void sendBlockBreakProgress(int breakerId, @Nonnull BlockPos pos, int progress) { + } + }; public TileQuarry() { caps.addProvider(new MjCapabilityHelper(new MjBatteryReciver(battery) { @@ -102,6 +215,11 @@ public long receivePower(long microJoules, boolean simulate) { caps.addCapabilityInstance(CapUtil.CAP_ITEM_TRANSACTOR, AutomaticProvidingTransactor.INSTANCE, EnumPipePart.VALUES); } + @Nonnull + private BoxIterator createBoxIterator() { + return new BoxIterator(miningBox, AxisOrder.getFor(EnumAxisOrder.XZY, AxisOrder.Inversion.NNN), true); + } + public List getFramePositions(IBlockState state) { List framePositions = new ArrayList<>(); @@ -156,6 +274,16 @@ public List getFramePositions(IBlockState state) { return framePositionsSorted; } + private boolean isShouldBeFrame(BlockPos p) { + boolean shouldBeFrameXY = (p.getX() == frameBox.min().getX() || p.getX() == frameBox.max().getX()) && + (p.getY() == frameBox.min().getY() || p.getY() == frameBox.max().getY()); + boolean shouldBeFrameYZ = (p.getY() == frameBox.min().getY() || p.getY() == frameBox.max().getY()) && + (p.getZ() == frameBox.min().getZ() || p.getZ() == frameBox.max().getZ()); + boolean shouldBeFrameZX = (p.getZ() == frameBox.min().getZ() || p.getZ() == frameBox.max().getZ()) && + (p.getX() == frameBox.min().getX() || p.getX() == frameBox.max().getX()); + return shouldBeFrameXY || shouldBeFrameYZ || shouldBeFrameZX; + } + public List getFramePositions() { IBlockState state = world.getBlockState(pos); if (state.getBlock() != BCBuildersBlocks.quarry) { @@ -213,6 +341,7 @@ public void onPlacedBy(EntityLivingBase placer, ItemStack stack) { miningBox.reset(); miningBox.setMin(new BlockPos(min.getX() + 1, 0, min.getZ() + 1)); miningBox.setMax(new BlockPos(max.getX() - 1, max.getY() - 1, max.getZ() - 1)); + onLoad(); } private boolean canNotMine(BlockPos blockPos) { @@ -228,16 +357,56 @@ private boolean canSkip(BlockPos blockPos) { return fluid != null && fluid.getViscosity() <= 1000; } + private void check(BlockPos blockPos) { + frameBreakBlockPoses.remove(blockPos); + framePlaceFramePoses.remove(blockPos); + if (isShouldBeFrame(blockPos)) { + if (world.getBlockState(blockPos).getBlock() != BCBuildersBlocks.frame) { + if (!world.isAirBlock(blockPos)) { + frameBreakBlockPoses.add(blockPos); + } else { + framePlaceFramePoses.add(blockPos); + } + } + } else { + if (!world.isAirBlock(blockPos)) { + frameBreakBlockPoses.add(blockPos); + } + } + if (!firstChecked) { + firstCheckedPoses.add(blockPos); + if (firstCheckedPoses.containsAll(frameBoxPoses)) { + firstChecked = true; + } + } + } + @Override public void validate() { super.validate(); BCBuildersEventDist.INSTANCE.validateQuarry(this); + if (!world.isRemote) { + world.addEventListener(worldEventListener); + } } @Override public void invalidate() { super.invalidate(); BCBuildersEventDist.INSTANCE.invalidateQuarry(this); + if (!world.isRemote) { + world.removeEventListener(worldEventListener); + } + } + + @Override + public void onLoad() { + frameBoxPoses.clear(); + if (frameBox.isInitialized()) { + frameBoxPoses.addAll(frameBox.getBlocksInArea()); + } + toCheck.clear(); + toCheck.addAll(frameBoxPoses); } @Override @@ -255,8 +424,6 @@ public void update() { if (!frameBox.isInitialized() || !miningBox.isInitialized()) { return; } - BlockPos min = frameBox.min(); - BlockPos max = frameBox.max(); /* if (drillPos != null) { @@ -297,6 +464,14 @@ public void update() { } */ + if (!toCheck.isEmpty()) { + for (int i = 0; i < (firstChecked ? 10 : 50); i++) { + BlockPos blockPos = toCheck.pollFirst(); + check(blockPos); + toCheck.addLast(blockPos); + } + } + if (currentTask != null) { long maxToExtract = MjAPI.MJ * 10; if (currentTask.addPower( @@ -311,59 +486,39 @@ public void update() { return; } - List breakPoses = new ArrayList<>(); - - for (int x = min.getX(); x <= max.getX(); x++) { - for (int y = min.getY(); y <= max.getY(); y++) { - for (int z = min.getZ(); z <= max.getZ(); z++) { - BlockPos framePos = new BlockPos(x, y, z); - boolean shouldBeFrame = ((x == min.getX() || x == max.getX()) && (y == min.getY() || y == max.getY())) || - ((y == min.getY() || y == max.getY()) && (z == min.getZ() || z == max.getZ())) || - ((z == min.getZ() || z == max.getZ()) && (x == min.getX() || x == max.getX())); - boolean isAir = world.isAirBlock(framePos); - if (shouldBeFrame - ? !isAir && world.getBlockState(framePos).getBlock() != BCBuildersBlocks.frame - : !isAir) { - if (!canSkip(framePos)) { - breakPoses.add(framePos); - } - } - } - } + if (!firstChecked) { + return; } - if (breakPoses.size() > 0) { - double closestDistance = Double.MAX_VALUE; - BlockPos closestPos = null; - - for (BlockPos breakPos : breakPoses) { - double distance = breakPos.distanceSq(pos); - - if (distance < closestDistance) { - closestDistance = distance; - closestPos = breakPos; - } - } - - if (!canNotMine(closestPos)) { + if (!frameBreakBlockPoses.isEmpty()) { + BlockPos blockPos = frameBreakBlockPoses.iterator().next(); + if (!canNotMine(blockPos)) { drillPos = null; - currentTask = new TaskBreakBlock(closestPos); + currentTask = new TaskBreakBlock(blockPos); sendNetworkUpdate(NET_RENDER_DATA); } + check(blockPos); return; } - for (BlockPos framePos : getFramePositions()) { - if (world.isAirBlock(framePos)) { + if (!framePlaceFramePoses.isEmpty()) { + for (BlockPos blockPos : getFramePositions()) { + if (!framePlaceFramePoses.contains(blockPos)) { + continue; + } + check(blockPos); + if (!framePlaceFramePoses.contains(blockPos)) { + continue; + } drillPos = null; - currentTask = new TaskAddFrame(framePos); + currentTask = new TaskAddFrame(blockPos); sendNetworkUpdate(NET_RENDER_DATA); return; } } - if ((boxIterator == null || drillPos == null) && miningBox.isInitialized()) { - boxIterator = new BoxIterator(miningBox, AxisOrder.getFor(EnumAxisOrder.XZY, AxisOrder.Inversion.NNN), true); + if (boxIterator == null || drillPos == null) { + boxIterator = createBoxIterator(); while (world.isAirBlock(boxIterator.getCurrent()) || canSkip(boxIterator.getCurrent())) { if (boxIterator.advance() == null) { break; @@ -422,6 +577,7 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { if (drillPos != null) { nbt.setTag("drillPos", NBTUtilBC.writeVec3d(drillPos)); } + nbt.setBoolean("firstChecked", firstChecked); return nbt; } @@ -439,6 +595,7 @@ public void readFromNBT(NBTTagCompound nbt) { currentTask = null; } drillPos = NBTUtilBC.readVec3d(nbt.getTag("drillPos")); + firstChecked = nbt.getBoolean("firstChecked"); } @Override @@ -565,7 +722,7 @@ private enum EnumTaskType { ADD_FRAME(TaskAddFrame.class, quarry -> quarry.new TaskAddFrame()), MOVE_DRILL(TaskMoveDrill.class, quarry -> quarry.new TaskMoveDrill()); - public final Class clazz; + public final Class clazz; public final Function supplier; EnumTaskType(Class clazz, Function supplier) { @@ -701,14 +858,15 @@ protected boolean finish() { BlockEvent.BreakEvent breakEvent = new BlockEvent.BreakEvent(world, breakPos, state, fake); MinecraftForge.EVENT_BUS.post(breakEvent); if (!breakEvent.isCanceled()) { - List stacks = new ArrayList<>(); // The drill pos will be null if we are making the frame: this is when we want to destroy the block, not // drop its contents world.sendBlockBreakProgress(breakPos.hashCode(), breakPos, -1); - world.destroyBlock(breakPos, true); if (drillPos != null) { + world.destroyBlock(breakPos, true); world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(breakPos)).stream() - .map(entity -> ItemTransactorHelper.getTransactorForEntity(entity, EnumFacing.UP)) + .filter(EntityItem.class::isInstance) + .map(EntityItem.class::cast) + .map(TransactorEntityItem::new) .forEach(transactor -> { ItemStack stack; while (!(stack = transactor.extract( @@ -717,13 +875,12 @@ protected boolean finish() { Integer.MAX_VALUE, false )).isEmpty()) { - stacks.add(stack); + InventoryUtil.addToBestAcceptor(world, pos, null, stack); } }); - } - for (ItemStack stack : stacks) { - InventoryUtil.addToBestAcceptor(world, pos, null, stack); + } else { + world.destroyBlock(breakPos, false); } return true; } else { diff --git a/common/buildcraft/lib/misc/NBTUtilBC.java b/common/buildcraft/lib/misc/NBTUtilBC.java index 75f691ee36..cde3edfc25 100644 --- a/common/buildcraft/lib/misc/NBTUtilBC.java +++ b/common/buildcraft/lib/misc/NBTUtilBC.java @@ -103,7 +103,6 @@ public static byte[] save(NBTTagCompound compound) { } public static NBTTagIntArray writeBlockPos(BlockPos pos) { - if (pos == null) return null; return new NBTTagIntArray(new int[] { pos.getX(), pos.getY(), pos.getZ() }); } diff --git a/common/buildcraft/lib/misc/data/BoxIterator.java b/common/buildcraft/lib/misc/data/BoxIterator.java index cdaca7e90a..4627a9e2f2 100644 --- a/common/buildcraft/lib/misc/data/BoxIterator.java +++ b/common/buildcraft/lib/misc/data/BoxIterator.java @@ -67,7 +67,9 @@ public NBTTagCompound writeToNbt() { nbt.setBoolean("invert", invert); // repeat nbt.setTag("order", order.writeNBT()); - nbt.setTag("current", NBTUtilBC.writeBlockPos(current)); + if (current != null) { + nbt.setTag("current", NBTUtilBC.writeBlockPos(current)); + } return nbt; } From d6db9b75f27de376e2d0ba9a414559219e823009 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Sun, 2 Jul 2017 16:49:45 +0300 Subject: [PATCH 76/89] Add adapter --- .../builders/snapshot/SnapshotBuilder.java | 76 +-------------- .../buildcraft/builders/tile/TileQuarry.java | 74 +------------- .../lib/world/WorldEventListenerAdapter.java | 97 +++++++++++++++++++ 3 files changed, 101 insertions(+), 146 deletions(-) create mode 100644 common/buildcraft/lib/world/WorldEventListenerAdapter.java diff --git a/common/buildcraft/builders/snapshot/SnapshotBuilder.java b/common/buildcraft/builders/snapshot/SnapshotBuilder.java index 211f149b3d..02974208ae 100644 --- a/common/buildcraft/builders/snapshot/SnapshotBuilder.java +++ b/common/buildcraft/builders/snapshot/SnapshotBuilder.java @@ -22,16 +22,11 @@ import java.util.stream.IntStream; import javax.annotation.Nonnull; -import javax.annotation.Nullable; import com.google.common.collect.ImmutableMap; import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -import net.minecraft.util.SoundCategory; -import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IWorldEventListener; @@ -48,12 +43,13 @@ import buildcraft.lib.misc.MessageUtil; import buildcraft.lib.misc.data.Box; import buildcraft.lib.net.PacketBufferBC; +import buildcraft.lib.world.WorldEventListenerAdapter; public abstract class SnapshotBuilder { private static final int MAX_QUEUE_SIZE = 64; protected final T tile; - private final IWorldEventListener worldEventListener = new IWorldEventListener() { + private final IWorldEventListener worldEventListener = new WorldEventListenerAdapter() { @Override public void notifyBlockUpdate(@Nonnull World world, @Nonnull BlockPos pos, @@ -64,74 +60,6 @@ public void notifyBlockUpdate(@Nonnull World world, check(pos); } } - - @Override - public void notifyLightSet(@Nonnull BlockPos pos) { - } - - @Override - public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2, int z2) { - } - - @Override - public void playSoundToAllNearExcept(@Nullable EntityPlayer player, - @Nonnull SoundEvent sound, - @Nonnull SoundCategory category, - double x, - double y, - double z, - float volume, - float pitch) { - } - - @Override - public void playRecord(@Nonnull SoundEvent sound, @Nonnull BlockPos pos) { - } - - @Override - public void spawnParticle(int particleID, - boolean ignoreRange, - double xCoord, - double yCoord, - double zCoord, - double xSpeed, - double ySpeed, - double zSpeed, - @Nonnull int... parameters) { - } - - @Override - public void spawnParticle(int id, - boolean ignoreRange, - boolean minParticles, - double x, - double y, - double z, - double xSpeed, - double ySpeed, - double zSpeed, - @Nonnull int... parameters) { - } - - @Override - public void onEntityAdded(@Nonnull Entity entity) { - } - - @Override - public void onEntityRemoved(@Nonnull Entity entity) { - } - - @Override - public void broadcastSound(int soundID, @Nonnull BlockPos pos, int data) { - } - - @Override - public void playEvent(@Nullable EntityPlayer player, int type, @Nonnull BlockPos blockPos, int data) { - } - - @Override - public void sendBlockBreakProgress(int breakerId, @Nonnull BlockPos pos, int progress) { - } }; private final Queue breakTasks = new ArrayDeque<>(); public final Queue clientBreakTasks = new ArrayDeque<>(); diff --git a/common/buildcraft/builders/tile/TileQuarry.java b/common/buildcraft/builders/tile/TileQuarry.java index be85f2e1ab..6f7ae2a15e 100644 --- a/common/buildcraft/builders/tile/TileQuarry.java +++ b/common/buildcraft/builders/tile/TileQuarry.java @@ -21,7 +21,6 @@ import java.util.function.Predicate; import javax.annotation.Nonnull; -import javax.annotation.Nullable; import com.google.common.collect.ImmutableList; @@ -36,8 +35,6 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing.Axis; import net.minecraft.util.ITickable; -import net.minecraft.util.SoundCategory; -import net.minecraft.util.SoundEvent; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; @@ -80,6 +77,7 @@ import buildcraft.lib.mj.MjBatteryReciver; import buildcraft.lib.net.PacketBufferBC; import buildcraft.lib.tile.TileBC_Neptune; +import buildcraft.lib.world.WorldEventListenerAdapter; import buildcraft.builders.BCBuildersBlocks; import buildcraft.builders.BCBuildersEventDist; @@ -105,7 +103,7 @@ public class TileQuarry extends TileBC_Neptune implements ITickable, IDebuggable * Recent power input, in MJ (not micro) */ private final AverageInt recentPowerAverage = new AverageInt(200); - private final IWorldEventListener worldEventListener = new IWorldEventListener() { + private final IWorldEventListener worldEventListener = new WorldEventListenerAdapter() { @Override public void notifyBlockUpdate(@Nonnull World world, @Nonnull BlockPos pos, @@ -131,74 +129,6 @@ public void notifyBlockUpdate(@Nonnull World world, } } } - - @Override - public void notifyLightSet(@Nonnull BlockPos pos) { - } - - @Override - public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2, int z2) { - } - - @Override - public void playSoundToAllNearExcept(@Nullable EntityPlayer player, - @Nonnull SoundEvent sound, - @Nonnull SoundCategory category, - double x, - double y, - double z, - float volume, - float pitch) { - } - - @Override - public void playRecord(@Nonnull SoundEvent sound, @Nonnull BlockPos pos) { - } - - @Override - public void spawnParticle(int particleID, - boolean ignoreRange, - double xCoord, - double yCoord, - double zCoord, - double xSpeed, - double ySpeed, - double zSpeed, - @Nonnull int... parameters) { - } - - @Override - public void spawnParticle(int id, - boolean ignoreRange, - boolean minParticles, - double x, - double y, - double z, - double xSpeed, - double ySpeed, - double zSpeed, - @Nonnull int... parameters) { - } - - @Override - public void onEntityAdded(@Nonnull Entity entity) { - } - - @Override - public void onEntityRemoved(@Nonnull Entity entity) { - } - - @Override - public void broadcastSound(int soundID, @Nonnull BlockPos pos, int data) { - } - - @Override - public void playEvent(@Nullable EntityPlayer player, int type, @Nonnull BlockPos blockPos, int data) { - } - - @Override - public void sendBlockBreakProgress(int breakerId, @Nonnull BlockPos pos, int progress) { - } }; public TileQuarry() { diff --git a/common/buildcraft/lib/world/WorldEventListenerAdapter.java b/common/buildcraft/lib/world/WorldEventListenerAdapter.java new file mode 100644 index 0000000000..ae627920e2 --- /dev/null +++ b/common/buildcraft/lib/world/WorldEventListenerAdapter.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.lib.world; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.SoundCategory; +import net.minecraft.util.SoundEvent; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IWorldEventListener; +import net.minecraft.world.World; + +public class WorldEventListenerAdapter implements IWorldEventListener { + @Override + public void notifyBlockUpdate(@Nonnull World world, + @Nonnull BlockPos pos, + @Nonnull IBlockState oldState, + @Nonnull IBlockState newState, + int flags) { + } + + @Override + public void notifyLightSet(@Nonnull BlockPos pos) { + } + + @Override + public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2, int z2) { + } + + @Override + public void playSoundToAllNearExcept(@Nullable EntityPlayer player, + @Nonnull SoundEvent sound, + @Nonnull SoundCategory category, + double x, + double y, + double z, + float volume, + float pitch) { + } + + @Override + public void playRecord(@Nonnull SoundEvent sound, @Nonnull BlockPos pos) { + } + + @Override + public void spawnParticle(int particleID, + boolean ignoreRange, + double xCoord, + double yCoord, + double zCoord, + double xSpeed, + double ySpeed, + double zSpeed, + @Nonnull int... parameters) { + } + + @Override + public void spawnParticle(int id, + boolean ignoreRange, + boolean minParticles, + double x, + double y, + double z, + double xSpeed, + double ySpeed, + double zSpeed, + @Nonnull int... parameters) { + } + + @Override + public void onEntityAdded(@Nonnull Entity entity) { + } + + @Override + public void onEntityRemoved(@Nonnull Entity entity) { + } + + @Override + public void broadcastSound(int soundID, @Nonnull BlockPos pos, int data) { + } + + @Override + public void playEvent(@Nullable EntityPlayer player, int type, @Nonnull BlockPos blockPos, int data) { + } + + @Override + public void sendBlockBreakProgress(int breakerId, @Nonnull BlockPos pos, int progress) { + } +} From 557a99664247e597f33b0700eb3d673f58c05b1f Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Sun, 2 Jul 2017 16:52:26 +0300 Subject: [PATCH 77/89] Fix entities casting --- .../buildcraft/builders/tile/TileQuarry.java | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/common/buildcraft/builders/tile/TileQuarry.java b/common/buildcraft/builders/tile/TileQuarry.java index 6f7ae2a15e..08c4aa68b0 100644 --- a/common/buildcraft/builders/tile/TileQuarry.java +++ b/common/buildcraft/builders/tile/TileQuarry.java @@ -25,7 +25,6 @@ import com.google.common.collect.ImmutableList; import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; @@ -793,22 +792,21 @@ protected boolean finish() { world.sendBlockBreakProgress(breakPos.hashCode(), breakPos, -1); if (drillPos != null) { world.destroyBlock(breakPos, true); - world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(breakPos)).stream() - .filter(EntityItem.class::isInstance) - .map(EntityItem.class::cast) - .map(TransactorEntityItem::new) - .forEach(transactor -> { - ItemStack stack; - while (!(stack = transactor.extract( - StackFilter.ALL, - 0, - Integer.MAX_VALUE, - false - )).isEmpty()) { - InventoryUtil.addToBestAcceptor(world, pos, null, stack); - } - }); - + for (EntityItem entity : world.getEntitiesWithinAABB( + EntityItem.class, + new AxisAlignedBB(breakPos).expandXyz(1) + )) { + TransactorEntityItem transactor = new TransactorEntityItem(entity); + ItemStack stack; + while (!(stack = transactor.extract( + StackFilter.ALL, + 0, + Integer.MAX_VALUE, + false + )).isEmpty()) { + InventoryUtil.addToBestAcceptor(world, pos, null, stack); + } + } } else { world.destroyBlock(breakPos, false); } From 3435f405a2b94efe8d317a309dae9f526599c154 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Sun, 2 Jul 2017 20:54:47 +0100 Subject: [PATCH 78/89] Fix the heat exchanger's rendering. It works now! --- common/buildcraft/energy/BCEnergyRecipes.java | 4 +- common/buildcraft/factory/BCFactoryProxy.java | 3 + .../factory/block/BlockHeatExchange.java | 9 +- .../client/render/RenderDistiller.java | 53 +---- .../render/RenderHeatExchangeStart.java | 216 ++++++++++++++++++ .../factory/client/render/RenderTank.java | 4 +- .../factory/tile/TileDistiller_BC8.java | 11 +- .../factory/tile/TileHeatExchangeEnd.java | 64 +++++- .../factory/tile/TileHeatExchangeStart.java | 166 +++++++++++--- common/buildcraft/factory/tile/TileTank.java | 22 +- .../lib/chunkload/IChunkLoadingTile.java | 2 +- .../client/render/fluid/FluidRenderer.java | 52 ++++- .../buildcraft/lib/fluid/FluidSmoother.java | 11 +- .../buildcraft/lib/misc/BoundingBoxUtil.java | 20 +- common/buildcraft/lib/misc/NBTUtilBC.java | 27 ++- .../client/render/PipeFlowRendererFluids.java | 9 + .../client/render/RenderPipeHolder.java | 6 + 17 files changed, 554 insertions(+), 125 deletions(-) diff --git a/common/buildcraft/energy/BCEnergyRecipes.java b/common/buildcraft/energy/BCEnergyRecipes.java index c70bef65f7..c761363c2b 100644 --- a/common/buildcraft/energy/BCEnergyRecipes.java +++ b/common/buildcraft/energy/BCEnergyRecipes.java @@ -75,9 +75,9 @@ public static void init() { final int _light_dense_residue = 3; final int _gas_light_dense = 8; - addFuel(BCEnergyFluids.fuelGaseous, _gas, 4); + addFuel(BCEnergyFluids.fuelGaseous, _gas, 8); addFuel(BCEnergyFluids.fuelLight, _light, 6); - addFuel(BCEnergyFluids.fuelDense, _dense, 8); + addFuel(BCEnergyFluids.fuelDense, _dense, 4); addFuel(BCEnergyFluids.fuelMixedLight, _gas_light, 3); addFuel(BCEnergyFluids.fuelMixedHeavy, _light_dense, 5); diff --git a/common/buildcraft/factory/BCFactoryProxy.java b/common/buildcraft/factory/BCFactoryProxy.java index 009e8686a4..62c20a83ab 100644 --- a/common/buildcraft/factory/BCFactoryProxy.java +++ b/common/buildcraft/factory/BCFactoryProxy.java @@ -16,6 +16,7 @@ import net.minecraftforge.fml.relauncher.SideOnly; import buildcraft.factory.client.render.RenderDistiller; +import buildcraft.factory.client.render.RenderHeatExchangeStart; import buildcraft.factory.client.render.RenderMiningWell; import buildcraft.factory.client.render.RenderPump; import buildcraft.factory.client.render.RenderTank; @@ -26,6 +27,7 @@ import buildcraft.factory.tile.TileAutoWorkbenchItems; import buildcraft.factory.tile.TileChute; import buildcraft.factory.tile.TileDistiller_BC8; +import buildcraft.factory.tile.TileHeatExchangeStart; import buildcraft.factory.tile.TileMiningWell; import buildcraft.factory.tile.TilePump; import buildcraft.factory.tile.TileTank; @@ -95,6 +97,7 @@ public void fmlInit() { ClientRegistry.bindTileEntitySpecialRenderer(TilePump.class, new RenderPump()); ClientRegistry.bindTileEntitySpecialRenderer(TileTank.class, new RenderTank()); ClientRegistry.bindTileEntitySpecialRenderer(TileDistiller_BC8.class, new RenderDistiller()); + ClientRegistry.bindTileEntitySpecialRenderer(TileHeatExchangeStart.class, new RenderHeatExchangeStart()); } } } diff --git a/common/buildcraft/factory/block/BlockHeatExchange.java b/common/buildcraft/factory/block/BlockHeatExchange.java index 268107a316..066c59b865 100644 --- a/common/buildcraft/factory/block/BlockHeatExchange.java +++ b/common/buildcraft/factory/block/BlockHeatExchange.java @@ -216,13 +216,6 @@ public BlockRenderLayer getBlockLayer() { @Override public float getExtension(World world, BlockPos pos, EnumFacing face, IBlockState state) { - if (part == Part.MIDDLE) { - return 0; - } - EnumFacing thisFacing = state.getValue(PROP_FACING); - if (face != thisFacing.getOpposite()) { - return 0; - } - return 2 / 16.0f; + return 0; } } diff --git a/common/buildcraft/factory/client/render/RenderDistiller.java b/common/buildcraft/factory/client/render/RenderDistiller.java index 0c4376cdfa..ceff773841 100644 --- a/common/buildcraft/factory/client/render/RenderDistiller.java +++ b/common/buildcraft/factory/client/render/RenderDistiller.java @@ -24,18 +24,14 @@ import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.profiler.Profiler; import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.Vec3d; - -import net.minecraftforge.fluids.FluidStack; import buildcraft.lib.block.BlockBCBase_Neptune; import buildcraft.lib.client.model.MutableQuad; import buildcraft.lib.client.render.fluid.FluidRenderer; +import buildcraft.lib.client.render.fluid.FluidRenderer.TankSize; import buildcraft.lib.client.render.fluid.FluidSpriteType; import buildcraft.lib.fluid.FluidSmoother; -import buildcraft.lib.fluid.FluidSmoother.SmoothedFluid; -import buildcraft.lib.fluid.Tank; -import buildcraft.lib.misc.VecUtil; +import buildcraft.lib.fluid.FluidSmoother.FluidStackInterp; import buildcraft.factory.BCFactoryBlocks; import buildcraft.factory.BCFactoryModels; @@ -46,9 +42,9 @@ public class RenderDistiller extends TileEntitySpecialRenderer { + private static final Map TANK_SIDES = new EnumMap<>(EnumFacing.class); + private static final TankSize TANK_BOTTOM, TANK_TOP; + + static { + double s = 1 / 64.0; + TANK_BOTTOM = new TankSize(2, 0, 2, 14, 2, 14).shrink(s, 0, s); + TANK_TOP = new TankSize(2, 14, 2, 14, 16, 14).shrink(s, 0, s); + TankSize start = new TankSize(0, 4, 4, 2, 12, 12).shrink(0, s, s); + TankSize end = new TankSize(14, 4, 4, 16, 12, 12).shrink(0, s, s); + TankSideData sides = new TankSideData(start, end); + EnumFacing face = EnumFacing.EAST; + for (int i = 0; i < 4; i++) { + TANK_SIDES.put(face, sides); + face = face.rotateY(); + sides = sides.rotateY(); + } + } + + static class TankSideData { + public final TankSize start, end; + + public TankSideData(TankSize start, TankSize end) { + this.start = start; + this.end = end; + } + + public TankSideData rotateY() { + return new TankSideData(start.rotateY(), end.rotateY()); + } + } + @Override public void renderTileEntityAt(TileHeatExchangeStart tile, double x, double y, double z, float partialTicks, int destroyStage) { + super.renderTileEntityAt(tile, x, y, z, partialTicks, destroyStage); + + IBlockState state = tile.getCurrentStateForBlock(BCFactoryBlocks.heatExchangeStart); + if (state == null) { + return; + } + + Profiler profiler = Minecraft.getMinecraft().mcProfiler; + profiler.startSection("bc"); + profiler.startSection("heat_exchange"); + + int combinedLight = tile.getWorld().getCombinedLight(tile.getPos(), 0); + + // gl state setup + RenderHelper.disableStandardItemLighting(); + Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); + GlStateManager.enableBlend(); + GlStateManager.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA); + + // buffer setup + VertexBuffer vb = Tessellator.getInstance().getBuffer(); + vb.begin(GL11.GL_QUADS, DefaultVertexFormats.BLOCK); + vb.setTranslation(x, y, z); + + profiler.startSection("tank"); + + EnumFacing face = state.getValue(BlockBCBase_Neptune.PROP_FACING); + TankSideData sideTank = TANK_SIDES.get(face); + renderTank(TANK_BOTTOM, tile.smoothedHeatableIn, combinedLight, partialTicks, vb); + renderTank(sideTank.start, tile.smoothedCoolableOut, combinedLight, partialTicks, vb); + + TileHeatExchangeEnd end = tile.getOtherTile(); + int middles = 0; + if (end != null) { + // TODO: Move this into the other renderer! + BlockPos diff = end.getPos().subtract(tile.getPos()); + middles = Math.abs(VecUtil.getValue(diff, face.getAxis())); + vb.setTranslation(x + diff.getX(), y + diff.getY(), z + diff.getZ()); + renderTank(TANK_TOP, end.smoothedHeatableOut, combinedLight, partialTicks, vb); + renderTank(sideTank.end, end.smoothedCoolableIn, combinedLight, partialTicks, vb); + vb.setTranslation(x, y, z); + } + + profiler.endStartSection("flow"); + + if (middles > 0) { + EnumProgressState progressState = tile.getProgressState(); + double progress = tile.getProgress(partialTicks); + if (progress > 0) { + double length = middles + 1 - 4 / 16.0 - 0.02; + double p0 = 2 / 16.0 + 0.01; + double p1 = p0 + length - 0.01; + double progressStart = p0; + double progressEnd = p0 + length * progress; + + boolean flip = progressState == EnumProgressState.PREPARING; + flip ^= face.getAxisDirection() == AxisDirection.NEGATIVE; + + if (flip) { + progressStart = p1 - length * progress; + progressEnd = p1; + } + BlockPos diff = BlockPos.ORIGIN; + if (face.getAxisDirection() == AxisDirection.NEGATIVE) { + diff = diff.offset(face, middles); + } + double otherStart = flip ? p0 : p1 - length * progress; + double otherEnd = flip ? p0 + length * progress : p1; + Vec3d vDiff = new Vec3d(diff).addVector(x, y, z); + renderFlow(vDiff, face, vb, progressStart + 0.01, progressEnd - 0.01, + end.smoothedCoolableIn.getFluidForRender(), 4); + renderFlow(vDiff, face.getOpposite(), vb, otherStart, otherEnd, + tile.smoothedHeatableIn.getFluidForRender(), 2); + } + } + + // buffer finish + vb.setTranslation(0, 0, 0); + profiler.endStartSection("draw"); + Tessellator.getInstance().draw(); + + // gl state finish + RenderHelper.enableStandardItemLighting(); + + profiler.endSection(); + profiler.endSection(); + profiler.endSection(); + } + + private static void renderTank(TankSize size, FluidSmoother tank, int combinedLight, float partialTicks, + VertexBuffer vb) { + FluidStackInterp fluid = tank.getFluidForRender(partialTicks); + if (fluid == null || fluid.amount <= 0) { + return; + } + int blockLight = fluid.fluid.getFluid().getLuminosity(fluid.fluid) & 0xF; + combinedLight |= blockLight << 4; + FluidRenderer.vertex.lighti(combinedLight); + FluidRenderer.renderFluid(FluidSpriteType.STILL, fluid.fluid, fluid.amount, tank.getCapacity(), size.min, + size.max, vb, null); + } + + private static void renderFlow(Vec3d diff, EnumFacing face, VertexBuffer vb, double s, double e, FluidStack fluid, + int point) { + double tickTime = Minecraft.getMinecraft().world.getTotalWorldTime(); + float partialTicks = 0; + double offset = (tickTime + partialTicks) % 31 / 31.0; + if (face.getAxisDirection() == AxisDirection.NEGATIVE) { + offset = -offset; + face = face.getOpposite(); + } + Vec3d dirVec = new Vec3d(face.getDirectionVec()); + double ds = (point + 0.1) / 16.0; + Vec3d vs = new Vec3d(ds, ds, ds); + Vec3d ve = new Vec3d(1 - ds, 1 - ds, 1 - ds); + diff = diff.subtract(VecUtil.scale(dirVec, offset)); + s += offset; + e += offset; + if (s < 0) { + s++; + e++; + diff = diff.subtract(dirVec); + } + for (int i = 0; i <= e; i++) { + Vec3d d = diff; + diff = diff.add(dirVec); + if (i < s - 1) { + continue; + } + vb.setTranslation(d.xCoord, d.yCoord, d.zCoord); + + double s1 = s < i ? 0 : (s % 1); + double e1 = e > i + 1 ? 1 : (e % 1); + vs = VecUtil.replaceValue(vs, face.getAxis(), s1); + ve = VecUtil.replaceValue(ve, face.getAxis(), e1); + boolean[] sides = new boolean[6]; + Arrays.fill(sides, true); + if (s < i) { + sides[face.getOpposite().ordinal()] = false; + } + if (e > i + 1) { + sides[face.ordinal()] = false; + } + FluidRenderer.renderFluid(FluidSpriteType.FROZEN, fluid, 1, 1, vs, ve, vb, sides); + + } + } + + @Override + public boolean isGlobalRenderer(TileHeatExchangeStart tile) { + return tile.getOtherTile() != null; } } diff --git a/common/buildcraft/factory/client/render/RenderTank.java b/common/buildcraft/factory/client/render/RenderTank.java index b8c1c52237..f7346c8e89 100644 --- a/common/buildcraft/factory/client/render/RenderTank.java +++ b/common/buildcraft/factory/client/render/RenderTank.java @@ -27,7 +27,7 @@ import buildcraft.lib.client.render.fluid.FluidRenderer; import buildcraft.lib.client.render.fluid.FluidSpriteType; -import buildcraft.lib.fluid.FluidSmoother.SmoothedFluid; +import buildcraft.lib.fluid.FluidSmoother.FluidStackInterp; import buildcraft.lib.fluid.Tank; import buildcraft.factory.tile.TileTank; @@ -42,7 +42,7 @@ public RenderTank() {} @Override public void renderTileEntityAt(TileTank tile, double x, double y, double z, float partialTicks, int destroyStage) { - SmoothedFluid forRender = tile.getFluidForRender(partialTicks); + FluidStackInterp forRender = tile.getFluidForRender(partialTicks); if (forRender == null) { return; } diff --git a/common/buildcraft/factory/tile/TileDistiller_BC8.java b/common/buildcraft/factory/tile/TileDistiller_BC8.java index 8f8127b0d2..ef878116da 100644 --- a/common/buildcraft/factory/tile/TileDistiller_BC8.java +++ b/common/buildcraft/factory/tile/TileDistiller_BC8.java @@ -98,10 +98,9 @@ public int fill(FluidStack resource, boolean doFill) { private final MjBattery mjBattery = new MjBattery(1024 * MjAPI.MJ); - public final FluidSmoother smoothedTankIn = new FluidSmoother(createSender(NET_TANK_IN), tankIn); - public final FluidSmoother smoothedTankOutGas = new FluidSmoother(createSender(NET_TANK_OUT_GAS), tankOutGas); - public final FluidSmoother smoothedTankOutLiquid = - new FluidSmoother(createSender(NET_TANK_OUT_LIQUID), tankOutLiquid); + public final FluidSmoother smoothedTankIn; + public final FluidSmoother smoothedTankOutGas; + public final FluidSmoother smoothedTankOutLiquid; /** The model variables, used to keep track of the various state-based variables. */ public final ModelVariableData clientModelData = new ModelVariableData(); @@ -124,6 +123,10 @@ public TileDistiller_BC8() { tankManager.add(tankOutGas); tankManager.add(tankOutLiquid); + smoothedTankIn = new FluidSmoother(createSender(NET_TANK_IN), tankIn); + smoothedTankOutGas = new FluidSmoother(createSender(NET_TANK_OUT_GAS), tankOutGas); + smoothedTankOutLiquid = new FluidSmoother(createSender(NET_TANK_OUT_LIQUID), tankOutLiquid); + caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankIn, EnumPipePart.HORIZONTALS); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankOutGas, EnumPipePart.UP); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankOutLiquid, EnumPipePart.DOWN); diff --git a/common/buildcraft/factory/tile/TileHeatExchangeEnd.java b/common/buildcraft/factory/tile/TileHeatExchangeEnd.java index 9dd6fcc629..18816803aa 100644 --- a/common/buildcraft/factory/tile/TileHeatExchangeEnd.java +++ b/common/buildcraft/factory/tile/TileHeatExchangeEnd.java @@ -14,6 +14,7 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; +import net.minecraft.util.ITickable; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; @@ -27,22 +28,44 @@ import buildcraft.api.tiles.IDebuggable; import buildcraft.lib.block.BlockBCBase_Neptune; +import buildcraft.lib.fluid.FluidSmoother; import buildcraft.lib.fluid.Tank; import buildcraft.lib.misc.CapUtil; +import buildcraft.lib.misc.data.IdAllocator; import buildcraft.lib.net.PacketBufferBC; import buildcraft.lib.tile.TileBC_Neptune; import buildcraft.factory.BCFactoryBlocks; -public class TileHeatExchangeEnd extends TileBC_Neptune implements IDebuggable { - public final Tank tankHeatableOut = new Tank("heatable_out", 2 * Fluid.BUCKET_VOLUME, this); - public final Tank tankCoolableIn = new Tank("coolable_in", 2 * Fluid.BUCKET_VOLUME, this, this::isCoolant); +public class TileHeatExchangeEnd extends TileBC_Neptune implements IDebuggable, ITickable { + public static final IdAllocator IDS = TileBC_Neptune.IDS.makeChild("HeatExchangeEnd"); + public static final int NET_TANK_HEATABLE_OUT = IDS.allocId("TANK_HEATABLE_OUT"); + public static final int NET_TANK_COOLABLE_IN = IDS.allocId("TANK_COOLABLE_IN"); + + @Override + public IdAllocator getIdAllocator() { + return IDS; + } + + // Package-private to allow TileHeatExchangeStart to access them + final Tank tankHeatableOut = new Tank("heatable_out", 2 * Fluid.BUCKET_VOLUME, this); + final Tank tankCoolableIn = new Tank("coolable_in", 2 * Fluid.BUCKET_VOLUME, this, this::isCoolant); + + public final FluidSmoother smoothedHeatableOut; + public final FluidSmoother smoothedCoolableIn; public TileHeatExchangeEnd() { tankManager.addAll(tankHeatableOut, tankCoolableIn); tankHeatableOut.setCanFill(false); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankHeatableOut, EnumPipePart.UP); caps.addCapability(CapUtil.CAP_FLUIDS, this::getTankForSide, EnumPipePart.HORIZONTALS); + + smoothedHeatableOut = createFluidSmoother(tankHeatableOut, NET_TANK_HEATABLE_OUT); + smoothedCoolableIn = createFluidSmoother(tankCoolableIn, NET_TANK_COOLABLE_IN); + } + + private FluidSmoother createFluidSmoother(Tank tank, int netId) { + return new FluidSmoother(w -> createAndSendMessage(netId, w), tank); } private boolean isCoolant(FluidStack fluid) { @@ -66,7 +89,12 @@ public void writePayload(int id, PacketBufferBC buffer, Side side) { super.writePayload(id, buffer, side); if (side == Side.SERVER) { if (id == NET_RENDER_DATA) { - tankManager.writeData(buffer); + writePayload(NET_TANK_COOLABLE_IN, buffer, side); + writePayload(NET_TANK_HEATABLE_OUT, buffer, side); + } else if (id == NET_TANK_COOLABLE_IN) { + smoothedCoolableIn.writeInit(buffer); + } else if (id == NET_TANK_HEATABLE_OUT) { + smoothedHeatableOut.writeInit(buffer); } } } @@ -76,16 +104,38 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext super.readPayload(id, buffer, side, ctx); if (side == Side.CLIENT) { if (id == NET_RENDER_DATA) { - tankManager.readData(buffer); + readPayload(NET_TANK_COOLABLE_IN, buffer, side, ctx); + readPayload(NET_TANK_HEATABLE_OUT, buffer, side, ctx); + smoothedHeatableOut.resetSmoothing(getWorld()); + smoothedCoolableIn.resetSmoothing(getWorld()); + } else if (id == NET_TANK_COOLABLE_IN) { + smoothedCoolableIn.handleMessage(getWorld(), buffer); + } else if (id == NET_TANK_HEATABLE_OUT) { + smoothedHeatableOut.handleMessage(getWorld(), buffer); } } } + @Override + public void update() { + smoothedCoolableIn.tick(getWorld()); + smoothedHeatableOut.tick(getWorld()); + } + @Override @SideOnly(Side.CLIENT) public void getDebugInfo(List left, List right, EnumFacing side) { - left.add("heatable_out = " + tankHeatableOut.getDebugString()); - left.add("coolable_in = " + tankCoolableIn.getDebugString()); + if (hasWorld() && world.isRemote) { + left.add(""); + left.add("coolable:"); + smoothedCoolableIn.getDebugInfo(left, right, side); + left.add(""); + left.add("heatable:"); + smoothedHeatableOut.getDebugInfo(left, right, side); + } else { + left.add("heatable_out = " + tankHeatableOut.getDebugString()); + left.add("coolable_in = " + tankCoolableIn.getDebugString()); + } } @Nullable diff --git a/common/buildcraft/factory/tile/TileHeatExchangeStart.java b/common/buildcraft/factory/tile/TileHeatExchangeStart.java index 0f315a0dd2..b1d574135a 100644 --- a/common/buildcraft/factory/tile/TileHeatExchangeStart.java +++ b/common/buildcraft/factory/tile/TileHeatExchangeStart.java @@ -19,6 +19,7 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.ITickable; +import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; @@ -39,9 +40,12 @@ import buildcraft.api.tiles.IDebuggable; import buildcraft.lib.block.BlockBCBase_Neptune; +import buildcraft.lib.fluid.FluidSmoother; import buildcraft.lib.fluid.Tank; +import buildcraft.lib.misc.BoundingBoxUtil; import buildcraft.lib.misc.CapUtil; import buildcraft.lib.misc.FluidUtilBC; +import buildcraft.lib.misc.MathUtil; import buildcraft.lib.misc.VecUtil; import buildcraft.lib.misc.data.IdAllocator; import buildcraft.lib.net.PacketBufferBC; @@ -55,23 +59,43 @@ public class TileHeatExchangeStart extends TileBC_Neptune implements ITickable, public static final IdAllocator IDS = TileBC_Neptune.IDS.makeChild("HeatExchangeStart"); public static final int NET_TANK_HEATABLE_IN = IDS.allocId("TANK_HEATABLE_IN"); public static final int NET_TANK_COOLABLE_OUT = IDS.allocId("TANK_COOLABLE_OUT"); + public static final int NET_STATE = IDS.allocId("STATE"); + + @Override + public IdAllocator getIdAllocator() { + return IDS; + } private static final int[] FLUID_MULT = { 10, 16, 20 }; private final Tank tankHeatableIn = new Tank("heatable_in", 2 * Fluid.BUCKET_VOLUME, this, this::isHeatant); private final Tank tankCoolableOut = new Tank("coolable_out", 2 * Fluid.BUCKET_VOLUME, this); + public final FluidSmoother smoothedHeatableIn; + public final FluidSmoother smoothedCoolableOut; + private TileHeatExchangeEnd tileEnd; private int middles; private int progress = 0; + private EnumProgressState progressState = EnumProgressState.OFF; + private EnumProgressState lastSentState = EnumProgressState.OFF; private int heatProvided = 0; private int coolingProvided = 0; + private int progressLast = 0; + public TileHeatExchangeStart() { tankManager.addAll(tankHeatableIn, tankCoolableOut); tankCoolableOut.setCanFill(false); caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tankHeatableIn, EnumPipePart.DOWN); caps.addCapability(CapUtil.CAP_FLUIDS, this::getTankForSide, EnumPipePart.HORIZONTALS); + + smoothedHeatableIn = createFluidSmoother(tankHeatableIn, NET_TANK_HEATABLE_IN); + smoothedCoolableOut = createFluidSmoother(tankCoolableOut, NET_TANK_COOLABLE_OUT); + } + + private FluidSmoother createFluidSmoother(Tank tank, int netId) { + return new FluidSmoother(w -> createAndSendMessage(netId, w), tank); } private boolean isHeatant(FluidStack fluid) { @@ -110,7 +134,16 @@ public void writePayload(int id, PacketBufferBC buffer, Side side) { super.writePayload(id, buffer, side); if (side == Side.SERVER) { if (id == NET_RENDER_DATA) { - tankManager.writeData(buffer); + writePayload(NET_TANK_HEATABLE_IN, buffer, side); + writePayload(NET_TANK_COOLABLE_OUT, buffer, side); + writePayload(NET_STATE, buffer, side); + buffer.writeInt(progress); + } else if (id == NET_TANK_HEATABLE_IN) { + smoothedHeatableIn.writeInit(buffer); + } else if (id == NET_TANK_COOLABLE_OUT) { + smoothedCoolableOut.writeInit(buffer); + } else if (id == NET_STATE) { + buffer.writeEnumValue(progressState); } } } @@ -120,23 +153,59 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext super.readPayload(id, buffer, side, ctx); if (side == Side.CLIENT) { if (id == NET_RENDER_DATA) { - tankManager.readData(buffer); + readPayload(NET_TANK_HEATABLE_IN, buffer, side, ctx); + readPayload(NET_TANK_COOLABLE_OUT, buffer, side, ctx); + readPayload(NET_STATE, buffer, side, ctx); + progress = buffer.readInt(); + smoothedHeatableIn.resetSmoothing(getWorld()); + smoothedCoolableOut.resetSmoothing(getWorld()); + } else if (id == NET_TANK_HEATABLE_IN) { + smoothedHeatableIn.handleMessage(getWorld(), buffer); + } else if (id == NET_TANK_COOLABLE_OUT) { + smoothedCoolableOut.handleMessage(getWorld(), buffer); + } else if (id == NET_STATE) { + progressState = buffer.readEnumValue(EnumProgressState.class); } } } @Override public void update() { + smoothedHeatableIn.tick(getWorld()); + smoothedCoolableOut.tick(getWorld()); + findEnd(); + updateProgress(); if (world.isRemote) { - // TODO: Client stuffs return; } - tileEnd = null; - findEnd(); if (tileEnd != null) { craft(); + } else if (progressState != EnumProgressState.OFF) { + progressState = EnumProgressState.STOPPING; } output(); + if (progressState != lastSentState) { + lastSentState = progressState; + sendNetworkUpdate(NET_STATE); + } + } + + private void updateProgress() { + progressLast = progress; + if (progressState == EnumProgressState.STOPPING) { + progress--; + if (progress <= 0) { + progress = 0; + progressState = EnumProgressState.OFF; + } + } else if (progressState == EnumProgressState.PREPARING) { + int lag = 120; + progress++; + if (progress >= lag) { + progress = lag; + progressState = EnumProgressState.RUNNING; + } + } } private void findEnd() { @@ -194,16 +263,12 @@ private void craft() { ICoolableRecipe c_recipe = reg.getCoolableRegistry().getRecipeForInput(c_in.getFluid()); IHeatableRecipe h_recipe = reg.getHeatableRegistry().getRecipeForInput(h_in.getFluid()); if (h_recipe == null || c_recipe == null) { - if (progress > 0) { - progress--; - } + progressState = EnumProgressState.STOPPING; return; } if (c_recipe.heatFrom() <= h_recipe.heatFrom()) { BCLog.logger.warn("Invalid heat values!"); - if (progress > 0) { - progress--; - } + progressState = EnumProgressState.STOPPING; return; } int c_diff = c_recipe.heatFrom() - c_recipe.heatTo(); @@ -211,6 +276,7 @@ private void craft() { if (h_diff < 1 || c_diff < 1) { throw new IllegalStateException("Invalid recipe " + c_recipe + ", " + h_recipe); } + // TODO: Make mult the *maximum* multiplier, not the exact one. int mult = FLUID_MULT[middles - 1]; boolean needs_c = heatProvided == 0; boolean needs_h = coolingProvided == 0; @@ -220,10 +286,9 @@ private void craft() { FluidStack h_in_f = setAmount(h_recipe.in(), mult); FluidStack h_out_f = setAmount(h_recipe.out(), mult); if (canFill(c_out, c_out_f) && canFill(h_out, h_out_f) && canDrain(c_in, c_in_f) && canDrain(h_in, h_in_f)) { - progress++; - int lag = 30; - if (progress >= lag) { - progress = lag; + if (progressState == EnumProgressState.OFF) { + progressState = EnumProgressState.PREPARING; + } else if (progressState == EnumProgressState.RUNNING) { heatProvided += c_diff - 1; coolingProvided += h_diff - 1; @@ -249,8 +314,8 @@ private void craft() { } } } - } else if (progress > 0) { - progress--; + } else { + progressState = EnumProgressState.STOPPING; } } @@ -262,17 +327,19 @@ private static void spewForth(Vec3d from, EnumFacing dir, EnumParticleTypes part double y = from.yCoord; double z = from.zCoord; - Vec3d motion = VecUtil.scale(vecDir, 0.4); - for (int i = 0; i < 10; i++) { - double dx = motion.xCoord + Math.random() * 0.01; - double dy = motion.yCoord + Math.random() * 0.01; - double dz = motion.zCoord + Math.random() * 0.01; + Minecraft.getMinecraft().addScheduledTask(() -> { + Vec3d motion = VecUtil.scale(vecDir, 0.4); + for (int i = 0; i < 10; i++) { + double dx = motion.xCoord + Math.random() * 0.01; + double dy = motion.yCoord + Math.random() * 0.01; + double dz = motion.zCoord + Math.random() * 0.01; - WorldClient w = Minecraft.getMinecraft().world; - if (w != null) { - w.spawnParticle(particle, x, y, z, dx, dy, dz); + WorldClient w = Minecraft.getMinecraft().world; + if (w != null) { + w.spawnParticle(particle, x, y, z, dx, dy, dz); + } } - } + }); } private void output() { @@ -334,11 +401,54 @@ private IFluidHandler getFluidAutoOutputTarget() { return tile.getCapability(CapUtil.CAP_FLUIDS, facing); } + public TileHeatExchangeEnd getOtherTile() { + return tileEnd; + } + + public double getProgress(float partialTicks) { + return MathUtil.interp(partialTicks, progressLast, progress) / 120.0; + } + + public EnumProgressState getProgressState() { + return this.progressState; + } + + @Override + public AxisAlignedBB getRenderBoundingBox() { + TileHeatExchangeEnd end = tileEnd; + if (end == null) { + return super.getRenderBoundingBox(); + } + return BoundingBoxUtil.makeFrom(getPos(), end.getPos()); + } + @Override @SideOnly(Side.CLIENT) public void getDebugInfo(List left, List right, EnumFacing side) { - left.add("heatable_in = " + tankHeatableIn.getDebugString()); - left.add("coolable_out = " + tankCoolableOut.getDebugString()); left.add("progress = " + progress); + left.add("state = " + progressState); + left.add("has_end = " + (tileEnd != null)); + if (hasWorld() && world.isRemote) { + left.add(""); + left.add("coolable:"); + smoothedCoolableOut.getDebugInfo(left, right, side); + left.add(""); + left.add("heatable:"); + smoothedHeatableIn.getDebugInfo(left, right, side); + } else { + left.add("heatable_in = " + tankHeatableIn.getDebugString()); + left.add("coolable_out = " + tankCoolableOut.getDebugString()); + } + } + + public enum EnumProgressState { + /** Progress is at 0, not moving. */ + OFF, + /** Progress is increasing from 0 to max */ + PREPARING, + /** progress stays at max */ + RUNNING, + /** Progress is decreasing from max to 0. */ + STOPPING; } } diff --git a/common/buildcraft/factory/tile/TileTank.java b/common/buildcraft/factory/tile/TileTank.java index 3a8a852748..495b8f914b 100644 --- a/common/buildcraft/factory/tile/TileTank.java +++ b/common/buildcraft/factory/tile/TileTank.java @@ -14,7 +14,6 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; @@ -36,7 +35,7 @@ import buildcraft.api.tiles.IDebuggable; import buildcraft.lib.fluid.FluidSmoother; -import buildcraft.lib.fluid.FluidSmoother.SmoothedFluid; +import buildcraft.lib.fluid.FluidSmoother.FluidStackInterp; import buildcraft.lib.fluid.Tank; import buildcraft.lib.misc.CapUtil; import buildcraft.lib.misc.FluidUtilBC; @@ -160,7 +159,7 @@ public void getDebugInfo(List left, List right, EnumFacing side) // Rendering @SideOnly(Side.CLIENT) - public SmoothedFluid getFluidForRender(float partialTicks) { + public FluidStackInterp getFluidForRender(float partialTicks) { return smoothedTank.getFluidForRender(partialTicks); } @@ -238,6 +237,10 @@ public int fill(FluidStack resource, boolean doFill) { return 0; } } + boolean gas = resource.getFluid().isGaseous(resource); + if (gas) { + Collections.reverse(tanks); + } for (TileTank t : tanks) { int tankFilled = t.tank.fill(resource, doFill); if (tankFilled > 0) { @@ -275,8 +278,17 @@ public FluidStack drain(IFluidFilter filter, int maxDrain, boolean doDrain) { return null; } List tanks = getTanks(); - // The returned list is ordered bottom -> top, but we want top -> bottom - Collections.reverse(tanks); + boolean gas = false; + for (TileTank tile : tanks) { + FluidStack fluid = tile.tank.getFluid(); + if (fluid != null) { + gas = fluid.getFluid().isGaseous(fluid); + break; + } + } + if (!gas) { + Collections.reverse(tanks); + } FluidStack total = null; for (TileTank t : tanks) { int realMax = maxDrain - (total == null ? 0 : total.amount); diff --git a/common/buildcraft/lib/chunkload/IChunkLoadingTile.java b/common/buildcraft/lib/chunkload/IChunkLoadingTile.java index baf5f770cb..f20725a4d5 100644 --- a/common/buildcraft/lib/chunkload/IChunkLoadingTile.java +++ b/common/buildcraft/lib/chunkload/IChunkLoadingTile.java @@ -50,7 +50,7 @@ default Collection getChunksToLoad() { return list; } - enum LoadType { + public enum LoadType { /** Softly attempt to chunkload this. If the value of {@link BCLibConfig#chunkLoadingType} is equal to * {@link ChunkLoaderLevel#STRICT_TILES} or {@link ChunkLoaderLevel#NONE} then it won't be loaded. */ SOFT, diff --git a/common/buildcraft/lib/client/render/fluid/FluidRenderer.java b/common/buildcraft/lib/client/render/fluid/FluidRenderer.java index 340c20c046..3c94f9a4b6 100644 --- a/common/buildcraft/lib/client/render/fluid/FluidRenderer.java +++ b/common/buildcraft/lib/client/render/fluid/FluidRenderer.java @@ -43,7 +43,8 @@ // TODO: thread safety (per thread context?) public class FluidRenderer { - private static final EnumMap> fluidSprites = new EnumMap<>(FluidSpriteType.class); + private static final EnumMap> fluidSprites = + new EnumMap<>(FluidSpriteType.class); public static final MutableVertex vertex = new MutableVertex(); private static final boolean[] DEFAULT_FACES = { true, true, true, true, true, true }; @@ -101,7 +102,8 @@ public static void onTextureStitchPost(TextureMap map) { * faces will be rendered. The indexes are determined by what {@link EnumFacing#ordinal()} returns. * * @see #renderFluid(FluidSpriteType, FluidStack, double, double, Vec3d, Vec3d, VertexBuffer, boolean[]) */ - public static void renderFluid(FluidSpriteType type, IFluidTank tank, Vec3d min, Vec3d max, VertexBuffer vbIn, boolean[] sideRender) { + public static void renderFluid(FluidSpriteType type, IFluidTank tank, Vec3d min, Vec3d max, VertexBuffer vbIn, + boolean[] sideRender) { renderFluid(type, tank.getFluid(), tank.getCapacity(), min, max, vbIn, sideRender); } @@ -116,7 +118,8 @@ public static void renderFluid(FluidSpriteType type, IFluidTank tank, Vec3d min, * @param vbIn The {@link VertexBuffer} that the fluid will be rendered into. * @param sideRender A size 6 boolean array that determines if the face will be rendered. If it is null then all * faces will be rendered. The indexes are determined by what {@link EnumFacing#ordinal()} returns. */ - public static void renderFluid(FluidSpriteType type, FluidStack fluid, int cap, Vec3d min, Vec3d max, VertexBuffer vbIn, boolean[] sideRender) { + public static void renderFluid(FluidSpriteType type, FluidStack fluid, int cap, Vec3d min, Vec3d max, + VertexBuffer vbIn, boolean[] sideRender) { renderFluid(type, fluid, fluid == null ? 0 : fluid.amount, cap, min, max, vbIn, sideRender); } @@ -133,7 +136,8 @@ public static void renderFluid(FluidSpriteType type, FluidStack fluid, int cap, * @param vbIn The {@link VertexBuffer} that the fluid will be rendered into. * @param sideRender A size 6 boolean array that determines if the face will be rendered. If it is null then all * faces will be rendered. The indexes are determined by what {@link EnumFacing#ordinal()} returns. */ - public static void renderFluid(FluidSpriteType type, FluidStack fluid, double amount, double cap, Vec3d min, Vec3d max, VertexBuffer vbIn, boolean[] sideRender) { + public static void renderFluid(FluidSpriteType type, FluidStack fluid, double amount, double cap, Vec3d min, + Vec3d max, VertexBuffer vbIn, boolean[] sideRender) { if (fluid == null || fluid.getFluid() == null || amount <= 0) { return; } @@ -378,4 +382,44 @@ private void apply(double x, double y, double z) { vertex.texf(sprite.getInterpolatedU(realu * 16), sprite.getInterpolatedV(realv * 16)); } } + + public static class TankSize { + public final Vec3d min; + public final Vec3d max; + + public TankSize(int sx, int sy, int sz, int ex, int ey, int ez) { + this(new Vec3d(sx, sy, sz).scale(1 / 16.0), new Vec3d(ex, ey, ez).scale(1 / 16.0)); + } + + public TankSize(Vec3d min, Vec3d max) { + this.min = min; + this.max = max; + } + + public TankSize shrink(double by) { + return shrink(by, by, by); + } + + public TankSize shrink(double x, double y, double z) { + return new TankSize(min.addVector(x, y, z), max.subtract(x, y, z)); + } + + public TankSize shink(Vec3d by) { + return shrink(by.xCoord, by.yCoord, by.zCoord); + } + + public TankSize rotateY() { + Vec3d _min = rotateY(min); + Vec3d _max = rotateY(max); + return new TankSize(VecUtil.min(_min, _max), VecUtil.max(_min, _max)); + } + + private static Vec3d rotateY(Vec3d vec) { + return new Vec3d(// + 1 - vec.zCoord,// + vec.yCoord,// + vec.xCoord// + ); + } + } } diff --git a/common/buildcraft/lib/fluid/FluidSmoother.java b/common/buildcraft/lib/fluid/FluidSmoother.java index d57f0ffefc..ac82421fc6 100644 --- a/common/buildcraft/lib/fluid/FluidSmoother.java +++ b/common/buildcraft/lib/fluid/FluidSmoother.java @@ -75,6 +75,9 @@ public void resetSmoothing(World world) { public FluidStack getFluidForRender() { if (data instanceof _Client) { _Client client = (_Client) data; + if (client.link == null) { + return null; + } FluidStack fluid = client.link.get(); if (fluid == null) { return null; @@ -84,7 +87,7 @@ public FluidStack getFluidForRender() { return null; } - public SmoothedFluid getFluidForRender(double partialTicks) { + public FluidStackInterp getFluidForRender(double partialTicks) { if (data instanceof _Client) { _Client client = (_Client) data; if (client.link == null) { @@ -95,7 +98,7 @@ public SmoothedFluid getFluidForRender(double partialTicks) { return null; } double amount = client.amountLast * (1 - partialTicks) + client.amount * partialTicks; - return new SmoothedFluid(fluid, amount); + return new FluidStackInterp(fluid, amount); } return null; } @@ -117,11 +120,11 @@ public interface IFluidDataSender { void writePacket(IPayloadWriter writer); } - public static class SmoothedFluid { + public static class FluidStackInterp { public final FluidStack fluid; public final double amount; - public SmoothedFluid(FluidStack fluid, double amount) { + public FluidStackInterp(FluidStack fluid, double amount) { this.fluid = fluid; this.amount = amount; } diff --git a/common/buildcraft/lib/misc/BoundingBoxUtil.java b/common/buildcraft/lib/misc/BoundingBoxUtil.java index 31516b12f0..a769fe6d9b 100644 --- a/common/buildcraft/lib/misc/BoundingBoxUtil.java +++ b/common/buildcraft/lib/misc/BoundingBoxUtil.java @@ -16,6 +16,8 @@ import buildcraft.api.core.IBox; +import buildcraft.lib.misc.data.Box; + /** Various methods operating on (and creating) {@link AxisAlignedBB} */ public class BoundingBoxUtil { @@ -32,6 +34,14 @@ public static AxisAlignedBB makeFrom(BlockPos additional, @Nullable IBox box) { } } + public static AxisAlignedBB makeFrom(BlockPos primary, BlockPos... additional) { + Box box = new Box(primary, primary); + for (BlockPos a : additional) { + box.extendToEncompass(a); + } + return box.getBoundingBox(); + } + /** Creates an {@link AxisAlignedBB} from a block pos and 2 boxes * * Note that additional must NOT be null, but (either of) the boxes can be. */ @@ -56,14 +66,8 @@ public static AxisAlignedBB makeFrom(Vec3d from, Vec3d to, double radius) { } public static AxisAlignedBB makeAround(Vec3d around, double radius) { - return new AxisAlignedBB( - around.xCoord, - around.yCoord, - around.zCoord, - around.xCoord, - around.yCoord, - around.zCoord - ).expandXyz(radius); + return new AxisAlignedBB(around.xCoord, around.yCoord, around.zCoord, around.xCoord, around.yCoord, + around.zCoord).expandXyz(radius); } public static AxisAlignedBB makeFrom(BlockPos pos, @Nullable IBox box, @Nullable Collection additional) { diff --git a/common/buildcraft/lib/misc/NBTUtilBC.java b/common/buildcraft/lib/misc/NBTUtilBC.java index b57dd8ea9b..0089dd0a16 100644 --- a/common/buildcraft/lib/misc/NBTUtilBC.java +++ b/common/buildcraft/lib/misc/NBTUtilBC.java @@ -19,6 +19,7 @@ import java.util.stream.Stream; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; @@ -102,29 +103,39 @@ public static byte[] save(NBTTagCompound compound) { } public static NBTTagIntArray writeBlockPos(BlockPos pos) { - if (pos == null) return null; + if (pos == null) { + throw new NullPointerException("Cannot return a null NBTTag -- pos was null!"); + } return new NBTTagIntArray(new int[] { pos.getX(), pos.getY(), pos.getZ() }); } public static NBTTagCompound writeBlockPosAsCompound(BlockPos pos) { - if (pos == null) return null; + if (pos == null) { + throw new NullPointerException("Cannot return a null NBTTag -- pos was null!"); + } NBTTagCompound nbt = new NBTTagCompound(); nbt.setInteger("x", pos.getX()); - nbt.setInteger("y", pos.getX()); - nbt.setInteger("z", pos.getX()); + nbt.setInteger("y", pos.getY()); + nbt.setInteger("z", pos.getZ()); return nbt; } + @Nullable public static BlockPos readBlockPos(NBTBase base) { - if (base == null) return null; + if (base == null) { + return null; + } switch (base.getId()) { case Constants.NBT.TAG_INT_ARRAY: { int[] array = ((NBTTagIntArray) base).getIntArray(); - return new BlockPos(array[0], array[1], array[2]); + if (array.length == 3){ + return new BlockPos(array[0], array[1], array[2]); + } + return null; } case Constants.NBT.TAG_COMPOUND: { NBTTagCompound nbt = (NBTTagCompound) base; - BlockPos pos = BlockPos.ORIGIN; + BlockPos pos = null; if (nbt.hasKey("i")) { int i = nbt.getInteger("i"); int j = nbt.getInteger("j"); @@ -144,7 +155,7 @@ public static BlockPos readBlockPos(NBTBase base) { } } BCLog.logger.warn("Attempted to read a block position from an invalid tag! (" + base + ")", new Throwable()); - return BlockPos.ORIGIN; + return null; } public static NBTTagList writeVec3d(Vec3d vec3) { diff --git a/common/buildcraft/transport/client/render/PipeFlowRendererFluids.java b/common/buildcraft/transport/client/render/PipeFlowRendererFluids.java index ad3e5c825e..d9bf89b6da 100644 --- a/common/buildcraft/transport/client/render/PipeFlowRendererFluids.java +++ b/common/buildcraft/transport/client/render/PipeFlowRendererFluids.java @@ -19,6 +19,7 @@ import net.minecraft.client.renderer.VertexBuffer; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; +import net.minecraft.profiler.Profiler; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing.Axis; import net.minecraft.util.math.Vec3d; @@ -46,6 +47,9 @@ public void render(PipeFlowFluids flow, double x, double y, double z, float part return; } + Profiler prof = Minecraft.getMinecraft().mcProfiler; + prof.startSection("calc"); + boolean[] sides = new boolean[6]; Arrays.fill(sides, true); @@ -67,6 +71,7 @@ public void render(PipeFlowFluids flow, double x, double y, double z, float part boolean vertical = flow.pipe.isConnected(gas ? EnumFacing.DOWN : EnumFacing.UP); for (EnumFacing face : EnumFacing.VALUES) { + prof.endStartSection(face.name()); double size = ((Pipe) flow.pipe).getConnectedDist(face); double amount = amounts[face.getIndex()]; if (face.getAxis() != Axis.Y) { @@ -106,6 +111,7 @@ public void render(PipeFlowFluids flow, double x, double y, double z, float part if (offset == null) offset = Vec3d.ZERO; fluidBuffer.setTranslation(x - offset.xCoord, y - offset.yCoord, z - offset.zCoord); + prof.endStartSection("c_horiz"); if (horizontal | !vertical) { Vec3d min = new Vec3d(0.26, 0.26, 0.26); Vec3d max = new Vec3d(0.74, 0.74, 0.74); @@ -117,6 +123,7 @@ public void render(PipeFlowFluids flow, double x, double y, double z, float part horizPos += (max.yCoord - min.yCoord) * amount / flow.capacity; } + prof.endStartSection("c_vert"); if (vertical && horizPos < 0.74) { double perc = amount / flow.capacity; perc = Math.sqrt(perc); @@ -141,12 +148,14 @@ public void render(PipeFlowFluids flow, double x, double y, double z, float part GlStateManager.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA); GlStateManager.enableCull(); + prof.endStartSection("draw"); fluidBuffer.setTranslation(0, 0, 0); Tessellator.getInstance().draw(); RenderHelper.enableStandardItemLighting(); FluidRenderer.vertex.lighti(0xF, 0xF); + prof.endSection(); } diff --git a/common/buildcraft/transport/client/render/RenderPipeHolder.java b/common/buildcraft/transport/client/render/RenderPipeHolder.java index aa38f8c5df..2a25238019 100644 --- a/common/buildcraft/transport/client/render/RenderPipeHolder.java +++ b/common/buildcraft/transport/client/render/RenderPipeHolder.java @@ -61,7 +61,9 @@ private static void renderPluggables(TilePipeHolder pipe, double x, double y, do private static

    void renderPlug(P plug, double x, double y, double z, float partialTicks, VertexBuffer vb) { IPlugDynamicRenderer

    renderer = PipeRegistryClient.getPlugRenderer(plug); if (renderer != null) { + Minecraft.getMinecraft().mcProfiler.startSection(plug.getClass()); renderer.render(plug, x, y, z, partialTicks, vb); + Minecraft.getMinecraft().mcProfiler.endSection(); } } @@ -81,14 +83,18 @@ private static void renderContents(TilePipeHolder pipe, double x, double y, doub private static void renderFlow(F flow, double x, double y, double z, float partialTicks, VertexBuffer vb) { IPipeFlowRenderer renderer = PipeRegistryClient.getFlowRenderer(flow); if (renderer != null) { + Minecraft.getMinecraft().mcProfiler.startSection(flow.getClass()); renderer.render(flow, x, y, z, partialTicks, vb); + Minecraft.getMinecraft().mcProfiler.endSection(); } } private static void renderBehaviour(B behaviour, double x, double y, double z, float partialTicks, VertexBuffer vb) { IPipeBehaviourRenderer renderer = PipeRegistryClient.getBehaviourRenderer(behaviour); if (renderer != null) { + Minecraft.getMinecraft().mcProfiler.startSection(behaviour.getClass()); renderer.render(behaviour, x, y, z, partialTicks, vb); + Minecraft.getMinecraft().mcProfiler.endSection(); } } } From 8bd2403b86f73cab4d91b2fc09ba722af243e776 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Mon, 3 Jul 2017 14:02:29 +0300 Subject: [PATCH 79/89] Fix #3647 --- .../builders/tile/TileElectronicLibrary.java | 134 ++++++++++++------ 1 file changed, 94 insertions(+), 40 deletions(-) diff --git a/common/buildcraft/builders/tile/TileElectronicLibrary.java b/common/buildcraft/builders/tile/TileElectronicLibrary.java index f0ced2c34f..ca61b6a0a8 100644 --- a/common/buildcraft/builders/tile/TileElectronicLibrary.java +++ b/common/buildcraft/builders/tile/TileElectronicLibrary.java @@ -5,12 +5,22 @@ package buildcraft.builders.tile; import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; import javax.annotation.Nonnull; +import com.google.common.primitives.Bytes; + +import org.apache.commons.lang3.tuple.Pair; + import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ITickable; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; @@ -37,7 +47,9 @@ public class TileElectronicLibrary extends TileBC_Neptune implements ITickable { public static final IdAllocator IDS = TileBC_Neptune.IDS.makeChild("library"); + @SuppressWarnings("WeakerAccess") public static final int NET_DOWN = IDS.allocId("DOWN"); + @SuppressWarnings("WeakerAccess") public static final int NET_UP = IDS.allocId("UP"); public final ItemHandlerSimple invDownIn = itemManager.addInvHandler("downIn", 1, EnumAccess.INSERT, EnumPipePart.VALUES); @@ -45,10 +57,11 @@ public class TileElectronicLibrary extends TileBC_Neptune implements ITickable { public final ItemHandlerSimple invUpIn = itemManager.addInvHandler("upIn", 1, EnumAccess.INSERT, EnumPipePart.VALUES); public final ItemHandlerSimple invUpOut = itemManager.addInvHandler("upOut", 1, EnumAccess.EXTRACT, EnumPipePart.VALUES); public Snapshot.Key selected = null; - public int progressDown = -1; - public int progressUp = -1; + private int progressDown = -1; + private int progressUp = -1; public final DeltaInt deltaProgressDown = deltaManager.addDelta("progressDown", DeltaManager.EnumNetworkVisibility.GUI_ONLY); public final DeltaInt deltaProgressUp = deltaManager.addDelta("progressUp", DeltaManager.EnumNetworkVisibility.GUI_ONLY); + private final Map, List> upSnapshotsParts = new HashMap<>(); @Override protected void onSlotChange(IItemHandlerModifiable handler, int slot, @Nonnull ItemStack before, @Nonnull ItemStack after) { @@ -153,25 +166,6 @@ public void writePayload(int id, PacketBufferBC buffer, Side side) { if (id == NET_UP) { } } - if (side == Side.CLIENT) { - if (id == NET_UP) { - if (selected != null) { - Snapshot snapshot = GlobalSavedDataSnapshots.get(world).getSnapshot(selected); - if (snapshot != null) { - buffer.writeBoolean(true); - NbtSquisher.squish( - Snapshot.writeToNBT(snapshot), - NbtSquishConstants.BUILDCRAFT_V1_COMPRESSED, - buffer - ); - } else { - buffer.writeBoolean(false); - } - } else { - buffer.writeBoolean(false); - } - } - } } @Override @@ -193,29 +187,89 @@ public void readPayload(int id, PacketBufferBC buffer, Side side, MessageContext } } if (id == NET_UP) { - MessageManager.sendToServer(createNetworkUpdate(NET_UP)); + if (selected != null) { + Snapshot snapshot = GlobalSavedDataSnapshots.get(world).getSnapshot(selected); + if (snapshot != null) { + try (OutputStream outputStream = new OutputStream() { + private byte[] buf = new byte[4 * 1024]; + private int pos = 0; + private boolean closed = false; + + private void write(boolean last) throws IOException { + MessageManager.sendToServer(createMessage(NET_UP, localBuffer -> { + localBuffer.writeUniqueId(ctx.getClientHandler().getGameProfile().getId()); + selected.writeToByteBuf(localBuffer); + localBuffer.writeBoolean(last); + localBuffer.writeByteArray(buf); + })); + } + + @Override + public void write(int b) throws IOException { + buf[pos++] = (byte) b; + if (pos >= buf.length) { + write(false); + buf = new byte[buf.length]; + pos = 0; + } + } + + @Override + public void close() throws IOException { + if (closed) { + return; + } + closed = true; + buf = Arrays.copyOf(buf, pos); + pos = 0; + write(true); + } + }) { + NbtSquisher.squish( + Snapshot.writeToNBT(snapshot), + NbtSquishConstants.BUILDCRAFT_V1_COMPRESSED, + outputStream + ); + } + } + } } } if (side == Side.SERVER) { if (id == NET_UP) { - if (buffer.readBoolean()) { - NBTTagCompound nbt = NbtSquisher.expand(buffer); - Snapshot snapshot = Snapshot.readFromNBT(nbt); - invUpIn.setStackInSlot(0, StackUtil.EMPTY); - snapshot.computeKey(); - GlobalSavedDataSnapshots.get(world).addSnapshot(snapshot); - invUpOut.setStackInSlot( - 0, - BCBuildersItems.snapshot.getUsed( - snapshot.getType(), - new Snapshot.Header( - snapshot.key, - getOwner().getId(), - new Date(), - "From library" + UUID playerId = buffer.readUniqueId(); + Snapshot.Key key = new Snapshot.Key(buffer); + Pair pair = Pair.of(playerId, key); + boolean last = buffer.readBoolean(); + upSnapshotsParts.computeIfAbsent(pair, localPair -> new ArrayList<>()).add(buffer.readByteArray()); + if (last && upSnapshotsParts.containsKey(pair)) { + try { + Snapshot snapshot = Snapshot.readFromNBT( + NbtSquisher.expand( + Bytes.concat( + upSnapshotsParts.get(pair) + .toArray(new byte[0][]) + ) ) - ) - ); + ); + invUpIn.setStackInSlot(0, StackUtil.EMPTY); + snapshot.computeKey(); + GlobalSavedDataSnapshots.get(world).addSnapshot(snapshot); + invUpOut.setStackInSlot( + 0, + BCBuildersItems.snapshot.getUsed( + snapshot.getType(), + new Snapshot.Header( + snapshot.key, + getOwner().getId(), + new Date(), + "From library" + ) + ) + ); + } finally { + upSnapshotsParts.remove(pair); + } } } } From fb7d409dff6a9c5eb65c1dea74a6fa43d8bcd7d2 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Mon, 3 Jul 2017 16:27:25 +0100 Subject: [PATCH 80/89] Fix the tank not flowing gasses around proplery when adding/removing a tank. --- common/buildcraft/energy/BCEnergyRecipes.java | 9 ++++ common/buildcraft/factory/tile/TileTank.java | 46 +++++++++++-------- .../behaviour/PipeBehaviourDirectional.java | 28 ++++++++++- .../pipe/behaviour/PipeBehaviourIron.java | 6 +++ 4 files changed, 70 insertions(+), 19 deletions(-) diff --git a/common/buildcraft/energy/BCEnergyRecipes.java b/common/buildcraft/energy/BCEnergyRecipes.java index c761363c2b..afbc43a9fc 100644 --- a/common/buildcraft/energy/BCEnergyRecipes.java +++ b/common/buildcraft/energy/BCEnergyRecipes.java @@ -21,6 +21,7 @@ import buildcraft.api.recipes.IRefineryRecipeManager.IDistillationRecipe; import buildcraft.lib.fluid.BCFluid; +import buildcraft.lib.misc.MathUtil; import buildcraft.lib.recipe.OredictionaryNames; import buildcraft.lib.recipe.RecipeBuilderShaped; @@ -188,6 +189,14 @@ private static void addDistillation(FluidStack[] in, FluidStack[] outGas, FluidS if (existing != null) { throw new IllegalStateException("Already added distillation recipe for " + _in.getFluid().getName()); } + int hcf = MathUtil.findHighestCommonFactor(_in.amount, _outGas.amount); + hcf = MathUtil.findHighestCommonFactor(hcf, _outLiquid.amount); + if (hcf > 1) { + (_in = _in.copy()).amount /= hcf; + (_outGas = _outGas.copy()).amount /= hcf; + (_outLiquid = _outLiquid.copy()).amount /= hcf; + mjCost /= hcf; + } BuildcraftRecipeRegistry.refineryRecipes.addDistillationRecipe(_in, _outGas, _outLiquid, mjCost); } diff --git a/common/buildcraft/factory/tile/TileTank.java b/common/buildcraft/factory/tile/TileTank.java index 495b8f914b..40496b0cac 100644 --- a/common/buildcraft/factory/tile/TileTank.java +++ b/common/buildcraft/factory/tile/TileTank.java @@ -75,24 +75,34 @@ public void update() { public void onPlacedBy(EntityLivingBase placer, ItemStack stack) { super.onPlacedBy(placer, stack); if (!placer.world.isRemote) { - BlockPos p = pos.up(); - TileTank moveTo = this; - while (true) { - TileEntity tileUp = world.getTileEntity(p); - if (tileUp instanceof TileTank) { - TileTank tankUp = (TileTank) tileUp; - - int used = moveTo.tank.fill(tankUp.tank.getFluid(), true); - if (used > 0) { - tankUp.drain(used, true); - } - - moveTo = tankUp; - p = p.up(); - } else { - break; + List tanks = getTanks(); + FluidStack fluid = null; + for (TileTank tile : tanks) { + FluidStack held = tile.tank.getFluid(); + if (held == null) { + continue; + } + if (fluid == null) { + fluid = held; + } else if (!fluid.isFluidEqual(held)) { + return; + } + } + if (fluid == null) { + return; + } + if (fluid.getFluid().isGaseous(fluid)) { + Collections.reverse(tanks); + } + TileTank prev = null; + isPlayerInteracting = true; + for (TileTank tile : tanks) { + if (prev != null) { + FluidUtilBC.move(tile.tank, prev.tank); } + prev = tile; } + isPlayerInteracting = false; } } @@ -244,7 +254,7 @@ public int fill(FluidStack resource, boolean doFill) { for (TileTank t : tanks) { int tankFilled = t.tank.fill(resource, doFill); if (tankFilled > 0) { - if (isPlayerInteracting) { + if (isPlayerInteracting & doFill) { t.sendNetworkUpdate(NET_RENDER_DATA); } resource.amount -= tankFilled; @@ -297,7 +307,7 @@ public FluidStack drain(IFluidFilter filter, int maxDrain, boolean doDrain) { } FluidStack drained = t.tank.drain(filter, realMax, doDrain); if (drained == null) continue; - if (isPlayerInteracting) { + if (isPlayerInteracting & doDrain) { t.sendNetworkUpdate(NET_RENDER_DATA); } if (total == null) { diff --git a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourDirectional.java b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourDirectional.java index eba807f206..d5073f4375 100644 --- a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourDirectional.java +++ b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourDirectional.java @@ -21,6 +21,9 @@ import buildcraft.api.transport.pipe.IPipe; import buildcraft.api.transport.pipe.IPipeHolder.PipeMessageReceiver; import buildcraft.api.transport.pipe.PipeBehaviour; +import buildcraft.api.transport.pipe.PipeEventActionActivate; +import buildcraft.api.transport.pipe.PipeEventHandler; +import buildcraft.api.transport.pipe.PipeEventStatement; import buildcraft.lib.block.VanillaRotationHandlers; import buildcraft.lib.misc.EntityUtil; @@ -28,6 +31,9 @@ import buildcraft.lib.misc.collect.OrderedEnumMap; import buildcraft.lib.net.PacketBufferBC; +import buildcraft.transport.BCTransportStatements; +import buildcraft.transport.statements.ActionPipeDirection; + public abstract class PipeBehaviourDirectional extends PipeBehaviour { public static final OrderedEnumMap ROTATION_ORDER = VanillaRotationHandlers.ROTATE_FACING; @@ -63,7 +69,8 @@ public void readPayload(PacketBuffer buffer, Side side, MessageContext ctx) { } @Override - public boolean onPipeActivate(EntityPlayer player, RayTraceResult trace, float hitX, float hitY, float hitZ, EnumPipePart part) { + public boolean onPipeActivate(EntityPlayer player, RayTraceResult trace, float hitX, float hitY, float hitZ, + EnumPipePart part) { if (EntityUtil.getWrenchHand(player) != null) { EntityUtil.activateWrench(player); if (part.face != getCurrentDir()) { @@ -106,4 +113,23 @@ protected void setCurrentDir(EnumFacing setTo) { pipe.getHolder().scheduleNetworkUpdate(PipeMessageReceiver.BEHAVIOUR); } } + + @PipeEventHandler + public void addActions(PipeEventStatement.AddActionInternal event) { + for (EnumFacing face : EnumFacing.VALUES) { + if (canFaceDirection(face)) { + event.actions.add(BCTransportStatements.ACTION_PIPE_DIRECTION[face.ordinal()]); + } + } + } + + @PipeEventHandler + public void onActionActivate(PipeEventActionActivate event) { + if (event.action instanceof ActionPipeDirection) { + ActionPipeDirection action = (ActionPipeDirection) event.action; + if (canFaceDirection(action.direction)) { + setCurrentDir(action.direction); + } + } + } } diff --git a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourIron.java b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourIron.java index 4dd8b08b63..fcd94cef1e 100644 --- a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourIron.java +++ b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourIron.java @@ -57,4 +57,10 @@ public static void tryBounce(PipeEventItem.TryBounce tryBounce) { tryBounce.canBounce = true; } + @PipeEventHandler + public void fluidInsert(PipeEventFluid.TryInsert insert) { + if (currentDir.face == insert.from) { + insert.cancel(); + } + } } From 69b2afe4cef69daf6e56739418179da7a0f88fa4 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Mon, 3 Jul 2017 16:34:37 +0100 Subject: [PATCH 81/89] Fix the heat exchanger not interpolating the flow --- .../factory/client/render/RenderHeatExchangeStart.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/common/buildcraft/factory/client/render/RenderHeatExchangeStart.java b/common/buildcraft/factory/client/render/RenderHeatExchangeStart.java index 580b72e575..76a34625b0 100644 --- a/common/buildcraft/factory/client/render/RenderHeatExchangeStart.java +++ b/common/buildcraft/factory/client/render/RenderHeatExchangeStart.java @@ -144,9 +144,9 @@ public void renderTileEntityAt(TileHeatExchangeStart tile, double x, double y, d double otherEnd = flip ? p0 + length * progress : p1; Vec3d vDiff = new Vec3d(diff).addVector(x, y, z); renderFlow(vDiff, face, vb, progressStart + 0.01, progressEnd - 0.01, - end.smoothedCoolableIn.getFluidForRender(), 4); + end.smoothedCoolableIn.getFluidForRender(), 4, partialTicks); renderFlow(vDiff, face.getOpposite(), vb, otherStart, otherEnd, - tile.smoothedHeatableIn.getFluidForRender(), 2); + tile.smoothedHeatableIn.getFluidForRender(), 2, partialTicks); } } @@ -177,9 +177,8 @@ private static void renderTank(TankSize size, FluidSmoother tank, int combinedLi } private static void renderFlow(Vec3d diff, EnumFacing face, VertexBuffer vb, double s, double e, FluidStack fluid, - int point) { + int point, float partialTicks) { double tickTime = Minecraft.getMinecraft().world.getTotalWorldTime(); - float partialTicks = 0; double offset = (tickTime + partialTicks) % 31 / 31.0; if (face.getAxisDirection() == AxisDirection.NEGATIVE) { offset = -offset; From 161ab4733cde2177b1ad85fc1780794e172c12f4 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Mon, 3 Jul 2017 18:04:01 +0100 Subject: [PATCH 82/89] Remove (testing) useless calls to markDirty() from TileBC_Neptune. I'll have to investigate the saving issue differently... Fix the heat exchanger spawning particles on the server, using client side code. --- .../factory/tile/TileHeatExchangeStart.java | 71 ++++++++++++------- .../buildcraft/lib/tile/TileBC_Neptune.java | 9 +-- 2 files changed, 49 insertions(+), 31 deletions(-) diff --git a/common/buildcraft/factory/tile/TileHeatExchangeStart.java b/common/buildcraft/factory/tile/TileHeatExchangeStart.java index b8fa9f4aab..3004c15f39 100644 --- a/common/buildcraft/factory/tile/TileHeatExchangeStart.java +++ b/common/buildcraft/factory/tile/TileHeatExchangeStart.java @@ -13,7 +13,6 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; @@ -22,6 +21,7 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; +import net.minecraft.world.World; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; @@ -176,6 +176,7 @@ public void update() { findEnd(); updateProgress(); if (world.isRemote) { + spawnParticles(); return; } if (tileEnd != null) { @@ -304,22 +305,12 @@ private void craft() { heatProvided += c_diff; fill(c_out, c_out_f); drain(c_in, c_in_f); - if (c_in_f.getFluid() == FluidRegistry.LAVA) { - Vec3d from = VecUtil.convertCenter(getPos()); - EnumFacing dir = EnumFacing.SOUTH; - spewForth(from, dir, EnumParticleTypes.SMOKE_LARGE); - } } if (needs_h) { coolingProvided += h_diff; fill(h_out, h_out_f); drain(h_in, h_in_f); - if (h_in_f.getFluid() == FluidRegistry.WATER) { - Vec3d from = VecUtil.convertCenter(tileEnd.getPos()); - EnumFacing dir = EnumFacing.UP; - spewForth(from, dir, EnumParticleTypes.CLOUD); - } } } } else { @@ -327,7 +318,32 @@ private void craft() { } } - private static void spewForth(Vec3d from, EnumFacing dir, EnumParticleTypes particle) { + private void spawnParticles() { + if (progressState == EnumProgressState.RUNNING) { + TileHeatExchangeEnd end = tileEnd; + if (end == null) { + return; + } + Vec3d from = VecUtil.convertCenter(getPos()); + FluidStack c_in_f = end.smoothedCoolableIn.getFluidForRender(); + if (c_in_f != null && c_in_f.getFluid() == FluidRegistry.LAVA) { + IBlockState state = getCurrentStateForBlock(BCFactoryBlocks.heatExchangeStart); + if (state != null) { + EnumFacing dir = state.getValue(BlockBCBase_Neptune.PROP_FACING); + spewForth(from, dir.getOpposite(), EnumParticleTypes.SMOKE_LARGE); + } + } + + FluidStack h_in_f = smoothedHeatableIn.getFluidForRender(); + from = VecUtil.convertCenter(tileEnd.getPos()); + if (h_in_f != null && h_in_f.getFluid() == FluidRegistry.WATER) { + EnumFacing dir = EnumFacing.UP; + spewForth(from, dir, EnumParticleTypes.CLOUD); + } + } + } + + private void spewForth(Vec3d from, EnumFacing dir, EnumParticleTypes particle) { Vec3d vecDir = new Vec3d(dir.getDirectionVec()); from = from.add(VecUtil.scale(vecDir, 0.5)); @@ -335,19 +351,24 @@ private static void spewForth(Vec3d from, EnumFacing dir, EnumParticleTypes part double y = from.yCoord; double z = from.zCoord; - Minecraft.getMinecraft().addScheduledTask(() -> { - Vec3d motion = VecUtil.scale(vecDir, 0.4); - for (int i = 0; i < 10; i++) { - double dx = motion.xCoord + Math.random() * 0.01; - double dy = motion.yCoord + Math.random() * 0.01; - double dz = motion.zCoord + Math.random() * 0.01; - - WorldClient w = Minecraft.getMinecraft().world; - if (w != null) { - w.spawnParticle(particle, x, y, z, dx, dy, dz); - } - } - }); + Vec3d motion = VecUtil.scale(vecDir, 0.4); + int particleCount = Minecraft.getMinecraft().gameSettings.particleSetting; + World w = getWorld(); + if (particleCount == 2 || w == null) { + return; + } + particleCount = particleCount == 0 ? 5 : 2; + for (int i = 0; i < particleCount; i++) { + double dx = motion.xCoord + (Math.random() - 0.5) * 0.1; + double dy = motion.yCoord + (Math.random() - 0.5) * 0.1; + double dz = motion.zCoord + (Math.random() - 0.5) * 0.1; + double interp = i / (double) particleCount; + x -= dx * interp; + y -= dy * interp; + z -= dz * interp; + + w.spawnParticle(particle, x, y, z, dx, dy, dz); + } } private void output() { diff --git a/common/buildcraft/lib/tile/TileBC_Neptune.java b/common/buildcraft/lib/tile/TileBC_Neptune.java index 516db7fb67..d2c6f1eef9 100644 --- a/common/buildcraft/lib/tile/TileBC_Neptune.java +++ b/common/buildcraft/lib/tile/TileBC_Neptune.java @@ -37,6 +37,7 @@ import net.minecraft.util.math.Vec3i; import net.minecraft.world.Explosion; import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.Constants; @@ -60,6 +61,7 @@ import buildcraft.lib.fluid.TankManager; import buildcraft.lib.migrate.BCVersion; import buildcraft.lib.misc.BlockUtil; +import buildcraft.lib.misc.ChunkUtil; import buildcraft.lib.misc.InventoryUtil; import buildcraft.lib.misc.MessageUtil; import buildcraft.lib.misc.PermissionUtil; @@ -543,7 +545,7 @@ public void readFromNBT(NBTTagCompound nbt) { if (nbt.hasKey("items", Constants.NBT.TAG_COMPOUND)) { itemManager.deserializeNBT(nbt.getCompoundTag("items")); } - if (nbt.hasKey("tanks",Constants.NBT.TAG_COMPOUND)) { + if (nbt.hasKey("tanks", Constants.NBT.TAG_COMPOUND)) { tankManager.deserializeNBT(nbt.getCompoundTag("tanks")); } } @@ -575,8 +577,6 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { if (!tanks.hasNoTags()) { nbt.setTag("tanks", tanks); } - - markDirty(); return nbt; } @@ -584,9 +584,6 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { protected void setWorldCreate(World world) { // The default impl doesn't actually set the world for some reason :/ setWorld(world); - if (hasWorld()) { - markDirty(); - } } // ################## From 85fa79ac19f3e99fe6defdbe6b5a59b6f35eb4dd Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Mon, 3 Jul 2017 18:35:11 +0100 Subject: [PATCH 83/89] Fix compile error, find out that PipeEventBus doesn't handle overriding PipeEventHandler methods very well. --- BuildCraftAPI | 2 +- .../transport/pipe/PipeEventBus.java | 8 ++--- .../pipe/behaviour/PipeBehaviourEmzuli.java | 8 +++-- .../transport/pipe/PipeEventBusTester.java | 36 +++++++++++++++++++ 4 files changed, 46 insertions(+), 8 deletions(-) diff --git a/BuildCraftAPI b/BuildCraftAPI index b8144f90fa..451f67dc66 160000 --- a/BuildCraftAPI +++ b/BuildCraftAPI @@ -1 +1 @@ -Subproject commit b8144f90fa742bb16d94341e907dc09d98473795 +Subproject commit 451f67dc6629ccfa7c25d0f752380b7cb4382706 diff --git a/common/buildcraft/transport/pipe/PipeEventBus.java b/common/buildcraft/transport/pipe/PipeEventBus.java index e960375a49..942cc5ffb1 100644 --- a/common/buildcraft/transport/pipe/PipeEventBus.java +++ b/common/buildcraft/transport/pipe/PipeEventBus.java @@ -48,6 +48,10 @@ private static List getAndBindHandlers(Object obj) { private static List getHandlers(Class cls) { if (!allHandlers.containsKey(cls)) { List list = new ArrayList<>(); + Class superCls = cls.getSuperclass(); + if (superCls != null) { + list.addAll(getHandlers(superCls)); + } for (Method m : cls.getMethods()) { PipeEventHandler annot = m.getAnnotation(PipeEventHandler.class); if (annot == null) { @@ -74,10 +78,6 @@ private static List getHandlers(Class cls) { list.add(new Handler(annot.priority(), annot.receiveCancelled(), isStatic, methodName, mh, p.getType())); } - Class superCls = cls.getSuperclass(); - if (superCls != null) { - list.addAll(getHandlers(superCls)); - } allHandlers.put(cls, list); return list; } diff --git a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourEmzuli.java b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourEmzuli.java index 85b25bdf96..5c82f91980 100644 --- a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourEmzuli.java +++ b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourEmzuli.java @@ -216,13 +216,15 @@ public boolean onPipeActivate(EntityPlayer player, RayTraceResult trace, float h return true; } - @PipeEventHandler - public static void addActions(PipeEventStatement.AddActionInternal event) { + @Override + public void addActions(PipeEventStatement.AddActionInternal event) { + super.addActions(event); Collections.addAll(event.actions, BCTransportStatements.ACTION_EXTRACTION_PRESET); } - @PipeEventHandler + @Override public void onActionActivate(PipeEventActionActivate event) { + super.onActionActivate(event); if (event.action instanceof ActionExtractionPreset) { ActionExtractionPreset preset = (ActionExtractionPreset) event.action; activeSlots.add(preset.index); diff --git a/src/test/java/buildcraft/test/transport/pipe/PipeEventBusTester.java b/src/test/java/buildcraft/test/transport/pipe/PipeEventBusTester.java index 8fa86ad433..449f1f700c 100644 --- a/src/test/java/buildcraft/test/transport/pipe/PipeEventBusTester.java +++ b/src/test/java/buildcraft/test/transport/pipe/PipeEventBusTester.java @@ -36,4 +36,40 @@ public void testSimpleEvent() { public void modifySpeed(PipeEventItem.ModifySpeed event) { event.targetSpeed = 1; } + + @Test + public void testExtends() { + PipeEventBus bus = new PipeEventBus(); + + PipeEventItem.ModifySpeed event = new PipeEventItem.ModifySpeed(null, null, null, 1); + bus.fireEvent(event); + Assert.assertEquals(0, event.targetSpeed, 0.00001); + + bus.registerHandler(new Base()); + + event = new PipeEventItem.ModifySpeed(null, null, null, 1); + bus.fireEvent(event); + Assert.assertEquals(2, event.targetSpeed, 0.00001); + + bus = new PipeEventBus(); + bus.registerHandler(new Sub()); + + event = new PipeEventItem.ModifySpeed(null, null, null, 1); + bus.fireEvent(event); + Assert.assertEquals(3, event.targetSpeed, 0.00001); + } + + public static class Base { + @PipeEventHandler + public void modifySpeed2(PipeEventItem.ModifySpeed event) { + event.targetSpeed = 2; + } + } + + public static class Sub extends Base { + @Override + public void modifySpeed2(PipeEventItem.ModifySpeed event) { + event.targetSpeed = 3; + } + } } From 332cdc40d6dea07437b7f00193766043c721bf42 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Mon, 3 Jul 2017 18:38:21 +0100 Subject: [PATCH 84/89] Fix another compile error. Woops. --- .../transport/pipe/behaviour/PipeBehaviourDaizuli.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourDaizuli.java b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourDaizuli.java index 5b9cfe83ea..6ab1b0807f 100644 --- a/common/buildcraft/transport/pipe/behaviour/PipeBehaviourDaizuli.java +++ b/common/buildcraft/transport/pipe/behaviour/PipeBehaviourDaizuli.java @@ -112,13 +112,15 @@ public void sideCheck(PipeEventItem.SideCheck sideCheck) { } } - @PipeEventHandler - public static void addActions(PipeEventStatement.AddActionInternal event) { + @Override + public void addActions(PipeEventStatement.AddActionInternal event) { + super.addActions(event); Collections.addAll(event.actions, BCTransportStatements.ACTION_PIPE_COLOUR); } - @PipeEventHandler - public void onActionActivated(PipeEventActionActivate event) { + @Override + public void onActionActivate(PipeEventActionActivate event) { + super.onActionActivate(event); if (event.action instanceof ActionPipeColor) { ActionPipeColor action = ((ActionPipeColor) event.action); if (this.colour != action.color) { From 6f13d71516a87ce62bcf566c367797d12cccac98 Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Mon, 3 Jul 2017 18:58:08 +0100 Subject: [PATCH 85/89] Fix the flood gate being able to store 16 buckets of fluid -- its not a tank! Fix BC fluids being non-translucent but rendering in the translucent layer. --- common/buildcraft/factory/tile/TileFloodGate.java | 2 +- common/buildcraft/lib/fluid/BCFluidBlock.java | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/common/buildcraft/factory/tile/TileFloodGate.java b/common/buildcraft/factory/tile/TileFloodGate.java index 841692f81e..1a741d0f40 100644 --- a/common/buildcraft/factory/tile/TileFloodGate.java +++ b/common/buildcraft/factory/tile/TileFloodGate.java @@ -73,7 +73,7 @@ public class TileFloodGate extends TileBC_Neptune implements ITickable, IDebugga 16384 }; - private final Tank tank = new Tank("tank", 16 * Fluid.BUCKET_VOLUME, this); + private final Tank tank = new Tank("tank", 2 * Fluid.BUCKET_VOLUME, this); public final EnumMap openSides = new EnumMap<>(EnumFacing.class); public final Queue queue = new PriorityQueue<>( Comparator.comparingInt(blockPos -> diff --git a/common/buildcraft/lib/fluid/BCFluidBlock.java b/common/buildcraft/lib/fluid/BCFluidBlock.java index 287d9164e8..91fb72154d 100644 --- a/common/buildcraft/lib/fluid/BCFluidBlock.java +++ b/common/buildcraft/lib/fluid/BCFluidBlock.java @@ -10,6 +10,7 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; +import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; @@ -26,6 +27,8 @@ public BCFluidBlock(Fluid fluid, Material material) { Boolean displaceLava = fluid.getDensity() > 9000; displacements.put(Blocks.LAVA, displaceLava); displacements.put(Blocks.FLOWING_LAVA, displaceLava); + + renderLayer = BlockRenderLayer.SOLID; } @Override From 62447dd7e15c41bc9f92cdf8d4b1870ea59c8d99 Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Tue, 4 Jul 2017 14:54:01 +0300 Subject: [PATCH 86/89] Fix sphere --- .../buildcraft/builders/filling/Filling.java | 4 +- .../builders/filling/FillingCircle.java | 110 ++++++------------ .../builders/filling/FillingSphere.java | 40 +++++++ common/buildcraft/lib/misc/DrawingUtil.java | 59 ++++++++++ 4 files changed, 135 insertions(+), 78 deletions(-) create mode 100644 common/buildcraft/builders/filling/FillingSphere.java diff --git a/common/buildcraft/builders/filling/Filling.java b/common/buildcraft/builders/filling/Filling.java index 8960ba7bf2..619df3186d 100644 --- a/common/buildcraft/builders/filling/Filling.java +++ b/common/buildcraft/builders/filling/Filling.java @@ -325,7 +325,7 @@ public static boolean[][][] getFillingPlan(BlockPos size, List param if (parameterPattern == EnumParameterPattern.CIRCLE) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); EnumParameterAxis parameterAxis = (EnumParameterAxis) parameters.get(2); - return FillingCircle.getCircle(size, parameterType, parameterAxis); + return FillingCircle.get(size, parameterType, parameterAxis); } if (parameterPattern == EnumParameterPattern.FRAME) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); @@ -333,7 +333,7 @@ public static boolean[][][] getFillingPlan(BlockPos size, List param } if (parameterPattern == EnumParameterPattern.SPHERE) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); - return FillingCircle.getSphere(size, parameterType); + return FillingSphere.getSphere(size, parameterType); } return generateFillingPlanByFunction(size, pos -> false); } diff --git a/common/buildcraft/builders/filling/FillingCircle.java b/common/buildcraft/builders/filling/FillingCircle.java index e16e43a0e4..0a80d8f042 100644 --- a/common/buildcraft/builders/filling/FillingCircle.java +++ b/common/buildcraft/builders/filling/FillingCircle.java @@ -14,92 +14,50 @@ import net.minecraft.util.math.BlockPos; import buildcraft.lib.misc.DrawingUtil; -import buildcraft.lib.misc.MathUtil; @SuppressWarnings("WeakerAccess") public class FillingCircle { - private static void draw(EnumParameterType parameterType, Point2i flatSize, boolean[][] flatFillingPlan) { - DrawingUtil.drawEllipse( - flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, - flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, - flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, - flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, - parameterType == EnumParameterType.FILLED, - (x, y) -> { - List positions = new ArrayList<>(); - positions.add( - new Point2i( - flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, - flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y - ) - ); - if (flatSize.x % 2 == 0 && x == flatSize.x / 2) { - positions.add( - new Point2i( - x + 1, - flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y - ) - ); - } - if (flatSize.y % 2 == 0 && y == flatSize.y / 2) { + public static boolean[][][] get(BlockPos size, + EnumParameterType parameterType, + EnumParameterAxis parameterAxis) { + return Filling.generateFillingPlanByFunctionInAxis(size, parameterAxis.axis, (flatSize, flatFillingPlan) -> { + DrawingUtil.drawEllipse( + flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, + flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, + flatSize.x % 2 == 0 ? flatSize.x / 2 - 1 : flatSize.x / 2, + flatSize.y % 2 == 0 ? flatSize.y / 2 - 1 : flatSize.y / 2, + parameterType == EnumParameterType.FILLED, + (x, y) -> { + List positions = new ArrayList<>(); positions.add( new Point2i( flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, - y + 1 + flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y ) ); - } - for (Point2i p : positions) { - if (p.x >= 0 && p.y >= 0 && p.x < flatSize.x && p.y < flatSize.y) { - flatFillingPlan[p.x][p.y] = true; + if (flatSize.x % 2 == 0 && x == flatSize.x / 2) { + positions.add( + new Point2i( + x + 1, + flatSize.y % 2 == 0 && y > flatSize.y / 2 ? y + 1 : y + ) + ); + } + if (flatSize.y % 2 == 0 && y == flatSize.y / 2) { + positions.add( + new Point2i( + flatSize.x % 2 == 0 && x > flatSize.x / 2 ? x + 1 : x, + y + 1 + ) + ); + } + for (Point2i p : positions) { + if (p.x >= 0 && p.y >= 0 && p.x < flatSize.x && p.y < flatSize.y) { + flatFillingPlan[p.x][p.y] = true; + } } } - } - ); - } - - public static boolean[][][] getCircle(BlockPos size, - EnumParameterType parameterType, - EnumParameterAxis parameterAxis) { - return Filling.generateFillingPlanByFunctionInAxis(size, parameterAxis.axis, (flatSize, flatFillingPlan) -> { - draw(parameterType, flatSize, flatFillingPlan); - }); - } - - public static boolean[][][] getSphere(BlockPos size, - EnumParameterType parameterType) { - boolean[][][] flatFillingPlans = new boolean[size.getY()][size.getX()][size.getZ()]; - Point2i flatSize = new Point2i(size.getX(), size.getZ()); - int levelsCount = size.getY(); - for (int level = 0; level < levelsCount; level++) { - double position = (level + 0.5) / levelsCount; - if (position > 0.5) { - position = 1 - position; - } - Point2i resizedSize = new Point2i( - MathUtil.clamp( - (int) Math.round(Math.sqrt(position * (1 - position)) * 2 * flatSize.x), - 1, - flatSize.x - 1 - ), - MathUtil.clamp( - (int) Math.round(Math.sqrt(position * (1 - position)) * 2 * flatSize.y), - 1, - flatSize.y - 1 - ) ); - boolean[][] resizedFillingPlan = new boolean[resizedSize.x][resizedSize.y]; - draw(parameterType, resizedSize, resizedFillingPlan); - for (int y = 0; y < resizedSize.y; y++) { - for (int x = 0; x < resizedSize.x; x++) { - flatFillingPlans - [level] - [x + (flatSize.x - resizedSize.x) / 2] - [y + (flatSize.y - resizedSize.y) / 2] - = resizedFillingPlan[x][y]; - } - } - } - return Filling.generateFillingPlanByFunction(size, pos -> flatFillingPlans[pos.getY()][pos.getX()][pos.getZ()]); + }); } } diff --git a/common/buildcraft/builders/filling/FillingSphere.java b/common/buildcraft/builders/filling/FillingSphere.java new file mode 100644 index 0000000000..2506914312 --- /dev/null +++ b/common/buildcraft/builders/filling/FillingSphere.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2017 SpaceToad and the BuildCraft team + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/ + */ + +package buildcraft.builders.filling; + +import net.minecraft.util.math.BlockPos; + +import buildcraft.lib.misc.DrawingUtil; +import buildcraft.lib.misc.MathUtil; + +@SuppressWarnings("WeakerAccess") +public class FillingSphere { + public static boolean[][][] getSphere(BlockPos size, + EnumParameterType parameterType) { + boolean[][][] fillingPlan = new boolean[size.getX()][size.getY()][size.getZ()]; + DrawingUtil.drawSphere( + new BlockPos( + Math.ceil(size.getX() / 2D + 0.5), + Math.ceil(size.getY() / 2D + 0.5), + Math.ceil(size.getZ() / 2D + 0.5) + ), + new BlockPos( + Math.round(size.getX() / 2D - 1), + Math.round(size.getY() / 2D - 1), + Math.round(size.getZ() / 2D - 1) + ), + parameterType == EnumParameterType.FILLED, + pos -> + fillingPlan + [MathUtil.clamp(pos.getX(), 0, size.getX() - 1)] + [MathUtil.clamp(pos.getY(), 0, size.getY() - 1)] + [MathUtil.clamp(pos.getZ(), 0, size.getZ() - 1)] + = true + ); + return fillingPlan; + } +} diff --git a/common/buildcraft/lib/misc/DrawingUtil.java b/common/buildcraft/lib/misc/DrawingUtil.java index c64165318f..c21d41f04c 100644 --- a/common/buildcraft/lib/misc/DrawingUtil.java +++ b/common/buildcraft/lib/misc/DrawingUtil.java @@ -9,9 +9,12 @@ import java.util.ArrayDeque; import java.util.Queue; import java.util.function.BiConsumer; +import java.util.function.Consumer; import javax.vecmath.Point2i; +import net.minecraft.util.math.BlockPos; + public class DrawingUtil { @SuppressWarnings("Duplicates") public static void drawEllipse(int cx, @@ -97,6 +100,62 @@ public static void drawLine(int x1, int y1, int x2, int y2, BiConsumer drawPixel) { + + double nextNx = 0; + xLabel: + for (int x = 0; x <= radius.getX(); x++) { + double nx = nextNx; + nextNx = (x + 1) * (1D / radius.getX()); + + double nextNy = 0; + yLabel: + for (int y = 0; y <= radius.getY(); y++) { + double ny = nextNy; + nextNy = (y + 1) * (1D / radius.getY()); + + double nextNz = 0; + zLabel: + for (int z = 0; z <= radius.getZ(); z++) { + double nz = nextNz; + nextNz = (z + 1) * (1D / radius.getZ()); + + if ((nx * nx) + (ny * ny) + (nz * nz) > 1) { + if (z != 0) { + break zLabel; + } else if (y != 0) { + break yLabel; + } else if (x != 0) { + break xLabel; + } + } + + if (!filled) { + if ((nextNx * nextNx) + (ny * ny) + (nz * nz) <= 1 && + (nx * nx) + (nextNy * nextNy) + (nz * nz) <= 1 && + (nx * nx) + (ny * ny) + (nextNz * nextNz) <= 1) { + continue; + } + } + + drawPixel.accept(center.add(-x, -y, -z)); + drawPixel.accept(center.add(-x, -y, z)); + drawPixel.accept(center.add(-x, y, -z)); + drawPixel.accept(center.add(-x, y, z)); + drawPixel.accept(center.add(x, -y, -z)); + drawPixel.accept(center.add(x, -y, z)); + drawPixel.accept(center.add(x, y, -z)); + drawPixel.accept(center.add(x, y, z)); + } + } + } + } + + public static void fill(boolean[][] data, int startX, int startY, int width, int height) { Queue queue = new ArrayDeque<>(); queue.add(new Point2i(startX, startY)); From b27c77286db1bf1f53ee241dfbd7244ff8f3618f Mon Sep 17 00:00:00 2001 From: Anton Danilkin Date: Tue, 4 Jul 2017 20:04:26 +0300 Subject: [PATCH 87/89] Rename empty to hollow --- .../textures/filling/type/{empty.png => hollow.png} | Bin .../builders/filling/EnumParameterType.java | 2 +- common/buildcraft/builders/filling/Filling.java | 4 ++-- 3 files changed, 3 insertions(+), 3 deletions(-) rename buildcraft_resources/assets/buildcraftbuilders/textures/filling/type/{empty.png => hollow.png} (100%) diff --git a/buildcraft_resources/assets/buildcraftbuilders/textures/filling/type/empty.png b/buildcraft_resources/assets/buildcraftbuilders/textures/filling/type/hollow.png similarity index 100% rename from buildcraft_resources/assets/buildcraftbuilders/textures/filling/type/empty.png rename to buildcraft_resources/assets/buildcraftbuilders/textures/filling/type/hollow.png diff --git a/common/buildcraft/builders/filling/EnumParameterType.java b/common/buildcraft/builders/filling/EnumParameterType.java index 85e1ed56a3..37e4577d15 100644 --- a/common/buildcraft/builders/filling/EnumParameterType.java +++ b/common/buildcraft/builders/filling/EnumParameterType.java @@ -7,6 +7,6 @@ package buildcraft.builders.filling; public enum EnumParameterType implements IParameter { - EMPTY, + HOLLOW, FILLED } diff --git a/common/buildcraft/builders/filling/Filling.java b/common/buildcraft/builders/filling/Filling.java index 619df3186d..3d6b450e0c 100644 --- a/common/buildcraft/builders/filling/Filling.java +++ b/common/buildcraft/builders/filling/Filling.java @@ -111,7 +111,7 @@ public static Class getNextParameterClass(List } if (parameters.size() == 2) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); - if (parameterType == EnumParameterType.EMPTY) { + if (parameterType == EnumParameterType.HOLLOW) { return EnumParameterAxis.class; } } @@ -302,7 +302,7 @@ public static boolean[][][] getFillingPlan(BlockPos size, List param } if (parameterPattern == EnumParameterPattern.SQUARE) { EnumParameterType parameterType = (EnumParameterType) parameters.get(1); - EnumParameterAxis parameterAxis = parameterType == EnumParameterType.EMPTY + EnumParameterAxis parameterAxis = parameterType == EnumParameterType.HOLLOW ? (EnumParameterAxis) parameters.get(2) : null; return FillingSquare.get(size, parameterType, parameterAxis); From a2bde9a927065d7b1eb36dd27ee27b30dcab463e Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 4 Jul 2017 22:34:05 +0100 Subject: [PATCH 88/89] Fix a few misc small bugs: - Pumps not loading fluids (might be long standaing, or it might have been introduced by me) - Fix tanks not playing a sound when loading/emptying buckets (definatly caused by me recently) - Fix fluid pipes always sending fluids around in EnumFacing.VALUES order, rather than randomly. --- build.gradle | 4 +++- .../factory/tile/TileFloodGate.java | 5 ++--- common/buildcraft/factory/tile/TileMiner.java | 4 +++- common/buildcraft/factory/tile/TileTank.java | 18 ++++++++++----- common/buildcraft/lib/fluid/Tank.java | 9 +++++++- common/buildcraft/lib/misc/FluidUtilBC.java | 17 +++++++++----- common/buildcraft/lib/misc/SoundUtil.java | 22 +++++++++++++++++-- .../buildcraft/lib/tile/TileBC_Neptune.java | 7 ++++-- .../transport/pipe/flow/PipeFlowFluids.java | 6 ++++- 9 files changed, 71 insertions(+), 21 deletions(-) diff --git a/build.gradle b/build.gradle index 893c77509b..c41f9fec7d 100644 --- a/build.gradle +++ b/build.gradle @@ -364,13 +364,15 @@ task allSrcJar(type: Jar, dependsOn:reobfJar) { } } +sourceJar.destinationDir = libsDir + // add api classes to main package jar { from sourceSets.api.output } // make sure all of these happen when we run build -build.dependsOn sourceJar, apiJar, deobfJar, javadocJar +build.dependsOn allSrcJar, apiJar, deobfJar, javadocJar // -------------------- // maven section diff --git a/common/buildcraft/factory/tile/TileFloodGate.java b/common/buildcraft/factory/tile/TileFloodGate.java index 1a741d0f40..fa6cffa9ee 100644 --- a/common/buildcraft/factory/tile/TileFloodGate.java +++ b/common/buildcraft/factory/tile/TileFloodGate.java @@ -88,6 +88,7 @@ public class TileFloodGate extends TileBC_Neptune implements ITickable, IDebugga public TileFloodGate() { caps.addCapabilityInstance(CapUtil.CAP_FLUIDS, tank, EnumPipePart.VALUES); + tankManager.add(tank); Arrays.stream(EnumFacing.VALUES) .forEach(side -> openSides.put(side, BlockFloodGate.CONNECTED_MAP.containsKey(side))); } @@ -249,7 +250,6 @@ public void update() { @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); - nbt.setTag("tank", tank.writeToNBT(new NBTTagCompound())); nbt.setTag("openSides", NBTUtilBC.writeBooleanList(openSides.values().stream())); return nbt; } @@ -257,14 +257,13 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); - tank.readFromNBT(nbt.getCompoundTag("tank")); Boolean[] blockedSidesArray = NBTUtilBC.readBooleanList(nbt.getTag("openSides")).toArray(Boolean[]::new); for (int i = 0; i < blockedSidesArray.length; i++) { openSides.put(EnumFacing.getFront(i), blockedSidesArray[i]); } } - // Netwokring + // Networking @Override public void writePayload(int id, PacketBufferBC buffer, Side side) { diff --git a/common/buildcraft/factory/tile/TileMiner.java b/common/buildcraft/factory/tile/TileMiner.java index 7a14c2a5d1..4cf8f72021 100644 --- a/common/buildcraft/factory/tile/TileMiner.java +++ b/common/buildcraft/factory/tile/TileMiner.java @@ -29,6 +29,7 @@ import buildcraft.api.tiles.TilesAPI; import buildcraft.lib.migrate.BCVersion; +import buildcraft.lib.misc.LocaleUtil; import buildcraft.lib.misc.data.IdAllocator; import buildcraft.lib.net.PacketBufferBC; import buildcraft.lib.tile.TileBC_Neptune; @@ -143,6 +144,7 @@ public boolean isComplete() { @Override protected void migrateOldNBT(int version, NBTTagCompound nbt) { + super.migrateOldNBT(version, nbt); if (version == BCVersion.BEFORE_RECORDS.dataVersion || version == BCVersion.v7_2_0_pre_12.dataVersion) { NBTTagCompound oldBattery = nbt.getCompoundTag("battery"); int energy = oldBattery.getInteger("energy"); @@ -217,7 +219,7 @@ public void getDebugInfo(List left, List right, EnumFacing side) left.add("currentLength = " + currentLength); left.add("lastLength = " + lastLength); left.add("isComplete = " + isComplete()); - left.add("progress = " + progress); + left.add("progress = " + LocaleUtil.localizeMj(progress)); } @Override diff --git a/common/buildcraft/factory/tile/TileTank.java b/common/buildcraft/factory/tile/TileTank.java index 40496b0cac..6cf75bbac3 100644 --- a/common/buildcraft/factory/tile/TileTank.java +++ b/common/buildcraft/factory/tile/TileTank.java @@ -39,6 +39,7 @@ import buildcraft.lib.fluid.Tank; import buildcraft.lib.misc.CapUtil; import buildcraft.lib.misc.FluidUtilBC; +import buildcraft.lib.misc.SoundUtil; import buildcraft.lib.misc.data.IdAllocator; import buildcraft.lib.net.PacketBufferBC; import buildcraft.lib.tile.TileBC_Neptune; @@ -120,11 +121,18 @@ public boolean onActivate(EntityPlayer player, EnumHand hand) { return true; } isPlayerInteracting = true; - if (FluidUtilBC.move(flItem, this) > 0 || FluidUtilBC.move(this, flItem) > 0) { - if (replace) { - player.setHeldItem(hand, flItem.getContainer()); - player.inventoryContainer.detectAndSendChanges(); - } + boolean changed = true; + FluidStack moved; + if ((moved = FluidUtilBC.move(flItem, this)) != null) { + SoundUtil.playBucketEmpty(getWorld(), getPos(), moved); + } else if ((moved = FluidUtilBC.move(this, flItem)) != null) { + SoundUtil.playBucketFill(getWorld(), getPos(), moved); + } else { + changed = false; + } + if (changed & replace) { + player.setHeldItem(hand, flItem.getContainer()); + player.inventoryContainer.detectAndSendChanges(); } isPlayerInteracting = false; return true; diff --git a/common/buildcraft/lib/fluid/Tank.java b/common/buildcraft/lib/fluid/Tank.java index 431775e2c7..816d2dca56 100644 --- a/common/buildcraft/lib/fluid/Tank.java +++ b/common/buildcraft/lib/fluid/Tank.java @@ -27,6 +27,7 @@ import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fluids.capability.IFluidHandlerItem; +import buildcraft.api.core.BCLog; import buildcraft.api.core.IFluidFilter; import buildcraft.api.core.IFluidHandlerAdv; @@ -121,11 +122,17 @@ public final FluidTank readFromNBT(NBTTagCompound nbt) { if (nbt.hasKey(name)) { // Old style of saving + loading NBTTagCompound tankData = nbt.getCompoundTag(name); + BCLog.logger.info(" - Loading old data " + tankData); super.readFromNBT(tankData); + BCLog.logger.info(" - Loading fluid " + getDebugString()); readTankFromNBT(tankData); + BCLog.logger.info(" - Loaded fluid " + getDebugString()); } else { + BCLog.logger.info(" - Loading new data " + nbt); super.readFromNBT(nbt); + BCLog.logger.info(" - Loading fluid " + getDebugString()); readTankFromNBT(nbt); + BCLog.logger.info(" - Loaded fluid " + getDebugString()); } return this; } @@ -180,7 +187,7 @@ public FluidStack drain(IFluidFilter drainFilter, int maxDrain, boolean doDrain) @Override public void setFluid(FluidStack fluid) { - if (fluid == null || canFillFluidType(fluid)) { + if (fluid == null || filter.test(fluid)) { super.setFluid(fluid); } } diff --git a/common/buildcraft/lib/misc/FluidUtilBC.java b/common/buildcraft/lib/misc/FluidUtilBC.java index 6f05e50fdb..eaed3ad93f 100644 --- a/common/buildcraft/lib/misc/FluidUtilBC.java +++ b/common/buildcraft/lib/misc/FluidUtilBC.java @@ -9,6 +9,8 @@ import java.util.ArrayList; import java.util.List; +import javax.annotation.Nullable; + import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -136,13 +138,18 @@ public static boolean areFluidsEqual(Fluid a, Fluid b) { return a.getName().equals(b.getName()); } - public static int move(IFluidHandler from, IFluidHandler to) { + /** @return The fluidstack that was moved, or null if no fluid was moved. */ + @Nullable + public static FluidStack move(IFluidHandler from, IFluidHandler to) { return move(from, to, Integer.MAX_VALUE); } - public static int move(IFluidHandler from, IFluidHandler to, int max) { + /** @param max The maximum amount of fluid to move. + * @return The fluidstack that was moved, or null if no fluid was moved. */ + @Nullable + public static FluidStack move(IFluidHandler from, IFluidHandler to, int max) { if (from == null || to == null) { - return 0; + return null; } FluidStack toDrainPotential; if (from instanceof IFluidHandlerAdv) { @@ -153,7 +160,7 @@ public static int move(IFluidHandler from, IFluidHandler to, int max) { } int accepted = to.fill(toDrainPotential, false); if (accepted <= 0) { - return 0; + return null; } FluidStack toDrain = new FluidStack(toDrainPotential, accepted); FluidStack drained = from.drain(toDrain, true); @@ -164,6 +171,6 @@ public static int move(IFluidHandler from, IFluidHandler to, int max) { if (actuallyAccepted != accepted) { throw new IllegalStateException("Mismatched IFluidHandler implementations!"); } - return actuallyAccepted; + return new FluidStack(drained, accepted); } } diff --git a/common/buildcraft/lib/misc/SoundUtil.java b/common/buildcraft/lib/misc/SoundUtil.java index 20e0b989c3..21317b1fb9 100644 --- a/common/buildcraft/lib/misc/SoundUtil.java +++ b/common/buildcraft/lib/misc/SoundUtil.java @@ -10,6 +10,7 @@ import net.minecraft.block.SoundType; import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.item.EnumDyeColor; import net.minecraft.util.EnumActionResult; @@ -18,6 +19,8 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import net.minecraftforge.fluids.FluidStack; + public class SoundUtil { public static void playBlockPlace(World world, BlockPos pos) { playBlockPlace(world, pos, world.getBlockState(pos)); @@ -77,9 +80,24 @@ public static void playSlideSound(World world, BlockPos pos, IBlockState state) public static void playSlideSound(World world, BlockPos pos, IBlockState state, EnumActionResult result) { if (result == EnumActionResult.PASS) return; SoundType soundType = state.getBlock().getSoundType(state, world, pos, null); - SoundEvent soundEvent = result == EnumActionResult.SUCCESS ? SoundEvents.BLOCK_PISTON_CONTRACT : SoundEvents.BLOCK_PISTON_EXTEND; + SoundEvent event; + if (result == EnumActionResult.SUCCESS) { + event = SoundEvents.BLOCK_PISTON_CONTRACT; + } else { + event = SoundEvents.BLOCK_PISTON_EXTEND; + } float volume = (soundType.getVolume() + 1.0F) / 2.0F; float pitch = soundType.getPitch() * 0.8F; - world.playSound(null, pos, soundEvent, SoundCategory.BLOCKS, volume, pitch); + world.playSound(null, pos, event, SoundCategory.BLOCKS, volume, pitch); + } + + public static void playBucketEmpty(World world, BlockPos pos, FluidStack moved) { + SoundEvent sound = moved.getFluid().getEmptySound(moved); + world.playSound(null, pos, sound, SoundCategory.PLAYERS, 1, 1); + } + + public static void playBucketFill(World world, BlockPos pos, FluidStack moved) { + SoundEvent sound = moved.getFluid().getFillSound(moved); + world.playSound(null, pos, sound, SoundCategory.PLAYERS, 1, 1); } } diff --git a/common/buildcraft/lib/tile/TileBC_Neptune.java b/common/buildcraft/lib/tile/TileBC_Neptune.java index d2c6f1eef9..759b0b1eb2 100644 --- a/common/buildcraft/lib/tile/TileBC_Neptune.java +++ b/common/buildcraft/lib/tile/TileBC_Neptune.java @@ -37,7 +37,6 @@ import net.minecraft.util.math.Vec3i; import net.minecraft.world.Explosion; import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.Constants; @@ -61,7 +60,6 @@ import buildcraft.lib.fluid.TankManager; import buildcraft.lib.migrate.BCVersion; import buildcraft.lib.misc.BlockUtil; -import buildcraft.lib.misc.ChunkUtil; import buildcraft.lib.misc.InventoryUtil; import buildcraft.lib.misc.MessageUtil; import buildcraft.lib.misc.PermissionUtil; @@ -546,18 +544,22 @@ public void readFromNBT(NBTTagCompound nbt) { itemManager.deserializeNBT(nbt.getCompoundTag("items")); } if (nbt.hasKey("tanks", Constants.NBT.TAG_COMPOUND)) { + BCLog.logger.info("Loading tanks for " + getClass().getSimpleName() + " {"); tankManager.deserializeNBT(nbt.getCompoundTag("tanks")); + BCLog.logger.info("}"); } } protected void migrateOldNBT(int version, NBTTagCompound nbt) { // 7.99.0 -> 7.99.4 // Most tiles with a single tank saved it under "tank" + BCLog.logger.info("Migrating NBT for " + getClass() + " = " + nbt); NBTTagCompound tankComp = nbt.getCompoundTag("tank"); if (!tankComp.hasNoTags()) { NBTTagCompound tanks = new NBTTagCompound(); tanks.setTag("tank", tankComp); nbt.setTag("tanks", tanks); + BCLog.logger.info("Migrated a tank!"); } } @@ -577,6 +579,7 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { if (!tanks.hasNoTags()) { nbt.setTag("tanks", tanks); } + BCLog.logger.info("Writing NBT for " + getClass() + " = " + nbt); return nbt; } diff --git a/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java b/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java index 702971600e..a2e698afeb 100644 --- a/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java +++ b/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java @@ -503,8 +503,12 @@ private void moveToCenter() { int spaceAvailable = capacity - center.amount; int flowRate = fluidTransferInfo.transferPerTick; + List faces = new ArrayList<>(); + Collections.addAll(faces, EnumPipePart.FACES); + Collections.shuffle(faces); + int[] inputPerTick = new int[6]; - for (EnumPipePart part : EnumPipePart.FACES) { + for (EnumPipePart part : faces) { Section section = sections.get(part); inputPerTick[part.getIndex()] = 0; if (section.getCurrentDirection().canInput()) { From 9c806a5064f3801ca7a27d3bf9fd1d8a4c9235df Mon Sep 17 00:00:00 2001 From: AlexIIL Date: Tue, 4 Jul 2017 22:56:52 +0100 Subject: [PATCH 89/89] Minor fixes --- common/buildcraft/lib/fluid/Tank.java | 9 +++------ common/buildcraft/lib/misc/FluidUtilBC.java | 3 ++- common/buildcraft/lib/misc/SoundUtil.java | 1 - 3 files changed, 5 insertions(+), 8 deletions(-) diff --git a/common/buildcraft/lib/fluid/Tank.java b/common/buildcraft/lib/fluid/Tank.java index 816d2dca56..27b37ff340 100644 --- a/common/buildcraft/lib/fluid/Tank.java +++ b/common/buildcraft/lib/fluid/Tank.java @@ -35,6 +35,7 @@ import buildcraft.lib.gui.elem.ToolTip; import buildcraft.lib.gui.help.ElementHelpInfo; import buildcraft.lib.misc.LocaleUtil; +import buildcraft.lib.misc.SoundUtil; import buildcraft.lib.misc.StackUtil; import buildcraft.lib.net.PacketBufferBC; import buildcraft.lib.net.cache.BuildCraftObjectCaches; @@ -296,9 +297,7 @@ public void onGuiClicked(ContainerBC_Neptune container) { if (hasFilled) { FluidStack fl = getFluid(); if (fl != null) { - SoundEvent sound = - fl.getFluid().getEmptySound(container.player.world, container.player.getPosition()); - container.player.world.playSound(null, player.getPosition(), sound, SoundCategory.BLOCKS, 1, 1); + SoundUtil.playBucketEmpty(player.world, player.getPosition(), fl); } return; } @@ -320,9 +319,7 @@ public void onGuiClicked(ContainerBC_Neptune container) { player.inventory.setItemStack(filledContainer); ((EntityPlayerMP) player).updateHeldItem(); } - SoundEvent sound = - reallyDrained.getFluid().getFillSound(container.player.world, container.player.getPosition()); - container.player.world.playSound(null, player.getPosition(), sound, SoundCategory.BLOCKS, 1, 1); + SoundUtil.playBucketFill(player.world, player.getPosition(), reallyDrained); } } diff --git a/common/buildcraft/lib/misc/FluidUtilBC.java b/common/buildcraft/lib/misc/FluidUtilBC.java index eaed3ad93f..d76689a7ec 100644 --- a/common/buildcraft/lib/misc/FluidUtilBC.java +++ b/common/buildcraft/lib/misc/FluidUtilBC.java @@ -165,7 +165,8 @@ public static FluidStack move(IFluidHandler from, IFluidHandler to, int max) { FluidStack toDrain = new FluidStack(toDrainPotential, accepted); FluidStack drained = from.drain(toDrain, true); if (!toDrain.isFluidEqual(drained) || toDrain.amount != drained.amount) { - throw new IllegalStateException(""); + throw new IllegalStateException( + "Drained fluid did not equal expected fluid! Bad impl - " + from.getClass()); } int actuallyAccepted = to.fill(drained, true); if (actuallyAccepted != accepted) { diff --git a/common/buildcraft/lib/misc/SoundUtil.java b/common/buildcraft/lib/misc/SoundUtil.java index 21317b1fb9..1cc2a76704 100644 --- a/common/buildcraft/lib/misc/SoundUtil.java +++ b/common/buildcraft/lib/misc/SoundUtil.java @@ -10,7 +10,6 @@ import net.minecraft.block.SoundType; import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.item.EnumDyeColor; import net.minecraft.util.EnumActionResult;