diff --git a/README.md b/README.md index e82d0074..4218f239 100644 --- a/README.md +++ b/README.md @@ -4,3 +4,8 @@ Changes from Original: - Store Coordinates & rotation of schematics per world/server. No more re-entering coordinates for large builds! - Fix heavy lag when having lotr armor stands/weapon racks in loaded schematic - Updated Chinese translation + +### Schematic compatibility + +- Schematica reads `.schematic` and `.schemplus` files automatically. New saves use classic block ID encoding up to 4095 and support IDs up to 24 bits when needed. Older readers may truncate wide IDs or extended metadata. +- Schematic downloads require matching download protocol versions on the client and server. diff --git a/dependencies.gradle b/dependencies.gradle index 03105e0b..604b25d6 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -3,4 +3,26 @@ dependencies { implementation('com.github.GTNewHorizons:LunatriusCore:1.3.0-GTNH:dev') compileOnly rfg.deobf('curse.maven:lotr-423748:4091561') + compileOnly('com.github.GTNewHorizons:ForgeMultipart:1.7.18:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:CodeChickenCore:1.4.22:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:ArchitectureCraft:1.12.19:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:CarpentersBlocks:3.7.3-GTNH:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:CookingForBlockheads:1.4.14-GTNH:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:EnderIO:2.10.49:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:EnderCore:0.5.15:dev') { transitive = false } + compileOnly('com.github.GTNewHorizons:Postea:1.2.7:dev') { transitive = false } + + // Optional mods and their dependencies for the compatibility test client. + runtimeOnlyNonPublishable('com.github.GTNewHorizons:ForgeMultipart:1.7.18:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:CodeChickenCore:1.4.22:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:ArchitectureCraft:1.12.19:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:CarpentersBlocks:3.7.3-GTNH:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:Postea:1.2.7:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:CookingForBlockheads:1.4.14-GTNH:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:AppleCore:3.3.13:dev') { transitive = false } + runtimeOnlyNonPublishable('ganymedes01.etfuturum:Et-Futurum-Requiem:2.6.65-GTNH:dev') { transitive = false } + runtimeOnlyNonPublishable('com.github.GTNewHorizons:GTNHLib:0.11.48:dev') { transitive = false } + runtimeOnlyNonPublishable('io.github.legacymoddingmc:unimixins:0.3.1:dev') { transitive = false } + + testImplementation('junit:junit:4.13.2') } diff --git a/gradle/gradle-daemon-jvm.properties b/gradle/gradle-daemon-jvm.properties new file mode 100644 index 00000000..9926fc2a --- /dev/null +++ b/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,12 @@ +#This file is generated by updateDaemonJvm +toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/50d5fe9033e125599b2aa94dc590a27d/redirect +toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/b4d79acf73eaf165b8c6bc8fba023764/redirect +toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/50d5fe9033e125599b2aa94dc590a27d/redirect +toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/b4d79acf73eaf165b8c6bc8fba023764/redirect +toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/54e1f31b8c26d88fb972744b5f1ba132/redirect +toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/5d8d54de3a467a8da01a32410565830f/redirect +toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/50d5fe9033e125599b2aa94dc590a27d/redirect +toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/b4d79acf73eaf165b8c6bc8fba023764/redirect +toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/a7c7be8a3ec5d8e677e7250d9c1ce3ed/redirect +toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/d0edfb63e02dc58e61e6c804b15e02e8/redirect +toolchainVersion=25 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 37f853b1..c42672d9 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/settings.gradle b/settings.gradle index ff436f2c..bbc17851 100644 --- a/settings.gradle +++ b/settings.gradle @@ -17,7 +17,7 @@ pluginManagement { } plugins { - id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.38' + id 'com.gtnewhorizons.gtnhsettingsconvention' version '2.0.34' } diff --git a/src/main/java/com/github/lunatrius/schematica/FileFilterSchematic.java b/src/main/java/com/github/lunatrius/schematica/FileFilterSchematic.java index 04db84c3..3ef18c9f 100644 --- a/src/main/java/com/github/lunatrius/schematica/FileFilterSchematic.java +++ b/src/main/java/com/github/lunatrius/schematica/FileFilterSchematic.java @@ -2,11 +2,15 @@ import java.io.File; import java.io.FileFilter; +import java.util.Locale; -import com.github.lunatrius.schematica.handler.ConfigurationHandler; +import com.github.lunatrius.schematica.util.FileUtils; public class FileFilterSchematic implements FileFilter { + public static final String EXTENSION_SCHEMATIC = ".schematic"; + public static final String EXTENSION_SCHEMPLUS = ".schemplus"; + private final boolean directory; public FileFilterSchematic(boolean dir) { @@ -18,14 +22,58 @@ public boolean accept(File file) { if (this.directory) { return file.isDirectory(); } - if (ConfigurationHandler.useSchematicplusFormat) { - return file.getName() - .toLowerCase() - .endsWith(".schemplus"); - } else { - return file.getName() - .toLowerCase() - .endsWith(".schematic"); + return isSchematicName(file.getName()); + } + + public static boolean isSchematicName(String name) { + String lower = name.toLowerCase(Locale.ROOT); + return lower.endsWith(EXTENSION_SCHEMATIC) || lower.endsWith(EXTENSION_SCHEMPLUS); + } + + public static boolean isSchemplusName(String name) { + return name.toLowerCase(Locale.ROOT) + .endsWith(EXTENSION_SCHEMPLUS); + } + + public static String stripExtension(String filename) { + if (filename == null) { + return null; + } + String lower = filename.toLowerCase(Locale.ROOT); + if (lower.endsWith(EXTENSION_SCHEMPLUS)) { + return filename.substring(0, filename.length() - EXTENSION_SCHEMPLUS.length()); + } + if (lower.endsWith(EXTENSION_SCHEMATIC)) { + return filename.substring(0, filename.length() - EXTENSION_SCHEMATIC.length()); + } + return filename; + } + + /** + * Finds {@code name}, {@code name.schematic}, or {@code name.schemplus} inside {@code directory}. + * A bare name prefers {@code .schematic} when both files exist. + */ + public static File resolve(File directory, String name) { + if (directory == null || name == null || name.isEmpty()) { + return null; + } + + File direct = new File(directory, name); + if (isSchematicName(name) && FileUtils.contains(directory, direct) && direct.isFile()) { + return direct; + } + if (isSchematicName(name)) { + return null; + } + + File schematic = new File(directory, name + EXTENSION_SCHEMATIC); + if (FileUtils.contains(directory, schematic) && schematic.isFile()) { + return schematic; + } + File schemplus = new File(directory, name + EXTENSION_SCHEMPLUS); + if (FileUtils.contains(directory, schemplus) && schemplus.isFile()) { + return schemplus; } + return null; } } diff --git a/src/main/java/com/github/lunatrius/schematica/api/event/PreSchematicSaveEvent.java b/src/main/java/com/github/lunatrius/schematica/api/event/PreSchematicSaveEvent.java index 8ea10b00..2184c398 100644 --- a/src/main/java/com/github/lunatrius/schematica/api/event/PreSchematicSaveEvent.java +++ b/src/main/java/com/github/lunatrius/schematica/api/event/PreSchematicSaveEvent.java @@ -14,7 +14,7 @@ */ public class PreSchematicSaveEvent extends Event { - private final Map mappings; + private final Map mappings; /** * The schematic that will be saved. @@ -27,11 +27,11 @@ public class PreSchematicSaveEvent extends Event { public final NBTTagCompound extendedMetadata; @Deprecated - public PreSchematicSaveEvent(Map mappings) { + public PreSchematicSaveEvent(Map mappings) { this(null, mappings); } - public PreSchematicSaveEvent(ISchematic schematic, Map mappings) { + public PreSchematicSaveEvent(ISchematic schematic, Map mappings) { this.schematic = schematic; this.mappings = mappings; this.extendedMetadata = new NBTTagCompound(); @@ -59,7 +59,7 @@ public boolean replaceMapping(String oldName, String newName) throws DuplicateMa newName)); } - Short id = this.mappings.get(oldName); + Integer id = this.mappings.get(oldName); if (id != null) { this.mappings.remove(oldName); this.mappings.put(newName, id); diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java new file mode 100644 index 00000000..59ed9f34 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/ArchitectureCraftSupport.java @@ -0,0 +1,280 @@ +package com.github.lunatrius.schematica.client.compat; + +import net.minecraft.block.Block; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import gcewing.architecture.ArchitectureCraft; +import gcewing.architecture.common.block.BlockShape; +import gcewing.architecture.common.item.ItemCladding; +import gcewing.architecture.common.shape.Shape; +import gcewing.architecture.common.shape.ShapeItem; +import gcewing.architecture.common.shape.ShapeSymmetry; +import gcewing.architecture.common.tile.TileArchitecture; +import gcewing.architecture.common.tile.TileShape; +import gcewing.architecture.compat.BlockCompatUtils; +import gcewing.architecture.compat.BlockPos; +import gcewing.architecture.compat.IBlockState; +import gcewing.architecture.compat.Trans3; +import gcewing.architecture.compat.Vector3; +import gcewing.architecture.util.Utils; + +public final class ArchitectureCraftSupport { + + private static final double[] HIT_OFFSETS = { 0.5, 0.125, 0.875 }; + public static final String NBT_SHAPE = "Shape"; + public static final String NBT_BASE_DATA = "BaseData"; + public static final String NBT_BASE_NAME = "BaseName"; + + private ArchitectureCraftSupport() {} + + public static boolean isShapeBlock(Block block) { + return block instanceof BlockShape; + } + + public static boolean isShapeItem(ItemStack stack) { + return stack.getItem() instanceof ShapeItem; + } + + public static String getMaterialName(ItemStack stack) { + if (stack.getItem() instanceof ItemCladding cladding) { + final IBlockState material = cladding.blockStateFromStack(stack); + return material == null ? "" + : Utils.displayNameOfBlock(material.getBlock(), BlockCompatUtils.getMetaFromBlockState(material)); + } + if (!isShapeItem(stack)) { + return ""; + } + final NBTTagCompound tag = stack.getTagCompound(); + final Block base = tag == null ? null : Block.getBlockFromName(tag.getString(NBT_BASE_NAME)); + return base == null ? "" : Utils.displayNameOfBlock(base, tag.getInteger(NBT_BASE_DATA)); + } + + public static ItemStack getSecondaryItem(TileEntity tile) { + if (tile instanceof TileShape shape && shape.shape != null && shape.secondaryBlockState != null) { + return shape.shape.kind.newSecondaryMaterialStack(shape.secondaryBlockState); + } + return null; + } + + public static ItemStack getItem(TileEntity tile, Block block) { + if (tile instanceof TileShape shape && shape.shape != null) { + return TileArchitecture.blockStackWithTileEntity(block, 1, shape); + } + return null; + } + + public static boolean itemsMatch(ItemStack stack, ItemStack target) { + return sameShape(stack, target); + } + + public static int getDisabledConnections(ItemStack stack) { + final NBTTagCompound tag = stack.getTagCompound(); + return tag == null ? 0 : tag.getInteger("Disconnected"); + } + + private static boolean sameShape(ItemStack stack, ItemStack target) { + final NBTTagCompound tag = stack.getTagCompound(); + final NBTTagCompound expected = target.getTagCompound(); + return tag != null && expected != null + && tag.hasKey(NBT_SHAPE) + && expected.hasKey(NBT_SHAPE) + && tag.getInteger(NBT_SHAPE) == expected.getInteger(NBT_SHAPE) + && tag.getInteger(NBT_BASE_DATA) == expected.getInteger(NBT_BASE_DATA) + && tag.getString(NBT_BASE_NAME) + .equals(expected.getString(NBT_BASE_NAME)); + } + + public static boolean matches(TileEntity placed, TileEntity target, Block block) { + if (!(placed instanceof TileShape actual) || !(target instanceof TileShape expected)) { + return false; + } + final ItemStack actualItem = getItem(actual, block); + final ItemStack expectedItem = getItem(expected, block); + return actualItem != null && expectedItem != null + && sameShape(actualItem, expectedItem) + && sameOrientation(actual, expected); + } + + public static boolean matchesPreview(TileEntity placed, TileEntity target, Block block) { + return placed instanceof TileShape actual && target instanceof TileShape expected + && matches(actual, expected, block) + && actual.disabledConnections == expected.disabledConnections + && sameMaterial(actual.secondaryBlockState, expected.secondaryBlockState); + } + + private static boolean sameMaterial(IBlockState actual, IBlockState expected) { + return actual == expected || (actual != null && expected != null + && actual.getBlock() == expected.getBlock() + && BlockCompatUtils.getMetaFromBlockState(actual) == BlockCompatUtils.getMetaFromBlockState(expected)); + } + + private static boolean sameOrientation(TileShape actual, TileShape expected) { + return actual.side == expected.side && actual.getOffsetX() == expected.getOffsetX() + && (actual.turn == expected.turn + || (expected.shape.symmetry == ShapeSymmetry.Quadrilateral && !requiresCapitalTurn(expected.shape))); + } + + private static boolean requiresCapitalTurn(Shape shape) { + return shape == Shape.DoricCapital || shape == Shape.CorinthianCapital; + } + + public static boolean isTurnableCapital(TileEntity tile) { + return tile instanceof TileShape shape && requiresCapitalTurn(shape.shape) && shape.getOffsetX() == 0; + } + + public static ItemStack getHammer() { + return new ItemStack(ArchitectureCraft.content.itemHammer); + } + + public static boolean needsHammerTurn(TileEntity placed, TileEntity target) { + return placed instanceof TileShape actual && target instanceof TileShape expected + && canHammerTurn(actual, expected) + && sameMaterial(actual.baseBlockState, expected.baseBlockState); + } + + public static int getTurn(TileEntity tile) { + return ((TileShape) tile).turn; + } + + private static boolean canHammerTurn(TileShape actual, TileShape expected) { + return isTurnableCapital(expected) && actual.shape == expected.shape + && actual.side == expected.side + && actual.getOffsetX() == 0 + && actual.turn != expected.turn; + } + + public static Vec3 findHit(EntityClientPlayerMP player, World world, TileEntity target, ItemStack stack, int x, + int y, int z, ForgeDirection support, boolean sneaking, boolean allowHammerTurn) { + if (!(target instanceof TileShape expected) || expected.shape == null) { + return null; + } + + final boolean originalSneak = player.movementInput.sneak; + player.movementInput.sneak = sneaking; + try { + final ForgeDirection face = support.getOpposite(); + final BlockPos neighbor = new BlockPos(x + support.offsetX, y + support.offsetY, z + support.offsetZ); + final TileEntity neighborTile = world.getTileEntity(neighbor.x, neighbor.y, neighbor.z); + final TileShape candidate = new TileShape(); + candidate.xCoord = x; + candidate.yCoord = y; + candidate.zCoord = z; + candidate.setWorldObj(world); + candidate.readFromItemStack(stack); + for (double u : HIT_OFFSETS) { + for (double v : HIT_OFFSETS) { + final double hitX = support.offsetX == 0 ? u : (1 + face.offsetX) / 2.0; + final double hitY = support.offsetY == 0 ? (support.offsetX == 0 ? v : u) + : (1 + face.offsetY) / 2.0; + final double hitZ = support.offsetZ == 0 ? v : (1 + face.offsetZ) / 2.0; + final Vector3 relative = new Vector3( + hitX - face.offsetX - 0.5, + hitY - face.offsetY - 0.5, + hitZ - face.offsetZ - 0.5); + candidate.setSide(0); + candidate.setTurn(0); + candidate.setOffsetX(0); + candidate.shape.orientOnPlacement( + player, + candidate, + neighbor, + BlockCompatUtils.getWorldBlockState(world, neighbor), + neighborTile, + EnumFacing.values()[face.ordinal()], + relative); + if (sameOrientation(candidate, expected) + || (allowHammerTurn && canHammerTurn(candidate, expected))) { + return Vec3.createVectorHelper(neighbor.x + hitX, neighbor.y + hitY, neighbor.z + hitZ); + } + } + } + return null; + } finally { + player.movementInput.sneak = originalSneak; + } + } + + public static void transform(TileEntity tile, ForgeDirection axis, boolean mirror) { + if (!(tile instanceof TileShape shape) || shape.shape == null + || shape.side < 0 + || shape.side >= 6 + || shape.turn < 0 + || shape.turn >= 4) { + return; + } + + Trans3 orientation = Trans3.sideTurn(shape.side, shape.turn); + int mirrorTurn = 0; + if (mirror) { + // The reflection is represented by a proper rotation and a reflection across the shape's local X axis. + switch (shape.shape) { + case RoofOverhangGableLH -> shape.shape = Shape.RoofOverhangGableRH; + case RoofOverhangGableRH -> shape.shape = Shape.RoofOverhangGableLH; + case RoofOverhangGableEndLH -> shape.shape = Shape.RoofOverhangGableEndRH; + case RoofOverhangGableEndRH -> shape.shape = Shape.RoofOverhangGableEndLH; + case CorniceLH -> shape.shape = Shape.CorniceRH; + case CorniceRH -> shape.shape = Shape.CorniceLH; + case CorniceEndLH -> shape.shape = Shape.CorniceEndRH; + case CorniceEndRH -> shape.shape = Shape.CorniceEndLH; + default -> {} + } + shape.setOffsetX(-shape.getOffsetX()); + // Placement symmetry differs from the mirrored geometry of these models. + mirrorTurn = switch (shape.shape) { + case AngledRoofRidge, DoricTriglyphCorner -> 1; + case DoubleRoofTile, IonicCapital, DoricCapital, CorinthianCapital -> 2; + default -> shape.shape.symmetry == ShapeSymmetry.Unilateral ? 1 : 0; + }; + } + + final Vector3 up = transform(orientation.v(0, 1, 0), axis, mirror); + final Vector3 forward = transform(orientation.v(0, 0, 1), axis, mirror); + for (int side = 0; side < 6; side++) { + for (int turn = 0; turn < 4; turn++) { + final Trans3 candidate = Trans3.sideTurn(side, turn); + if (candidate.v(0, 1, 0) + .dot(up) > 0.99 + && candidate.v(0, 0, 1) + .dot(forward) > 0.99) { + shape.setSide(side); + shape.setTurn((turn + mirrorTurn) & 3); + } + } + } + + int connections = shape.disabledConnections & ~0x3f; + for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) { + if ((shape.disabledConnections & 1 << direction.ordinal()) == 0) { + continue; + } + final Vector3 transformed = transform( + new Vector3(direction.offsetX, direction.offsetY, direction.offsetZ), + axis, + mirror); + for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) { + if (transformed.dot(face.offsetX, face.offsetY, face.offsetZ) > 0.99) { + connections |= 1 << face.ordinal(); + } + } + } + shape.disabledConnections = connections; + } + + private static Vector3 transform(Vector3 vector, ForgeDirection axis, boolean mirror) { + return switch (axis) { + case EAST -> mirror ? new Vector3(-vector.x, vector.y, vector.z) + : new Vector3(vector.x, vector.z, -vector.y); + case UP -> mirror ? new Vector3(vector.x, -vector.y, vector.z) : new Vector3(-vector.z, vector.y, vector.x); + case SOUTH -> mirror ? new Vector3(vector.x, vector.y, -vector.z) + : new Vector3(vector.y, -vector.x, vector.z); + default -> vector; + }; + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java new file mode 100644 index 00000000..339e12b0 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersBlocksSupport.java @@ -0,0 +1,456 @@ +package com.github.lunatrius.schematica.client.compat; + +import java.util.function.BiConsumer; +import java.util.function.Predicate; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockDirectional; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Direction; +import net.minecraft.util.MathHelper; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import com.carpentersblocks.api.ICarpentersChisel; +import com.carpentersblocks.api.ICarpentersHammer; +import com.carpentersblocks.block.BlockCarpentersBlock; +import com.carpentersblocks.block.BlockCarpentersCollapsibleBlock; +import com.carpentersblocks.block.BlockCarpentersGarageDoor; +import com.carpentersblocks.block.BlockCarpentersLadder; +import com.carpentersblocks.block.BlockCarpentersSlope; +import com.carpentersblocks.block.BlockCarpentersStairs; +import com.carpentersblocks.block.BlockCarpentersTorch; +import com.carpentersblocks.block.BlockCoverable; +import com.carpentersblocks.data.Collapsible; +import com.carpentersblocks.data.GarageDoor; +import com.carpentersblocks.data.Ladder; +import com.carpentersblocks.data.Slope; +import com.carpentersblocks.data.Stairs; +import com.carpentersblocks.data.Torch; +import com.carpentersblocks.network.PacketActivateBlock; +import com.carpentersblocks.tileentity.TEBase; +import com.carpentersblocks.util.BlockProperties; +import com.carpentersblocks.util.handler.PacketHandler; +import com.carpentersblocks.util.protection.PlayerPermissions; +import com.carpentersblocks.util.registry.FeatureRegistry; +import com.github.lunatrius.schematica.client.util.BlockToItemStack; +import com.github.lunatrius.schematica.client.world.SchematicWorld; +import com.github.lunatrius.schematica.reference.Mods; + +public final class CarpentersBlocksSupport { + + private static final int BASE = 6; + private static final byte[][] SURFACE_ATTRIBUTES = { TEBase.ATTR_COVER, TEBase.ATTR_DYE, TEBase.ATTR_OVERLAY }; + private static final int[] TOP_BOTTOM_FACING = { 0, 3, 1, 2 }; + private static final int[] SLOPE_CORNERS = { 2, 0, 3, 1 }; + private static final int[] WEDGE_NEAR = { Slope.ID_WEDGE_NW, Slope.ID_WEDGE_SE, Slope.ID_WEDGE_SW, + Slope.ID_WEDGE_NE }; + private static final int[] WEDGE_FAR = { Slope.ID_WEDGE_NE, Slope.ID_WEDGE_SW, Slope.ID_WEDGE_NW, + Slope.ID_WEDGE_SE }; + private static final Ladder LADDER = new Ladder(); + private static final Torch TORCH = new Torch(); + + private CarpentersBlocksSupport() {} + + public static boolean isCoverable(Block block) { + return block instanceof BlockCoverable; + } + + public static boolean isStairs(Block block) { + return block instanceof BlockCarpentersStairs; + } + + public static boolean isCollapsible(Block block) { + return block instanceof BlockCarpentersCollapsibleBlock; + } + + public static ForgeDirection getCollapsibleDirection(TileEntity tile) { + return tile instanceof TEBase carpenter ? Collapsible.INSTANCE.getDirection(carpenter) : ForgeDirection.UNKNOWN; + } + + public static boolean isGarageDoor(Block block) { + return block instanceof BlockCarpentersGarageDoor; + } + + public static boolean isGarageDoorHost(TileEntity tile) { + return tile instanceof TEBase carpenter && GarageDoor.INSTANCE.isHost(carpenter); + } + + public static ForgeDirection getAttachmentDirection(Block block, TileEntity tile) { + if (block instanceof BlockCarpentersLadder) { + return tile instanceof TEBase carpenter ? LADDER.getDirection(carpenter) : ForgeDirection.UNKNOWN; + } + if (block instanceof BlockCarpentersTorch) { + return tile instanceof TEBase carpenter ? TORCH.getDirection(carpenter) : ForgeDirection.UNKNOWN; + } + return null; + } + + public static boolean isFreestandingLadder(Block block, ForgeDirection direction) { + return block instanceof BlockCarpentersLadder && direction.offsetY != 0; + } + + public static boolean isSlope(Block block) { + return block instanceof BlockCarpentersSlope; + } + + public static ItemStack getSlopeItem(Block block, TileEntity tile) { + if (!(tile instanceof TEBase slope) || slope.getData() < 0 || slope.getData() > Slope.ID_PRISM_WEDGE_POS_E) { + return null; + } + final int data = slope.getData(); + final int subtype; + if (data >= Slope.ID_PRISM_WEDGE_POS_N) { + subtype = BlockCarpentersSlope.META_PRISM_SLOPE; + } else if (data >= Slope.ID_PRISM_NEG) { + subtype = BlockCarpentersSlope.META_PRISM; + } else if (data >= Slope.ID_OBL_EXT_NEG_SE) { + subtype = BlockCarpentersSlope.META_OBLIQUE_EXT; + } else if (data >= Slope.ID_OBL_INT_NEG_SE) { + subtype = BlockCarpentersSlope.META_OBLIQUE_INT; + } else { + subtype = BlockCarpentersSlope.META_WEDGE; + } + return new ItemStack(block, 1, subtype); + } + + public static ItemStack getWedgeItem(ItemStack slope) { + return new ItemStack(slope.getItem(), 1, BlockCarpentersSlope.META_WEDGE); + } + + public static boolean matchesSlopePlacement(TileEntity tile, ItemStack item, ForgeDirection face, float hitX, + float hitY, float hitZ, float yaw, boolean allowReshape) { + if (!(tile instanceof TEBase expected)) { + return false; + } + final int facing = MathHelper.floor_double(yaw * 4.0F / 360.0F + 0.5D) & 3; + final int corner = SLOPE_CORNERS[MathHelper.floor_double(yaw * 4.0F / 360.0F) & 3]; + final boolean positive = face == ForgeDirection.UP || (face.offsetY == 0 && hitY < 0.5f); + // Sneaking disables native neighbor reshaping during placement. + final int initial = switch (item.getItemDamage()) { + case BlockCarpentersSlope.META_WEDGE -> wedgePlacement(face, hitX, hitY, hitZ, facing); + case BlockCarpentersSlope.META_OBLIQUE_INT -> (positive ? Slope.ID_OBL_INT_POS_SE : Slope.ID_OBL_INT_NEG_SE) + + corner; + case BlockCarpentersSlope.META_OBLIQUE_EXT -> (positive ? Slope.ID_OBL_EXT_POS_SE : Slope.ID_OBL_EXT_NEG_SE) + + corner; + case BlockCarpentersSlope.META_PRISM -> positive ? Slope.ID_PRISM_POS : Slope.ID_PRISM_NEG; + case BlockCarpentersSlope.META_PRISM_SLOPE -> Slope.ID_PRISM_WEDGE_POS_N + TOP_BOTTOM_FACING[facing]; + default -> -1; + }; + return initial >= 0 && (initial == expected.getData() + || (allowReshape && CarpentersHammerSupport.canReshapeSlope(expected.getData(), initial))); + } + + private static int wedgePlacement(ForgeDirection face, float hitX, float hitY, float hitZ, int facing) { + if (face.offsetY != 0) { + final int base = face == ForgeDirection.UP ? Slope.ID_WEDGE_POS_N : Slope.ID_WEDGE_NEG_N; + return base + TOP_BOTTOM_FACING[facing]; + } + final float across = switch (face) { + case NORTH -> 1 - hitX; + case WEST -> hitZ; + case EAST -> 1 - hitZ; + default -> hitX; + }; + final int side = face.ordinal(); + if (hitY > 0.5f && across > 1 - hitY && across < hitY) { + return side + 2; + } + if (hitY < 0.5f && across < 1 - hitY && across > hitY) { + return side + 6; + } + if (across < 0.2f) { + return WEDGE_NEAR[side - 2]; + } + if (across > 0.8f) { + return WEDGE_FAR[side - 2]; + } + return side + (hitY > 0.5f ? 2 : 6); + } + + public static boolean canConfigure(TileEntity tile, EntityPlayer player) { + // A rejected edit can fall through to normal activation. Remote clients only know the synced owner. + return tile instanceof TEBase carpenter && PlayerPermissions.hasElevatedPermission(carpenter, player, true); + } + + public static boolean passesThroughMicroblockClick(Block block) { + return block instanceof BlockCarpentersBlock || isStairs(block) || isCollapsible(block); + } + + public static boolean isCarpenterTool(ItemStack stack) { + return stack.getItem() instanceof ICarpentersHammer || stack.getItem() instanceof ICarpentersChisel; + } + + public static boolean usesActivationPacket(ItemStack stack) { + return !(stack.getItem() instanceof ItemBlock) || BlockProperties.isOverlay(stack); + } + + public static void sendActivation(int x, int y, int z, int side) { + PacketHandler.sendPacketToServer(new PacketActivateBlock(x, y, z, side)); + } + + public static boolean allowsPlacementClick(Block clicked, ItemStack stack, boolean sneaking) { + if (!isCoverable(clicked)) { + return true; + } + if (sneaking) { + return !usesActivationPacket(stack); + } + return Mods.FORGE_MICROBLOCK && MicroblockSupport.isMicroblockItem(stack) + && passesThroughMicroblockClick(clicked); + } + + public static void addMaterials(TileEntity target, TileEntity placed, BiConsumer add) { + if (!(target instanceof TEBase expected)) { + return; + } + final TEBase actual = placed instanceof TEBase carpenter ? carpenter : null; + for (byte[] attributes : SURFACE_ATTRIBUTES) { + for (byte attribute : attributes) { + addMaterial(expected, actual, attribute, add); + } + } + addMaterial(expected, actual, TEBase.ATTR_ILLUMINATOR, add); + } + + private static void addMaterial(TEBase expected, TEBase actual, byte attribute, + BiConsumer add) { + final ItemStack stack = expected.getAttribute(attribute); + if (stack != null) { + add.accept(ingredient(stack, attribute), matches(stack, actual, attribute)); + } + } + + private static boolean matches(ItemStack expected, TEBase actual, byte attribute) { + final ItemStack placed = actual == null ? null : actual.getAttribute(attribute); + return expected == null ? placed == null : placed != null && BlockToItemStack.matches(placed, expected); + } + + private static ItemStack ingredient(ItemStack stack, byte attribute) { + final ItemStack ingredient = stack.copy(); + ingredient.stackSize = 1; + if (attribute <= TEBase.ATTR_COVER[BASE]) { + final Block block = BlockProperties.toBlock(stack); + final int damage = stack.getItemDamage(); + if (BlockProperties.blockRotates(stack) || block instanceof BlockDirectional) { + ingredient.setItemDamage(block.damageDropped(damage)); + } + } + return ingredient; + } + + public static boolean matches(Block block, TileEntity target, TileEntity placed) { + if (!(target instanceof TEBase expected)) { + return placed == null; + } + if (!(placed instanceof TEBase actual) || !matchesShape(block, expected, actual) + || !CarpentersHammerSupport.matchesSettings(block, expected, actual)) { + return false; + } + for (byte[] attributes : SURFACE_ATTRIBUTES) { + for (byte attribute : attributes) { + if (!matches(expected.getAttribute(attribute), actual, attribute)) { + return false; + } + } + } + return matches(expected.getAttribute(TEBase.ATTR_ILLUMINATOR), actual, TEBase.ATTR_ILLUMINATOR); + } + + private static boolean matchesShape(Block block, TEBase expected, TEBase actual) { + if (isGarageDoor(block)) { + return GarageDoor.INSTANCE.getDirection(actual) == GarageDoor.INSTANCE.getDirection(expected) + && GarageDoor.INSTANCE.isHost(actual) == GarageDoor.INSTANCE.isHost(expected); + } + if (isCollapsible(block)) { + return getCollapsibleDirection(actual) == getCollapsibleDirection(expected); + } + return !(block instanceof BlockCarpentersBlock || block instanceof BlockCarpentersSlope || isStairs(block)) + || actual.getData() == expected.getData(); + } + + public static Float findGarageDoorYaw(Block block, SchematicWorld schematic, World world, int x, int y, int z) { + final GarageDoor door = GarageDoor.INSTANCE; + if (!(schematic.getTileEntity(x, y, z) instanceof TEBase host) || !door.isHost(host)) { + return null; + } + final ForgeDirection direction = door.getDirection(host); + if (direction.offsetY != 0 || direction == ForgeDirection.UNKNOWN) { + return null; + } + final int wx = schematic.position.x + x; + final int wy = schematic.position.y + y; + final int wz = schematic.position.z + z; + if (!block.canPlaceBlockOnSide(world, wx, wy, wz, ForgeDirection.DOWN.ordinal())) { + return null; + } + + // Native placement fills the replaceable prefix. Every remaining saved panel must already exist. + boolean fillsPanel = true; + for (int panelY = y - 1, worldY = wy - 1;; panelY--, worldY--) { + fillsPanel = fillsPanel && worldY >= 0 + && world.getBlock(wx, worldY, wz) + .isReplaceable(world, wx, worldY, wz); + if (schematic.getBlockIncludingHiddenLayers(x, panelY, z) != block) { + if (fillsPanel) { + return null; + } + break; + } + if (!(schematic.getTileEntity(x, panelY, z) instanceof TEBase savedPanel)) { + return null; + } + if (door.isHost(savedPanel)) { + if (fillsPanel) { + return null; + } + break; + } + if (door.getDirection(savedPanel) != direction + || (!fillsPanel && (worldY < 0 || world.getBlock(wx, worldY, wz) != block + || !isGaragePanel(world.getTileEntity(wx, worldY, wz), direction)))) { + return null; + } + } + return Direction.facingToDirection[direction.ordinal()] * 90.0f; + } + + private static boolean isGaragePanel(TileEntity tile, ForgeDirection direction) { + return tile instanceof TEBase panel && !GarageDoor.INSTANCE.isHost(panel) + && GarageDoor.INSTANCE.getDirection(panel) == direction; + } + + public static boolean matchesStairPlacement(TileEntity tile, Block block, World world, int x, int y, int z, + int side, float hitX, float hitY, float hitZ, float yaw, boolean allowReshape) { + if (!(tile instanceof TEBase expected)) { + return false; + } + final int metadata = block.onBlockPlaced(world, x, y, z, side, hitX, hitY, hitZ, 0); + final int facing = MathHelper.floor_double(yaw * 4.0F / 360.0F + 0.5D) & 3; + final int data = metadata < 12 ? metadata + : (metadata == 12 ? Stairs.ID_NORMAL_NEG_N : Stairs.ID_NORMAL_POS_N) + TOP_BOTTOM_FACING[facing]; + return data == expected.getData() + || (allowReshape && CarpentersHammerSupport.canReshapeStair(expected.getData(), data)); + } + + public static Interaction findAttachment(Block block, TileEntity target, TileEntity placed, EntityPlayer player, + Predicate available) { + if (!(target instanceof TEBase expected) || !(placed instanceof TEBase actual) + || !matchesShape(block, expected, actual) + || (isGarageDoor(block) && GarageDoor.INSTANCE.isOpen(actual))) { + return null; + } + final boolean hasBaseCover = actual.hasAttribute(TEBase.ATTR_COVER[BASE]); + final int bareFace = uncoveredFace(actual); + if (bareFace != -1) { + final Interaction decoration = findDecoration(expected, actual, BASE, bareFace, available); + if (decoration != null) { + return decoration; + } + } + final boolean needsBaseDecoration = (FeatureRegistry.enableDyeColors + && isMissing(expected, actual, TEBase.ATTR_DYE[BASE])) + || (FeatureRegistry.enableOverlays && isMissing(expected, actual, TEBase.ATTR_OVERLAY[BASE])); + for (int side = BASE; side >= 0; side--) { + final byte attribute = TEBase.ATTR_COVER[side]; + final ItemStack cover = expected.getAttribute(attribute); + // Leave a bare face available for base decorations, even if their items are currently missing. + if (side == bareFace && needsBaseDecoration) { + continue; + } + if (FeatureRegistry.enableCovers && cover != null + && !actual.hasAttribute(attribute) + && (side == BASE ? bareFace != -1 : hasBaseCover)) { + final ItemStack item = ingredient(cover, attribute); + if (available.test(item) && BlockProperties.isCover(item) + && matchesCoverDamage(cover, item, actual, player)) { + return new Interaction(item, side == BASE ? bareFace : side, false, attribute, cover); + } + } + } + if (FeatureRegistry.enableIllumination) { + final Interaction illuminator = missing(expected, actual, TEBase.ATTR_ILLUMINATOR, 1, available); + if (illuminator != null) { + return illuminator; + } + } + for (int face = 0; face < BASE; face++) { + if (actual.hasAttribute(TEBase.ATTR_COVER[face])) { + final Interaction decoration = findDecoration(expected, actual, face, face, available); + if (decoration != null) { + return decoration; + } + } + } + return null; + } + + private static Interaction findDecoration(TEBase expected, TEBase actual, int side, int face, + Predicate available) { + final Interaction dye = FeatureRegistry.enableDyeColors + ? missing(expected, actual, TEBase.ATTR_DYE[side], face, available) + : null; + return dye != null || !FeatureRegistry.enableOverlays ? dye + : missing(expected, actual, TEBase.ATTR_OVERLAY[side], face, available); + } + + private static boolean matchesCoverDamage(ItemStack cover, ItemStack item, TEBase tile, EntityPlayer player) { + final Block block = BlockProperties.toBlock(item); + int damage = block instanceof BlockDirectional + ? MathHelper.floor_double(player.rotationYaw * 4.0F / 360.0F + 2.5D) & 3 + : item.getItemDamage(); + if (BlockProperties.blockRotates(item)) { + final int facing = MathHelper.floor_double(player.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; + final int side = player.rotationPitch < -45 ? 0 + : player.rotationPitch > 45 ? 1 : Direction.directionToFacing[Direction.rotateOpposite[facing]]; + damage = block + .onBlockPlaced(player.worldObj, tile.xCoord, tile.yCoord, tile.zCoord, side, 0.5f, 0.5f, 0.5f, damage); + } + return damage == cover.getItemDamage(); + } + + private static int uncoveredFace(TEBase tile) { + for (int side = 0; side < BASE; side++) { + if (!tile.hasAttribute(TEBase.ATTR_COVER[side])) { + return side; + } + } + return -1; + } + + private static Interaction missing(TEBase expected, TEBase actual, byte attribute, int face, + Predicate available) { + final ItemStack stack = expected.getAttribute(attribute); + return stack != null && !actual.hasAttribute(attribute) && available.test(stack) + ? new Interaction(stack, face, true, attribute, stack) + : null; + } + + private static boolean isMissing(TEBase expected, TEBase actual, byte attribute) { + return expected.hasAttribute(attribute) && !actual.hasAttribute(attribute); + } + + public static final class Interaction { + + public final ItemStack item; + public final int face; + public final boolean sneaking; + private final byte attribute; + private final ItemStack expected; + + private Interaction(ItemStack item, int face, boolean sneaking, byte attribute, ItemStack expected) { + this.item = item; + this.face = face; + this.sneaking = sneaking; + this.attribute = attribute; + this.expected = expected; + } + + public boolean isConfirmed(TileEntity tile) { + return tile instanceof TEBase carpenter && matches(this.expected, carpenter, this.attribute); + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java new file mode 100644 index 00000000..8eb79477 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CarpentersHammerSupport.java @@ -0,0 +1,563 @@ +package com.github.lunatrius.schematica.client.compat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.IntUnaryOperator; +import java.util.function.Predicate; + +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import com.carpentersblocks.api.ICarpentersHammer; +import com.carpentersblocks.block.BlockCarpentersBarrier; +import com.carpentersblocks.block.BlockCarpentersBed; +import com.carpentersblocks.block.BlockCarpentersBlock; +import com.carpentersblocks.block.BlockCarpentersButton; +import com.carpentersblocks.block.BlockCarpentersCollapsibleBlock; +import com.carpentersblocks.block.BlockCarpentersDaylightSensor; +import com.carpentersblocks.block.BlockCarpentersDoor; +import com.carpentersblocks.block.BlockCarpentersFlowerPot; +import com.carpentersblocks.block.BlockCarpentersGarageDoor; +import com.carpentersblocks.block.BlockCarpentersGate; +import com.carpentersblocks.block.BlockCarpentersHatch; +import com.carpentersblocks.block.BlockCarpentersLadder; +import com.carpentersblocks.block.BlockCarpentersLever; +import com.carpentersblocks.block.BlockCarpentersPressurePlate; +import com.carpentersblocks.block.BlockCarpentersSafe; +import com.carpentersblocks.block.BlockCarpentersSlope; +import com.carpentersblocks.block.BlockCarpentersStairs; +import com.carpentersblocks.block.BlockCarpentersTorch; +import com.carpentersblocks.data.Barrier; +import com.carpentersblocks.data.Bed; +import com.carpentersblocks.data.Button; +import com.carpentersblocks.data.Collapsible; +import com.carpentersblocks.data.DaylightSensor; +import com.carpentersblocks.data.GarageDoor; +import com.carpentersblocks.data.Gate; +import com.carpentersblocks.data.Hatch; +import com.carpentersblocks.data.Hinge; +import com.carpentersblocks.data.Ladder; +import com.carpentersblocks.data.Lever; +import com.carpentersblocks.data.PressurePlate; +import com.carpentersblocks.data.Safe; +import com.carpentersblocks.data.Slab; +import com.carpentersblocks.data.Slope; +import com.carpentersblocks.data.Stairs; +import com.carpentersblocks.data.Torch; +import com.carpentersblocks.tileentity.TEBase; +import com.carpentersblocks.util.collapsible.CollapsibleUtil; +import com.carpentersblocks.util.handler.DesignHandler; +import com.carpentersblocks.util.registry.FeatureRegistry; +import com.carpentersblocks.util.registry.ItemRegistry; +import com.github.lunatrius.schematica.client.world.SchematicWorld; + +public final class CarpentersHammerSupport { + + private static final Slab SLAB = new Slab(); + private static final Ladder LADDER = new Ladder(); + private static final Torch TORCH = new Torch(); + private static final DaylightSensor SENSOR = new DaylightSensor(); + private static final PressurePlate PRESSURE_PLATE = new PressurePlate(); + private static final Button BUTTON = new Button(); + private static final Lever LEVER = new Lever(); + private static final double[] CORNER_SAMPLES = { 0.5, 0.0625, 0.9375 }; + private static final double[] CORNER_HEIGHTS = { 0.5, 1, 0 }; + + private static final BlockSettings NO_SETTINGS = new BlockSettings(Block.class); + // Settings are ordered by the sequence in which the hammer should adjust them. + private static final BlockSettings[] BLOCK_SETTINGS = { + new BlockSettings( + BlockCarpentersGarageDoor.class, + cycle(GarageDoor.INSTANCE::getType, BlockCarpentersGarageDoor.type.length), + toggle(GarageDoor.INSTANCE::getRigidity, Click.SNEAK_RIGHT)), + new BlockSettings( + BlockCarpentersBarrier.class, + new Setting<>(Barrier::getType, CarpentersHammerSupport::fenceClick), + toggle(Barrier::getPost, Click.MANUAL)), + new BlockSettings(BlockCarpentersGate.class, new Setting<>(Gate::getType, CarpentersHammerSupport::fenceClick)), + new BlockSettings( + BlockCarpentersDoor.class, + cycle(Hinge::getType, BlockCarpentersDoor.type.length), + toggle(Hinge::getHinge, Click.MANUAL)), + new BlockSettings( + BlockCarpentersHatch.class, + cycle(Hatch::getType, Hatch.TYPE_PANEL + 1), + toggle(Hatch::getRigidity, Click.SNEAK_RIGHT), + toggle(Hatch::getDir, Click.MANUAL)), + new BlockSettings(BlockCarpentersLadder.class, cycle(LADDER::getType, BlockCarpentersLadder.type.length)), + new BlockSettings(BlockCarpentersTorch.class, cycle(TORCH::getType, BlockCarpentersTorch.type.length)), + new BlockSettings(BlockCarpentersBed.class, decoration("bed")), + new BlockSettings(BlockCarpentersFlowerPot.class, decoration("flowerpot")), + new BlockSettings( + BlockCarpentersDaylightSensor.class, + cycle(SENSOR::getSensitivity, 3), + toggle(SENSOR::getPolarity, Click.MANUAL)), + new BlockSettings( + BlockCarpentersPressurePlate.class, + cycle(PRESSURE_PLATE::getTriggerEntity, 4), + toggle(PRESSURE_PLATE::getPolarity, Click.MANUAL)), + new BlockSettings(BlockCarpentersButton.class, toggle(BUTTON::getPolarity, Click.MANUAL)), + new BlockSettings(BlockCarpentersLever.class, toggle(LEVER::getPolarity, Click.MANUAL)), + new BlockSettings(BlockCarpentersCollapsibleBlock.class, toggle(TEBase::getData, Click.MANUAL)), + // An unlock click also enables insertion and extraction. Only compare safe access settings for preview. + new BlockSettings( + BlockCarpentersSafe.class, + toggle(Safe::isLocked, Click.MANUAL), + toggle(Safe::getAutoPerm, Click.MANUAL)) }; + + private CarpentersHammerSupport() {} + + static boolean matchesSettings(Block block, TEBase expected, TEBase actual) { + if (block instanceof BlockCarpentersTorch && TORCH.getDirection(actual) != TORCH.getDirection(expected)) { + return false; + } + if (block instanceof BlockCarpentersLadder && LADDER.getDirection(actual) != LADDER.getDirection(expected)) { + return false; + } + return settingsFor(block).findClick(expected, actual) == null; + } + + public static ItemStack findHammer(ItemStack[] inventory, Predicate available) { + for (ItemStack stack : inventory) { + if (stack != null && stack.stackSize > 0 + && stack.getItem() instanceof ICarpentersHammer + && available.test(stack)) { + return stack; + } + } + if (ItemRegistry.itemCarpentersHammer != null) { + final ItemStack hammer = new ItemStack(ItemRegistry.itemCarpentersHammer); + if (available.test(hammer)) { + return hammer; + } + } + return null; + } + + public static boolean canUseHammer(EntityPlayer player, World world) { + final ItemStack stack = player.getHeldItem(); + return stack != null && stack.stackSize > 0 + && stack.getItem() instanceof ICarpentersHammer hammer + && hammer.canUseHammer(world, player); + } + + public static Adjustment findAdjustment(Block block, SchematicWorld schematic, TileEntity target, TileEntity placed, + EntityPlayer player, double reach) { + if (!(target instanceof TEBase expected) || !(placed instanceof TEBase actual)) { + return null; + } + + final BlockSettings settings = settingsFor(block); + if (CarpentersBlocksSupport.isCollapsible(block)) { + return findCollapsibleAdjustment(block, schematic, expected, actual, player, Math.min(5, reach), settings); + } + Click click = settings.findClick(expected, actual); + ForgeDirection face = ForgeDirection.UP; + if (block instanceof BlockCarpentersBlock && expected.getData() != actual.getData() + && validIndex(expected.getData(), Slab.SLAB_Z_POS + 1) + && validIndex(actual.getData(), Slab.SLAB_Z_POS + 1)) { + // A second click shapes a different half only after the first restores the full cube. + face = SLAB.isFullCube(actual) ? SLAB.getDirection(expected) + .getOpposite() : ForgeDirection.UP; + click = Click.RIGHT; + } else if (block instanceof BlockCarpentersStairs) { + click = shapeClick( + expected.getData(), + actual.getData(), + Stairs.stairsList.length, + CarpentersHammerSupport::nextStairShape); + } else if (block instanceof BlockCarpentersSlope) { + click = canReshapeSlope(expected.getData(), actual.getData()) ? Click.RIGHT : null; + } + if (click == null || click == Click.MANUAL) { + return null; + } + + final Collection affected = affectedBlocks(block, actual, expected, click); + if (affected.isEmpty()) { + return null; + } + for (TEBase piece : affected) { + final int x = piece.xCoord - schematic.position.x; + final int y = piece.yCoord - schematic.position.y; + final int z = piece.zCoord - schematic.position.z; + if (schematic.getBlockIncludingHiddenLayers(x, y, z) != block + || !(schematic.getTileEntity(x, y, z) instanceof TEBase saved) + || settings.findClick(expected, saved) != null) { + return null; + } + } + return new Adjustment(click, face.ordinal(), affected, block, actual, settings, null); + } + + private static Adjustment findCollapsibleAdjustment(Block block, SchematicWorld schematic, TEBase expected, + TEBase actual, EntityPlayer player, double reach, BlockSettings settings) { + if (CarpentersBlocksSupport.getCollapsibleDirection(expected) + != CarpentersBlocksSupport.getCollapsibleDirection(actual)) { + return null; + } + final boolean positive = Collapsible.INSTANCE.isPositive(actual); + for (int quad = 0; quad < 4; quad++) { + final int goal = Collapsible.getQuadDepth(expected, quad); + final int depth = Collapsible.getQuadDepth(actual, quad); + if (depth == goal) { + continue; + } + final int nextDepth = depth + Integer.signum(goal - depth); + final Collection affected = collapsibleNeighbors(block, schematic, actual, quad, goal, nextDepth); + if (affected.isEmpty()) { + continue; + } + final CornerHit hit = findCornerHit(actual, player, reach, quad, nextDepth); + if (hit != null) { + final Click click = (goal > depth) == positive ? Click.RIGHT : Click.LEFT; + return new Adjustment(click, hit.hit.sideHit, affected, block, actual, settings, hit); + } + } + return null; + } + + private static Collection collapsibleNeighbors(Block block, SchematicWorld schematic, TEBase actual, + int quad, int goal, int nextDepth) { + final World world = actual.getWorldObj(); + final Collection affected = new ArrayList<>(); + affected.add(actual); + // Carpenter's smooths this corner into the three neighbors that share it. + for (int neighbor = 1; neighbor < 4; neighbor++) { + final int x = actual.xCoord + ((neighbor & 2) == 0 ? 0 : (quad & 2) == 0 ? -1 : 1); + final int y = actual.yCoord; + final int z = actual.zCoord + ((neighbor & 1) == 0 ? 0 : (quad & 1) == 0 ? -1 : 1); + final int neighborQuad = quad ^ neighbor; + if (world.getBlock(x, y, z) != block || !(world.getTileEntity(x, y, z) instanceof TEBase other) + || !Collapsible.INSTANCE.match(actual, other) + || Collapsible.getQuadDepth(other, neighborQuad) == nextDepth) { + continue; + } + final int sx = x - schematic.position.x; + final int sy = y - schematic.position.y; + final int sz = z - schematic.position.z; + if (schematic.getBlockIncludingHiddenLayers(sx, sy, sz) != block + || !(schematic.getTileEntity(sx, sy, sz) instanceof TEBase saved) + || !Collapsible.INSTANCE.match(other, saved) + || Collapsible.getQuadDepth(saved, neighborQuad) != goal) { + return Collections.emptyList(); + } + affected.add(other); + } + return affected; + } + + private static CornerHit findCornerHit(TEBase tile, EntityPlayer player, double reach, int quad, int nextDepth) { + final World world = tile.getWorldObj(); + final float[] bounds = CollapsibleUtil.genBounds(tile, quad); + // Carpenter's gets the quadrant from a fresh server-side trace of the player's normal click. + final Vec3 eye = Vec3.createVectorHelper(player.posX, player.boundingBox.minY + 1.62F, player.posZ); + for (double u : CORNER_SAMPLES) { + for (double v : CORNER_SAMPLES) { + for (double h : CORNER_HEIGHTS) { + final double dx = tile.xCoord + bounds[0] + (bounds[3] - bounds[0]) * u - eye.xCoord; + final double dy = tile.yCoord + bounds[1] + (bounds[4] - bounds[1]) * h - eye.yCoord; + final double dz = tile.zCoord + bounds[2] + (bounds[5] - bounds[2]) * v - eye.zCoord; + final double distance = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (distance == 0 || distance > reach) { + continue; + } + final double scale = reach / distance; + final MovingObjectPosition hit = world + .rayTraceBlocks(eye.addVector(0, 0, 0), eye.addVector(dx * scale, dy * scale, dz * scale)); + if (hit != null && hit.blockX == tile.xCoord + && hit.blockY == tile.yCoord + && hit.blockZ == tile.zCoord + && Collapsible.getQuad(hit.hitVec.xCoord - tile.xCoord, hit.hitVec.zCoord - tile.zCoord) + == quad) { + final float yaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); + final float pitch = (float) -Math.toDegrees(Math.atan2(dy, Math.hypot(dx, dz))); + return new CornerHit(hit, yaw, pitch, quad, nextDepth); + } + } + } + } + return null; + } + + private static Collection affectedBlocks(Block block, TEBase actual, TEBase expected, Click click) { + final World world = actual.getWorldObj(); + if (CarpentersBlocksSupport.isGarageDoor(block)) { + final GarageDoor door = GarageDoor.INSTANCE; + if (door.getDirection(actual) != door.getDirection(expected) || door.getDirection(actual) + .ordinal() < 2 || door.getDirection(actual) == ForgeDirection.UNKNOWN || !door.isVisible(actual)) { + return Collections.emptyList(); + } + TEBase activation = actual; + if (door.isOpen(actual)) { + // Carpenter's Blocks redirects both right-click paths to the bottom of an open door. + activation = door.getBottommost(world, actual.xCoord, actual.yCoord, actual.zCoord); + if (activation == null || door.getDirection(activation) != door.getDirection(actual) + || (click == Click.RIGHT ? door.getType(activation) != door.getType(actual) + : door.getRigidity(activation) != door.getRigidity(actual))) { + return Collections.emptyList(); + } + } + final Collection pieces = door.getBlocks(activation, block); + // A capped client search can omit panels the server will change. + return pieces.size() > FeatureRegistry.multiBlockSizeLimit || !pieces.contains(actual) + ? Collections.emptyList() + : pieces; + } + if (block instanceof BlockCarpentersBed) { + final TEBase other = Bed.getOppositeTE(actual); + return other == null ? Collections.emptyList() : Arrays.asList(actual, other); + } + if (block instanceof BlockCarpentersFlowerPot && actual.hasAttribute(TEBase.ATTR_COVER[6])) { + // Turning the pot's design drops its existing base cover. + return Collections.emptyList(); + } + if (block instanceof BlockCarpentersDoor) { + final int otherY = actual.yCoord + (Hinge.getPiece(actual) == Hinge.PIECE_TOP ? -1 : 1); + if (world.getBlock(actual.xCoord, otherY, actual.zCoord) == block + && world.getTileEntity(actual.xCoord, otherY, actual.zCoord) instanceof TEBase other) { + return Arrays.asList(actual, other); + } + return Collections.emptyList(); + } + return Collections.singletonList(actual); + } + + private static BlockSettings settingsFor(Block block) { + for (BlockSettings settings : BLOCK_SETTINGS) { + if (settings.blockType.isInstance(block)) { + return settings; + } + } + return NO_SETTINGS; + } + + private static Setting toggle(Function read, Click click) { + return new Setting<>(read, (expected, actual) -> expected.equals(actual) ? null : click); + } + + private static Setting cycle(Function read, int variants) { + return new Setting<>(read, (expected, actual) -> cycle(expected, actual, variants)); + } + + private static Setting decoration(String designType) { + return new Setting<>(TEBase::getDesign, (expected, actual) -> { + if (expected.equals(actual)) { + return null; + } + return expected.isEmpty() ? Click.SNEAK_RIGHT + : DesignHandler.getListForType(designType) + .contains(expected) ? Click.RIGHT : null; + }); + } + + private static Click fenceClick(int expected, int actual) { + final Click type = cycle(expected, actual, Barrier.TYPE_WALL + 1); + return type != null && expected <= Barrier.TYPE_VANILLA_X3 && actual <= Barrier.TYPE_VANILLA_X3 + ? Click.SNEAK_RIGHT + : type; + } + + private static Click cycle(int expected, int actual, int variants) { + return toggle( + expected != actual && validIndex(expected, variants) && validIndex(actual, variants), + Click.RIGHT); + } + + private static Click toggle(boolean different, Click click) { + return different ? click : null; + } + + private static boolean validIndex(int value, int size) { + return value >= 0 && value < size; + } + + private static int nextStairShape(int id) { + return switch (id >> 2) { + case 0 -> id + 8; + case 1, 3 -> id + 12; + case 2, 4, 6 -> id - 4; + case 5 -> Stairs.ID_NORMAL_SE; + default -> id; + }; + } + + static boolean canReshapeStair(int expected, int actual) { + return shapeClick(expected, actual, Stairs.stairsList.length, CarpentersHammerSupport::nextStairShape) != null; + } + + static boolean canReshapeSlope(int expected, int actual) { + return shapeClick(expected, actual, Slope.ID_PRISM_WEDGE_POS_E + 1, id -> { + final Slope slope = Slope.getSlopeById(id); + return slope.slopeType.getNextSlopeType(slope).slopeID; + }) != null; + } + + private static Click shapeClick(int expected, int actual, int variants, IntUnaryOperator reshape) { + if (expected == actual || !validIndex(expected, variants) || !validIndex(actual, variants)) { + return null; + } + int next = actual; + for (int step = 0; step < variants; step++) { + next = reshape.applyAsInt(next); + if (next == expected) { + return Click.RIGHT; + } + if (next == actual) { + break; + } + } + return null; + } + + private static final class Setting { + + private final Function read; + private final BiFunction chooseClick; + + private Setting(Function read, BiFunction chooseClick) { + this.read = read; + this.chooseClick = chooseClick; + } + + private Click findClick(TEBase expected, TEBase actual) { + return this.chooseClick.apply(this.read.apply(expected), this.read.apply(actual)); + } + } + + private static final class BlockSettings { + + private final Class blockType; + private final Setting[] settings; + + private BlockSettings(Class blockType, Setting... settings) { + this.blockType = blockType; + this.settings = settings; + } + + private Click findClick(TEBase expected, TEBase actual) { + for (Setting setting : this.settings) { + final Click click = setting.findClick(expected, actual); + if (click != null) { + return click; + } + } + return null; + } + + private boolean usesEntireDataValue() { + // Shape IDs and barriers retain their existing raw-data acknowledgment. + return this.settings.length == 0 || this.blockType == BlockCarpentersBarrier.class; + } + + private Object[] snapshot(TEBase tile) { + if (usesEntireDataValue()) { + return new Object[] { tile.getData() }; + } + final Object[] values = new Object[this.settings.length]; + for (int i = 0; i < values.length; i++) { + values[i] = this.settings[i].read.apply(tile); + } + return values; + } + + private boolean matches(TEBase tile, Object[] values) { + if (usesEntireDataValue()) { + return values[0].equals(tile.getData()); + } + for (int i = 0; i < values.length; i++) { + if (!values[i].equals(this.settings[i].read.apply(tile))) { + return false; + } + } + return true; + } + } + + public enum Click { + MANUAL, + LEFT, + RIGHT, + SNEAK_RIGHT + } + + public static final class CornerHit { + + public final MovingObjectPosition hit; + public final float yaw; + public final float pitch; + private final int quad; + private final int nextDepth; + + private CornerHit(MovingObjectPosition hit, float yaw, float pitch, int quad, int nextDepth) { + this.hit = hit; + this.yaw = yaw; + this.pitch = pitch; + this.quad = quad; + this.nextDepth = nextDepth; + } + + private boolean matches(TEBase clicked, TEBase actual) { + final int quad = this.quad ^ (actual.xCoord == clicked.xCoord ? 0 : 2) + ^ (actual.zCoord == clicked.zCoord ? 0 : 1); + return Collapsible.getQuadDepth(actual, quad) == this.nextDepth; + } + } + + public static final class Adjustment { + + public final Click click; + public final int face; + public final Collection affected; + public final CornerHit corner; + + private final Block block; + private final TEBase clicked; + private final BlockSettings settings; + private final Object[] previousState; + + private Adjustment(Click click, int face, Collection affected, Block block, TEBase clicked, + BlockSettings settings, CornerHit corner) { + this.click = click; + this.face = face; + this.affected = affected; + this.block = block; + this.clicked = clicked; + this.settings = settings; + this.previousState = settings.snapshot(clicked); + this.corner = corner; + } + + public boolean isConfirmed(World world) { + if (!(world.getTileEntity( + this.clicked.xCoord, + this.clicked.yCoord, + this.clicked.zCoord) instanceof TEBase current)) { + return false; + } + if (this.settings.matches(current, this.previousState)) { + return false; + } + final Object[] state = this.settings.snapshot(current); + for (TileEntity piece : this.affected) { + if (world.getBlock(piece.xCoord, piece.yCoord, piece.zCoord) != this.block + || !(world.getTileEntity(piece.xCoord, piece.yCoord, piece.zCoord) instanceof TEBase updated) + || !(this.corner == null ? this.settings.matches(updated, state) + : this.corner.matches(this.clicked, updated))) { + return false; + } + } + return true; + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/CookingForBlockheadsSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/CookingForBlockheadsSupport.java new file mode 100644 index 00000000..d7e48888 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/CookingForBlockheadsSupport.java @@ -0,0 +1,77 @@ +package com.github.lunatrius.schematica.client.compat; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.function.BiConsumer; + +import net.blay09.mods.cookingforblockheads.tile.BaseKitchenTileWithInventory; +import net.blay09.mods.cookingforblockheads.tile.TileCookingTable; +import net.blay09.mods.cookingforblockheads.tile.TileFridge; +import net.blay09.mods.cookingforblockheads.tile.TileSink; +import net.blay09.mods.cookingforblockheads.utils.DyeUtils; +import net.minecraft.block.Block; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; + +import com.github.lunatrius.schematica.client.world.SchematicWorld; +import com.github.lunatrius.schematica.reference.Reference; + +public final class CookingForBlockheadsSupport { + + public static final boolean SUPPORTS_DYE_SUBSTITUTES = supportsDyeSubstitutes(); + + private CookingForBlockheadsSupport() {} + + public static int getDyeDamage(ItemStack stack) { + return DyeUtils.rawDyeDamageFromStack(stack); + } + + public static void addDyeRequirement(SchematicWorld schematic, int x, int y, int z, World world, int wx, int wy, + int wz, BiConsumer add) { + final TileEntity tile = schematic.getTileEntity(x, y, z); + final int color = getColor(tile); + if (color < 0 || color > 15) { + return; + } + final Block block = schematic.getBlock(x, y, z); + final boolean pairFridges = tile instanceof TileFridge && !schematic.isRenderingLayer; + if (pairFridges && colorAt(schematic, block, x, y - 1, z) == color) { + return; + } + final boolean hasUpperFridge = pairFridges && colorAt(schematic, block, x, y + 1, z) == color; + final int currentColor = colorAt(world, block, wx, wy, wz); + final int upperColor = hasUpperFridge ? colorAt(world, block, wx, wy + 1, wz) : -1; + if (color == 0 && currentColor <= 0 && upperColor <= 0) { + return; + } + add.accept( + new ItemStack(Items.dye, 1, 15 - color), + currentColor == color && (!hasUpperFridge || upperColor == color)); + } + + private static int colorAt(World world, Block block, int x, int y, int z) { + return world.getBlock(x, y, z) == block ? getColor(world.getTileEntity(x, y, z)) : -1; + } + + private static int getColor(TileEntity tile) { + if (tile instanceof BaseKitchenTileWithInventory kitchen) { + return kitchen.getColor(); + } + if (tile instanceof TileCookingTable table) { + return table.getColor(); + } + return tile instanceof TileSink sink ? sink.getColor() : -1; + } + + private static boolean supportsDyeSubstitutes() { + try { + final Method method = DyeUtils.class.getMethod("rawDyeDamageFromStack", ItemStack.class); + return method.getReturnType() == int.class && Modifier.isStatic(method.getModifiers()); + } catch (ReflectiveOperationException | LinkageError e) { + Reference.logger.debug("Cooking for Blockheads dye substitutes are unavailable", e); + return false; + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/EnderIOSlabSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/EnderIOSlabSupport.java new file mode 100644 index 00000000..4cb27038 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/EnderIOSlabSupport.java @@ -0,0 +1,40 @@ +package com.github.lunatrius.schematica.client.compat; + +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; + +import crazypants.enderio.machine.painter.BlockPaintedSlab; +import crazypants.enderio.machine.painter.PainterUtil; +import crazypants.enderio.machine.painter.TileEntityPaintedBlock; + +public final class EnderIOSlabSupport { + + private EnderIOSlabSupport() {} + + public static boolean isPaintedSlab(Block block) { + return block instanceof BlockPaintedSlab; + } + + public static ItemStack getItem(TileEntity tile) { + if (tile instanceof TileEntityPaintedBlock painted) { + return BlockPaintedSlab + .createItemStackForSourceBlock(painted.getSourceBlock(), painted.getSourceBlockMetadata()); + } + return null; + } + + public static boolean itemsMatch(ItemStack actual, ItemStack expected) { + return PainterUtil.isMetadataEquivelent(actual, expected); + } + + public static String getPaintName(ItemStack stack) { + return PainterUtil.getTooltTipText(stack); + } + + public static boolean matchesPaint(TileEntity actual, TileEntity expected) { + return actual instanceof TileEntityPaintedBlock placed && expected instanceof TileEntityPaintedBlock saved + && placed.getSourceBlock() == saved.getSourceBlock() + && placed.getSourceBlockMetadata() == saved.getSourceBlockMetadata(); + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java new file mode 100644 index 00000000..1c8a546a --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/compat/MicroblockSupport.java @@ -0,0 +1,625 @@ +package com.github.lunatrius.schematica.client.compat; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiConsumer; +import java.util.function.Predicate; +import java.util.function.Supplier; + +import net.minecraft.block.Block; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.MathHelper; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import com.github.lunatrius.schematica.reference.Mods; + +import codechicken.lib.raytracer.IndexedCuboid6; +import codechicken.lib.raytracer.RayTracer; +import codechicken.lib.render.CCRenderState; +import codechicken.lib.vec.Cuboid6; +import codechicken.lib.vec.Vector3; +import codechicken.microblock.CommonMicroClass; +import codechicken.microblock.ExecutablePlacement; +import codechicken.microblock.ExpandingPlacement; +import codechicken.microblock.ItemMicroPart; +import codechicken.microblock.Microblock; +import codechicken.microblock.MicroblockPlacement; +import codechicken.multipart.BlockMultipart; +import codechicken.multipart.TMultiPart; +import codechicken.multipart.TSlottedPart; +import codechicken.multipart.TileMultipart; +import scala.collection.Iterator; + +public final class MicroblockSupport { + + private static final double[] FACE_SAMPLES = { 0.5, 0.125, 0.875, 0.03125, 0.96875 }; + private static final double SERVER_SNEAK_EYE_OFFSET = 0.08; + public static final String NBT_MAT = "mat"; + + private MicroblockSupport() {} + + public static boolean isMultipartBlock(Block block) { + return block instanceof BlockMultipart; + } + + public static boolean isMicroblockItem(ItemStack stack) { + return stack.getItem() instanceof ItemMicroPart; + } + + public static boolean itemsMatch(ItemStack stack, ItemStack target) { + return stack.isItemEqual(target) && stack.hasTagCompound() + && target.hasTagCompound() + && stack.getTagCompound() + .getString(NBT_MAT) + .equals( + target.getTagCompound() + .getString(NBT_MAT)); + } + + public static boolean hasMicroblocks(TileEntity tile) { + return !getParts(tile).isEmpty(); + } + + public static void renderMissingParts(IBlockAccess schematic, TileEntity placed, int x, int y, int z, int pass) { + if (!(placed instanceof TileMultipart)) { + return; + } + + final List missing = getParts(schematic.getTileEntity(x, y, z)); + if (missing.isEmpty()) { + return; + } + final List actual = getParts(placed); + missing.removeIf(part -> removeMatch(actual, part)); + if (missing.isEmpty()) { + return; + } + + final CCRenderState state = CCRenderState.instance(); + state.resetInstance(); + state.lightMatrix.locate(schematic, x, y, z); + try { + final Vector3 position = new Vector3(x, y, z); + for (Microblock part : missing) { + part.renderStatic(position, pass); + } + } finally { + state.lightMatrix.access = null; + } + } + + public static boolean addMaterials(TileEntity schematic, TileEntity world, BiConsumer add) { + final List expected = getParts(schematic); + final List otherParts = getOtherParts(schematic); + if (expected.isEmpty() && otherParts.isEmpty()) { + return false; + } + + final List unmatchedOtherParts = getOtherParts(world); + for (TMultiPart part : otherParts) { + final boolean placed = removeOtherPartMatch(unmatchedOtherParts, part); + for (ItemStack stack : part.getDrops()) { + add.accept(stack, placed); + } + } + + final List unmatched = getParts(world); + for (Microblock part : expected) { + if (removeMatch(unmatched, part)) { + for (ItemStack stack : part.getDrops()) { + add.accept(stack, true); + } + continue; + } + final Microblock partial = findPartialMatch(unmatched, part); + if (partial == null) { + for (ItemStack stack : part.getDrops()) { + add.accept(stack, false); + } + continue; + } + unmatched.remove(partial); + for (ItemStack stack : partial.getDrops()) { + add.accept(stack, true); + } + int remaining = part.getSize() - partial.getSize(); + while (remaining > 0) { + final int size = Integer.highestOneBit(remaining); + add.accept(ItemMicroPart.create(part.itemClassID() << 8 | size, part.getMaterial()), false); + remaining -= size; + } + } + return true; + } + + public static Click findPlacement(EntityClientPlayerMP player, TileEntity schematic, int x, int y, int z, + Predicate hasItem) { + final List expected = getParts(schematic); + final List unmatched = getParts(player.worldObj.getTileEntity(x, y, z)); + expected.removeIf(part -> removeMatch(unmatched, part)); + + final List additions = new ArrayList<>(); + final List expansions = new ArrayList<>(); + for (Microblock part : expected) { + final Microblock partial = findPartialMatch(unmatched, part); + final int existingSize = partial == null ? 0 : partial.getSize(); + final List requests = existingSize == 0 ? additions : expansions; + for (int size = Integer.highestOneBit(part.getSize() - existingSize); size > 0; size >>= 1) { + final ItemStack item = ItemMicroPart.create(part.itemClassID() << 8 | size, part.getMaterial()); + if (hasItem.test(item)) { + requests.add(new PlacementRequest(part, item, existingSize + size)); + } + } + } + if (additions.isEmpty() && expansions.isEmpty()) { + return null; + } + + final float yaw = player.rotationYaw; + final float pitch = player.rotationPitch; + final boolean sneaking = player.movementInput.sneak; + try { + // Additions sneak to bypass block activation. FMP expands an existing part with a normal click. + // Finish an exposed partial part before adding parts that could obstruct it. + final Click expansion = findClick(player, x, y, z, expansions, false, true, block -> true); + if (expansion != null) { + return expansion; + } + player.rotationYaw = yaw; + player.rotationPitch = pitch; + final Click addition = findClick( + player, + x, + y, + z, + additions, + true, + false, + block -> !Mods.CARPENTERS_BLOCKS || !CarpentersBlocksSupport.isCoverable(block)); + if (addition != null || !Mods.CARPENTERS_BLOCKS) { + return addition; + } + player.rotationYaw = yaw; + player.rotationPitch = pitch; + // Carpenter's intercepts sneak-clicks with microblocks before Forge Multipart can use them. + return findClick( + player, + x, + y, + z, + additions, + false, + false, + CarpentersBlocksSupport::passesThroughMicroblockClick); + } finally { + player.rotationYaw = yaw; + player.rotationPitch = pitch; + player.movementInput.sneak = sneaking; + } + } + + private static Click findClick(EntityClientPlayerMP player, int x, int y, int z, List requests, + boolean sneaking, boolean expanding, Predicate canClick) { + if (requests.isEmpty()) { + return null; + } + player.movementInput.sneak = sneaking; + final Vec3 eye = RayTracer.getStartVec(player); + // CodeChickenLib uses the server's standing eye height above the player's feet, then adjusts for sneaking. + final double serverEyeOffset = player.boundingBox.minY + 1.62F + - player.posY + - (sneaking ? SERVER_SNEAK_EYE_OFFSET : 0); + return new PlacementSearch(player, x, y, z, requests, eye, serverEyeOffset, expanding, canClick).find(); + } + + private static final class PlacementSearch { + + private final EntityClientPlayerMP player; + private final World world; + private final int x, y, z; + private final List requests; + private final Vec3 eye; + private final Vec3 serverEye; + private final double reach; + private final double aimOffsetY; + private final boolean expanding; + private final Predicate canClick; + + private PlacementSearch(EntityClientPlayerMP player, int x, int y, int z, List requests, + Vec3 eye, double serverEyeOffset, boolean expanding, Predicate canClick) { + this.player = player; + this.world = player.worldObj; + this.x = x; + this.y = y; + this.z = z; + this.requests = requests; + this.eye = eye; + this.serverEye = eye.addVector(0, serverEyeOffset, 0); + this.reach = RayTracer.getBlockReachDistance(player); + this.aimOffsetY = -serverEyeOffset / 2; + this.expanding = expanding; + this.canClick = canClick; + } + + private Click find() { + final Vec3 look = player.getLook(1); + final MovingObjectPosition visible = traceWithoutChangingBounds( + world, + eye, + eye.addVector(look.xCoord * reach, look.yCoord * reach, look.zCoord * reach)); + if (visible != null + && Math.abs(visible.blockX - x) + Math.abs(visible.blockY - y) + Math.abs(visible.blockZ - z) + <= (expanding ? 0 : 1)) { + final Block block = world.getBlock(visible.blockX, visible.blockY, visible.blockZ); + final Click click = withSavedBlockBounds( + block, + () -> tryAim(visible.blockX, visible.blockY, visible.blockZ, visible.sideHit)); + if (click != null) { + return click; + } + } + + final Click internal = tryBlock(x, y, z, ForgeDirection.UNKNOWN); + if (internal != null || expanding) { + return internal; + } + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + final Click external = tryBlock( + x + side.offsetX, + y + side.offsetY, + z + side.offsetZ, + side.getOpposite()); + if (external != null) { + return external; + } + } + return null; + } + + private Click tryBlock(int bx, int by, int bz, ForgeDirection face) { + final Block block = world.getBlock(bx, by, bz); + if (world.isAirBlock(bx, by, bz) || !canClick.test(block)) { + return null; + } + return withSavedBlockBounds(block, () -> tryBlockFaces(block, bx, by, bz, face)); + } + + private Click tryBlockFaces(Block block, int bx, int by, int bz, ForgeDirection face) { + if (world.getTileEntity(bx, by, bz) instanceof TileMultipart multipart) { + final Iterator parts = multipart.partList() + .iterator(); + final Vector3 origin = new Vector3(bx, by, bz); + while (parts.hasNext()) { + for (IndexedCuboid6 box : parts.next() + .getSubParts()) { + final Click click = tryBounds( + bx, + by, + bz, + face, + box.copy() + .add(origin)); + if (click != null) { + return click; + } + } + } + return null; + } + + block.setBlockBoundsBasedOnState(world, bx, by, bz); + final AxisAlignedBB selected = block.getSelectedBoundingBoxFromPool(world, bx, by, bz); + final Cuboid6 bounds = selected == null ? new Cuboid6(bx, by, bz, bx + 1, by + 1, bz + 1) + : new Cuboid6(selected); + return tryBounds(bx, by, bz, face, bounds); + } + + private Click tryBounds(int bx, int by, int bz, ForgeDirection face, Cuboid6 bounds) { + if (face != ForgeDirection.UNKNOWN) { + return tryFace(bx, by, bz, face, bounds); + } + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + final Click click = tryFace(bx, by, bz, side, bounds); + if (click != null) { + return click; + } + } + return null; + } + + private Click tryFace(int bx, int by, int bz, ForgeDirection face, Cuboid6 bounds) { + final double plane = bounds.getSide(face.ordinal()); + final double distance = face.offsetX != 0 ? (eye.xCoord - plane) * face.offsetX + : face.offsetY != 0 ? (eye.yCoord - plane) * face.offsetY : (eye.zCoord - plane) * face.offsetZ; + if (distance <= 0 || distance > reach) { + return null; + } + + // Sample the actual click surface, including the narrow borders used by the placement grid. + for (double u : FACE_SAMPLES) { + for (double v : FACE_SAMPLES) { + final double hx = face.offsetX == 0 ? bounds.min.x + (bounds.max.x - bounds.min.x) * u : plane; + final double hy = face.offsetY == 0 + ? bounds.min.y + (bounds.max.y - bounds.min.y) * (face.offsetX == 0 ? v : u) + : plane; + final double hz = face.offsetZ == 0 ? bounds.min.z + (bounds.max.z - bounds.min.z) * v : plane; + final double aimY = hy + aimOffsetY; + if (eye.squareDistanceTo(hx, aimY, hz) > reach * reach) { + continue; + } + aimAt(player, eye, hx, aimY, hz); + final Click click = tryAim(bx, by, bz, face.ordinal()); + if (click != null) { + return click; + } + } + } + return null; + } + + private Click tryAim(int bx, int by, int bz, int face) { + final Vec3 look = player.getLook(1); + final double dx = look.xCoord * reach; + final double dy = look.yCoord * reach; + final double dz = look.zCoord * reach; + final Vec3 end = eye.addVector(dx, dy, dz); + final Block block = world.getBlock(bx, by, bz); + if (!canClick.test(block)) { + return null; + } + final MovingObjectPosition hit = block.collisionRayTrace(world, bx, by, bz, eye, end); + if (hit == null || hit.sideHit != face) { + return null; + } + + for (PlacementRequest request : requests) { + final ExecutablePlacement placement = predictPlacement(player, x, y, z, request, hit, expanding); + if (placement == null) { + continue; + } + final MovingObjectPosition serverHit = block + .collisionRayTrace(world, bx, by, bz, serverEye, serverEye.addVector(dx, dy, dz)); + if (serverHit == null || serverHit.sideHit != face + || predictPlacement(player, x, y, z, request, serverHit, expanding) == null) { + continue; + } + final MovingObjectPosition visible = traceWithoutChangingBounds(world, eye, end); + if (visible != null && visible.blockX == bx + && visible.blockY == by + && visible.blockZ == bz + && visible.sideHit == face) { + return new Click( + request.item, + hit, + player.rotationYaw, + player.rotationPitch, + player.isSneaking(), + placement.part()); + } + return null; + } + return null; + } + } + + private static MovingObjectPosition traceWithoutChangingBounds(World world, Vec3 origin, Vec3 end) { + final Vec3 start = origin.addVector(0, 0, 0); + final int endX = MathHelper.floor_double(end.xCoord); + final int endY = MathHelper.floor_double(end.yCoord); + final int endZ = MathHelper.floor_double(end.zCoord); + int x = MathHelper.floor_double(start.xCoord); + int y = MathHelper.floor_double(start.yCoord); + int z = MathHelper.floor_double(start.zCoord); + + // Match vanilla's voxel order, including its Z/Y/X tie order at grid boundaries. + for (int step = 0; step <= 201; step++) { + final Block block = world.getBlock(x, y, z); + if (block.canCollideCheck(world.getBlockMetadata(x, y, z), false)) { + final int bx = x; + final int by = y; + final int bz = z; + final MovingObjectPosition hit = withSavedBlockBounds( + block, + () -> block.collisionRayTrace(world, bx, by, bz, start, end)); + if (hit != null) { + return hit; + } + } + if (x == endX && y == endY && z == endZ) { + return null; + } + + final double boundaryX = x + (endX > x ? 1 : 0); + final double boundaryY = y + (endY > y ? 1 : 0); + final double boundaryZ = z + (endZ > z ? 1 : 0); + final double dx = end.xCoord - start.xCoord; + final double dy = end.yCoord - start.yCoord; + final double dz = end.zCoord - start.zCoord; + final double tx = x == endX ? Double.POSITIVE_INFINITY : (boundaryX - start.xCoord) / dx; + final double ty = y == endY ? Double.POSITIVE_INFINITY : (boundaryY - start.yCoord) / dy; + final double tz = z == endZ ? Double.POSITIVE_INFINITY : (boundaryZ - start.zCoord) / dz; + final boolean crossX = tx < ty && tx < tz; + final boolean crossY = !crossX && ty < tz; + final boolean crossZ = !crossX && !crossY; + final double t = crossX ? tx : crossY ? ty : tz; + start.xCoord = crossX ? boundaryX : start.xCoord + dx * t; + start.yCoord = crossY ? boundaryY : start.yCoord + dy * t; + start.zCoord = crossZ ? boundaryZ : start.zCoord + dz * t; + x = MathHelper.floor_double(start.xCoord) - (crossX && dx < 0 ? 1 : 0); + y = MathHelper.floor_double(start.yCoord) - (crossY && dy < 0 ? 1 : 0); + z = MathHelper.floor_double(start.zCoord) - (crossZ && dz < 0 ? 1 : 0); + } + return null; + } + + private static T withSavedBlockBounds(Block block, Supplier action) { + final double minX = block.minX; + final double minY = block.minY; + final double minZ = block.minZ; + final double maxX = block.maxX; + final double maxY = block.maxY; + final double maxZ = block.maxZ; + try { + return action.get(); + } finally { + block.minX = minX; + block.minY = minY; + block.minZ = minZ; + block.maxX = maxX; + block.maxY = maxY; + block.maxZ = maxZ; + } + } + + private static ExecutablePlacement predictPlacement(EntityClientPlayerMP player, int x, int y, int z, + PlacementRequest request, MovingObjectPosition hit, boolean expanding) { + final int damage = request.item.getItemDamage(); + final CommonMicroClass microClass = CommonMicroClass.getMicroClass(damage); + final ExecutablePlacement placement = new MicroblockPlacement( + player, + hit, + damage & 0xff, + request.part.getMaterial(), + !player.capabilities.isCreativeMode, + microClass.placementProperties()).apply(); + return placement != null && (placement instanceof ExpandingPlacement) == expanding + && placement.pos().x == x + && placement.pos().y == y + && placement.pos().z == z + && sameOrientation(placement.part(), request.part) + && placement.part() + .getSize() == request.resultSize ? placement : null; + } + + private static void aimAt(EntityClientPlayerMP player, Vec3 eye, double x, double y, double z) { + final double dx = x - eye.xCoord; + final double dy = y - eye.yCoord; + final double dz = z - eye.zCoord; + player.rotationYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); + player.rotationPitch = (float) -Math.toDegrees(Math.atan2(dy, Math.hypot(dx, dz))); + } + + public static boolean hasMissingOtherParts(TileEntity schematic, TileEntity world) { + final List unmatched = getOtherParts(world); + return getOtherParts(schematic).stream() + .anyMatch(part -> !removeOtherPartMatch(unmatched, part)); + } + + private static boolean removeOtherPartMatch(List placed, TMultiPart expected) { + for (int i = 0; i < placed.size(); i++) { + final TMultiPart actual = placed.get(i); + if (expected.getType() + .equals(actual.getType()) && slotMask(expected) == slotMask(actual)) { + placed.remove(i); + return true; + } + } + return false; + } + + private static int slotMask(TMultiPart part) { + return part instanceof TSlottedPart slotted ? slotted.getSlotMask() : 0; + } + + private static List getOtherParts(TileEntity tile) { + final List parts = getParts(tile, TMultiPart.class); + parts.removeIf(Microblock.class::isInstance); + return parts; + } + + private static List getParts(TileEntity tile) { + return getParts(tile, Microblock.class); + } + + private static List getParts(TileEntity tile, Class type) { + final List parts = new ArrayList<>(); + if (tile instanceof TileMultipart multipart) { + final Iterator iterator = multipart.partList() + .iterator(); + while (iterator.hasNext()) { + final TMultiPart part = iterator.next(); + if (type.isInstance(part)) { + parts.add(type.cast(part)); + } + } + } + return parts; + } + + private static boolean removeMatch(List parts, Microblock expected) { + for (int i = 0; i < parts.size(); i++) { + final Microblock part = parts.get(i); + if (part.getSize() == expected.getSize() && sameOrientation(part, expected)) { + parts.remove(i); + return true; + } + } + return false; + } + + private static boolean sameOrientation(Microblock part, Microblock expected) { + return part.getMaterial() == expected.getMaterial() && part.getShape() == expected.getShape() + && part.microClass() == expected.microClass(); + } + + private static Microblock findPartialMatch(List parts, Microblock expected) { + Microblock partial = null; + for (Microblock part : parts) { + if (sameOrientation(part, expected) && part.getSize() < expected.getSize() + && (partial == null || part.getSize() > partial.getSize())) { + partial = part; + } + } + return partial; + } + + private static final class PlacementRequest { + + private final Microblock part; + private final ItemStack item; + private final int resultSize; + + private PlacementRequest(Microblock part, ItemStack item, int resultSize) { + this.part = part; + this.item = item; + this.resultSize = resultSize; + } + } + + public static final class Click { + + public final ItemStack item; + public final MovingObjectPosition hit; + public final float yaw; + public final float pitch; + public final boolean sneaking; + + private final Microblock result; + + private Click(ItemStack item, MovingObjectPosition hit, float yaw, float pitch, boolean sneaking, + Microblock result) { + this.item = item; + this.hit = hit; + this.yaw = yaw; + this.pitch = pitch; + this.sneaking = sneaking; + this.result = result; + } + + public boolean isConfirmed(TileEntity tile) { + for (Microblock part : getParts(tile)) { + if (part.getSize() == result.getSize() && sameOrientation(part, result)) { + return true; + } + } + return false; + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/gui/GuiHelper.java b/src/main/java/com/github/lunatrius/schematica/client/gui/GuiHelper.java index b27d5808..b83a25e6 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/gui/GuiHelper.java +++ b/src/main/java/com/github/lunatrius/schematica/client/gui/GuiHelper.java @@ -22,7 +22,7 @@ public static void drawItemStack(TextureManager textureManager, FontRenderer fon if (itemStack != null && itemStack.getItem() != null) { GL11.glEnable(GL12.GL_RESCALE_NORMAL); RenderHelper.enableGUIStandardItemLighting(); - renderItem.renderItemIntoGUI(fontRenderer, textureManager, itemStack, x + 2, y + 2); + renderItem.renderItemAndEffectIntoGUI(fontRenderer, textureManager, itemStack, x + 2, y + 2); RenderHelper.disableStandardItemLighting(); GL11.glDisable(GL12.GL_RESCALE_NORMAL); } diff --git a/src/main/java/com/github/lunatrius/schematica/client/gui/control/GuiSchematicMaterials.java b/src/main/java/com/github/lunatrius/schematica/client/gui/control/GuiSchematicMaterials.java index 1f135b1b..95e44add 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/gui/control/GuiSchematicMaterials.java +++ b/src/main/java/com/github/lunatrius/schematica/client/gui/control/GuiSchematicMaterials.java @@ -128,7 +128,7 @@ private void dumpMaterialList(final List blockList) for (final BlockList.WrappedItemStack wrappedItemStack : blockList) { maxLengthName = Math.max( maxLengthName, - wrappedItemStack.getItemStackDisplayName() + wrappedItemStack.getExportDisplayName() .length()); maxSize = Math.max(maxSize, wrappedItemStack.total); } @@ -141,7 +141,7 @@ private void dumpMaterialList(final List blockList) final StringBuilder stringBuilder = new StringBuilder((maxLengthName + 1 + maxLengthSize) * blockList.size()); final Formatter formatter = new Formatter(stringBuilder); for (final BlockList.WrappedItemStack wrappedItemStack : blockList) { - formatter.format(formatName, wrappedItemStack.getItemStackDisplayName()); + formatter.format(formatName, wrappedItemStack.getExportDisplayName()); stringBuilder.append(" "); formatter.format(formatSize, wrappedItemStack.total); stringBuilder.append(System.lineSeparator()); diff --git a/src/main/java/com/github/lunatrius/schematica/client/gui/load/GuiSchematicLoadSlot.java b/src/main/java/com/github/lunatrius/schematica/client/gui/load/GuiSchematicLoadSlot.java index a51185fd..462bc81f 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/gui/load/GuiSchematicLoadSlot.java +++ b/src/main/java/com/github/lunatrius/schematica/client/gui/load/GuiSchematicLoadSlot.java @@ -4,6 +4,7 @@ import net.minecraft.client.gui.GuiSlot; import net.minecraft.client.renderer.Tessellator; +import com.github.lunatrius.schematica.FileFilterSchematic; import com.github.lunatrius.schematica.client.gui.GuiHelper; public class GuiSchematicLoadSlot extends GuiSlot { @@ -64,7 +65,7 @@ protected void drawSlot(int index, int x, int y, int par4, Tessellator tessellat if (schematic.isDirectory()) { schematicName += "/"; } else { - schematicName = schematicName.replaceAll("(?i)\\.schematic$", ""); + schematicName = FileFilterSchematic.stripExtension(schematicName); } GuiHelper diff --git a/src/main/java/com/github/lunatrius/schematica/client/gui/save/GuiSchematicSave.java b/src/main/java/com/github/lunatrius/schematica/client/gui/save/GuiSchematicSave.java index 2b4c513c..7af640de 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/gui/save/GuiSchematicSave.java +++ b/src/main/java/com/github/lunatrius/schematica/client/gui/save/GuiSchematicSave.java @@ -8,6 +8,7 @@ import com.github.lunatrius.core.client.gui.GuiNumericField; import com.github.lunatrius.core.client.gui.GuiScreenBase; import com.github.lunatrius.core.util.vector.Vector3i; +import com.github.lunatrius.schematica.FileFilterSchematic; import com.github.lunatrius.schematica.Schematica; import com.github.lunatrius.schematica.handler.ConfigurationHandler; import com.github.lunatrius.schematica.proxy.ClientProxy; @@ -168,12 +169,7 @@ protected void actionPerformed(GuiButton guiButton) { this.btnEnable.displayString = ClientProxy.isRenderingGuide ? this.strOn : this.strOff; this.btnSave.enabled = ClientProxy.isRenderingGuide; } else if (guiButton.id == this.btnSave.id) { - String path; - if (ConfigurationHandler.useSchematicplusFormat) { - path = this.tfFilename.getText() + ".schemplus"; - } else { - path = this.tfFilename.getText() + ".schematic"; - } + String path = this.tfFilename.getText() + FileFilterSchematic.EXTENSION_SCHEMATIC; if (Schematica.proxy.saveSchematic( this.mc.thePlayer, ConfigurationHandler.schematicDirectory, diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java new file mode 100644 index 00000000..8032f4c4 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/ArchitectureCraftPrinter.java @@ -0,0 +1,126 @@ +package com.github.lunatrius.schematica.client.printer; + +import java.util.Map; +import java.util.WeakHashMap; +import java.util.concurrent.TimeUnit; + +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.handler.ConfigurationHandler; + +final class ArchitectureCraftPrinter { + + private static final long TURN_ACK_TIMEOUT = TimeUnit.SECONDS.toNanos(5); + // An outstanding click belongs to the live tile, even when the schematic is refreshed. + private final Map pendingTurns = new WeakHashMap<>(); + + void beginPass(World world) { + final long now = System.nanoTime(); + this.pendingTurns.entrySet() + .removeIf(entry -> { + final TileEntity tile = entry.getKey(); + final PendingTurn pending = entry.getValue(); + return tile.getWorldObj() != world || !world.blockExists(tile.xCoord, tile.yCoord, tile.zCoord) + || world.getTileEntity(tile.xCoord, tile.yCoord, tile.zCoord) != tile + || ArchitectureCraftSupport.getTurn(tile) != pending.turn + || now - pending.sentAt >= TURN_ACK_TIMEOUT; + }); + } + + static boolean place(PrinterInteraction interaction, int x, int y, int z, TileEntity tile, ItemStack item) { + if (!interaction.canSelectItem(item)) { + return false; + } + final ForgeDirection[] supports = interaction.findSupports(x, y, z); + final boolean hasSupport = supports.length > 0; + if (!hasSupport && ConfigurationHandler.placeAdjacent) { + return false; + } + if (placeAgainstSupports(interaction, x, y, z, tile, item, supports, false)) { + return true; + } + return ArchitectureCraftSupport.isTurnableCapital(tile) + && interaction.canSelectItem(ArchitectureCraftSupport.getHammer()) + && placeAgainstSupports(interaction, x, y, z, tile, item, supports, true); + } + + boolean rotateCapital(PrinterInteraction interaction, TileEntity tile, int x, int y, int z) { + if (this.pendingTurns.containsKey(tile) || !interaction.selectItem(ArchitectureCraftSupport.getHammer())) { + return false; + } + final int previousTurn = ArchitectureCraftSupport.getTurn(tile); + // Native hammer prediction changes the tile even when the server denies the click. + final boolean sent = interaction.withSneaking( + false, + () -> interaction.useBlockOnServer( + interaction.player.getHeldItem(), + x, + y, + z, + ForgeDirection.NORTH.ordinal(), + Vec3.createVectorHelper(x + 0.5, y + 0.5, z))); + if (sent) { + // A turn is relative. Wait for a tile update before sending another click. + this.pendingTurns.put(tile, new PendingTurn(previousTurn, System.nanoTime())); + } + return sent; + } + + private static final class PendingTurn { + + private final int turn; + private final long sentAt; + + private PendingTurn(int turn, long sentAt) { + this.turn = turn; + this.sentAt = sentAt; + } + } + + private static boolean placeAgainstSupports(PrinterInteraction interaction, int x, int y, int z, TileEntity tile, + ItemStack item, ForgeDirection[] supports, boolean allowHammerTurn) { + final boolean hasSupport = supports.length > 0; + for (ForgeDirection support : hasSupport ? supports : ForgeDirection.VALID_DIRECTIONS) { + for (boolean sneaking : new boolean[] { true, false }) { + // A standing click on the support could activate it instead of placing the shape. + final boolean clickSupport = hasSupport && sneaking; + final int clickedX = x + (clickSupport ? support.offsetX : 0); + final int clickedY = y + (clickSupport ? support.offsetY : 0); + final int clickedZ = z + (clickSupport ? support.offsetZ : 0); + if (!PrinterInteraction + .canClickForPlacement(interaction.world.getBlock(clickedX, clickedY, clickedZ), item, sneaking)) { + continue; + } + final Vec3 hit = ArchitectureCraftSupport.findHit( + interaction.player, + interaction.world, + tile, + item, + x, + y, + z, + support, + sneaking, + allowHammerTurn); + if (hit != null) { + return interaction.selectItem(item) && interaction.withSneaking( + sneaking, + () -> interaction.place( + interaction.player.getHeldItem(), + clickedX, + clickedY, + clickedZ, + support.getOpposite() + .ordinal(), + clickSupport ? hit : hit.addVector(-support.offsetX, -support.offsetY, -support.offsetZ))); + } + } + } + return false; + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java new file mode 100644 index 00000000..2505b5b1 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/CarpentersPrinter.java @@ -0,0 +1,459 @@ +package com.github.lunatrius.schematica.client.printer; + +import java.lang.ref.WeakReference; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.BooleanSupplier; + +import net.minecraft.block.Block; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; +import net.minecraft.world.ChunkPosition; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; +import com.github.lunatrius.schematica.client.compat.CarpentersHammerSupport; +import com.github.lunatrius.schematica.client.world.SchematicWorld; +import com.github.lunatrius.schematica.handler.ConfigurationHandler; + +final class CarpentersPrinter { + + private static final float[] SHAPE_HIT_OFFSETS = { 0.5f, 0.125f, 0.875f, 0.25f, 0.75f }; + + private final Map pendingClicks = new HashMap<>(); + private final Set deferredGarageHosts = new HashSet<>(); + private WeakReference garageWorld = new WeakReference<>(null); + private PendingClick pendingGarageStock; + private ChunkPosition pendingGarageHost; + private long currentPass; + + void reset() { + this.pendingClicks.clear(); + this.deferredGarageHosts.clear(); + } + + void beginPass(World world) { + final long pass = ++this.currentPass; + this.pendingClicks.values() + .removeIf(click -> click.allowsNextClick(world, pass)); + if (this.garageWorld.get() != world) { + this.deferredGarageHosts.clear(); + this.garageWorld = new WeakReference<>(world); + } + if (this.pendingGarageStock != null && this.pendingGarageStock.allowsNextClick(world, pass)) { + if (this.pendingGarageStock.world.get() == world && pass >= this.pendingGarageStock.retryPass) { + // Let the current scan try the other garage hosts before retrying this one. + this.deferredGarageHosts.add(this.pendingGarageHost); + } + this.pendingGarageStock = null; + this.pendingGarageHost = null; + } + } + + void finishPass() { + if (this.pendingGarageStock == null) { + this.deferredGarageHosts.clear(); + } + } + + boolean isWaiting(int x, int y, int z) { + return !this.pendingClicks.isEmpty() && this.pendingClicks.containsKey(new ChunkPosition(x, y, z)); + } + + boolean configureBlock(PrinterInteraction interaction, SchematicWorld schematic, Block block, TileEntity target, + int x, int y, int z) { + final World world = interaction.world; + final TileEntity placed = world.getTileEntity(x, y, z); + if (!CarpentersBlocksSupport.canConfigure(placed, interaction.player)) { + return false; + } + final CarpentersHammerSupport.Adjustment adjustment = CarpentersHammerSupport + .findAdjustment(block, schematic, target, placed, interaction.player, interaction.blockReach()); + if (adjustment != null && adjustment.affected.stream() + .allMatch( + piece -> !isWaiting(piece.xCoord, piece.yCoord, piece.zCoord) + && CarpentersBlocksSupport.canConfigure(piece, interaction.player)) + && applyHammer(interaction, adjustment, x, y, z)) { + final PendingClick click = new PendingClick(world, this.currentPass, () -> adjustment.isConfirmed(world)); + for (TileEntity piece : adjustment.affected) { + this.pendingClicks.put(new ChunkPosition(piece.xCoord, piece.yCoord, piece.zCoord), click); + } + return true; + } + + final CarpentersBlocksSupport.Interaction attachment = CarpentersBlocksSupport + .findAttachment(block, target, placed, interaction.player, interaction::canSelectItem); + if (attachment == null || !interaction.selectItem(attachment.item)) { + return false; + } + if (!useFace(interaction, x, y, z, attachment.face, attachment.sneaking)) { + return false; + } + this.pendingClicks.put( + new ChunkPosition(x, y, z), + new PendingClick(world, this.currentPass, () -> attachment.isConfirmed(world.getTileEntity(x, y, z)))); + return true; + } + + private static boolean applyHammer(PrinterInteraction interaction, CarpentersHammerSupport.Adjustment adjustment, + int x, int y, int z) { + final ItemStack hammer = findHammer(interaction); + if (hammer == null || !interaction.selectItem(hammer) + || !CarpentersHammerSupport.canUseHammer(interaction.player, interaction.world)) { + return false; + } + if (adjustment.corner != null) { + final CarpentersHammerSupport.CornerHit corner = adjustment.corner; + final MovingObjectPosition hit = corner.hit; + final ItemStack held = interaction.player.getHeldItem(); + return interaction.withSneaking( + false, + () -> interaction.withLook( + corner.yaw, + corner.pitch, + () -> adjustment.click == CarpentersHammerSupport.Click.LEFT + ? interaction.tapBlock(held, x, y, z, hit.sideHit) + : interaction.useBlock(held, x, y, z, hit.sideHit, hit.hitVec))); + } + return useFace( + interaction, + x, + y, + z, + adjustment.face, + adjustment.click == CarpentersHammerSupport.Click.SNEAK_RIGHT); + } + + private static boolean useFace(PrinterInteraction interaction, int x, int y, int z, int side, boolean sneaking) { + final ForgeDirection face = ForgeDirection.getOrientation(side); + final Vec3 hit = Vec3.createVectorHelper( + x + 0.5 + face.offsetX * 0.5, + y + 0.5 + face.offsetY * 0.5, + z + 0.5 + face.offsetZ * 0.5); + return interaction.withSneaking(sneaking, () -> { + final ItemStack held = interaction.player.getHeldItem(); + if (sneaking && held != null && CarpentersBlocksSupport.usesActivationPacket(held)) { + return interaction.activateCarpenterBlock(held, x, y, z, side); + } + return interaction.useBlock(held, x, y, z, side, hit); + }); + } + + boolean place(PrinterInteraction interaction, SchematicWorld schematic, Block block, int localX, int localY, + int localZ, ItemStack item, BooleanSupplier placeNormally) { + final int x = schematic.position.x + localX; + final int y = schematic.position.y + localY; + final int z = schematic.position.z + localZ; + if (CarpentersBlocksSupport.isGarageDoor(block)) { + final Float yaw = CarpentersBlocksSupport + .findGarageDoorYaw(block, schematic, interaction.world, localX, localY, localZ); + return yaw != null && placeGarageDoor(interaction, x, y, z, block, item, yaw); + } + final TileEntity tile = schematic.getTileEntity(localX, localY, localZ); + if (CarpentersBlocksSupport.isStairs(block) || CarpentersBlocksSupport.isSlope(block)) { + return placeShape(interaction, x, y, z, block, tile, item); + } + if (CarpentersBlocksSupport.isCollapsible(block)) { + return placeCollapsible(interaction, x, y, z, block, tile, item); + } + final ForgeDirection face = CarpentersBlocksSupport.getAttachmentDirection(block, tile); + if (face != null) { + return placeSidedBlock(interaction, x, y, z, block, item, face); + } + return placeNormally.getAsBoolean(); + } + + private static boolean placeCollapsible(PrinterInteraction interaction, int x, int y, int z, Block block, + TileEntity tile, ItemStack item) { + final ForgeDirection face = CarpentersBlocksSupport.getCollapsibleDirection(tile); + if (face != ForgeDirection.UP && face != ForgeDirection.DOWN) { + return false; + } + final float yaw = interaction.player.rotationYaw; + if (canUseSupport(interaction, x, y, z, face, item)) { + return placeFromFace(interaction, x, y, z, block, item, face, true, 0.5, 0.5, yaw); + } + final ForgeDirection[] supports = interaction.findSupports(x, y, z); + for (ForgeDirection support : supports) { + final ForgeDirection side = support.getOpposite(); + if (side.offsetY == 0 && canUseSupport(interaction, x, y, z, side, item)) { + final double height = face == ForgeDirection.UP ? 0.25 : 0.75; + return placeFromFace(interaction, x, y, z, block, item, side, true, 0.5, height, yaw); + } + } + final World world = interaction.world; + final boolean snowForcesUp = world.getBlock(x, y, z) == Blocks.snow_layer + && (world.getBlockMetadata(x, y, z) & 7) == 0; + return (!ConfigurationHandler.placeAdjacent || supports.length > 0) + && (face == ForgeDirection.UP || !snowForcesUp) + && placeFromFace(interaction, x, y, z, block, item, face, false, 0.5, 0.5, yaw); + } + + private static boolean placeSidedBlock(PrinterInteraction interaction, int x, int y, int z, Block block, + ItemStack item, ForgeDirection face) { + if (face == ForgeDirection.UNKNOWN) { + return false; + } + if (CarpentersBlocksSupport.isFreestandingLadder(block, face)) { + final float yaw = face == ForgeDirection.UP ? 90 : 0; + for (ForgeDirection vertical : new ForgeDirection[] { ForgeDirection.UP, ForgeDirection.DOWN }) { + if (block.canPlaceBlockOnSide(interaction.world, x, y, z, vertical.ordinal()) + && canUseSupport(interaction, x, y, z, vertical, item)) { + return placeFromFace(interaction, x, y, z, block, item, vertical, true, 0.5, 0.5, yaw); + } + } + return false; + } + return block.canPlaceBlockOnSide(interaction.world, x, y, z, face.ordinal()) + && canUseSupport(interaction, x, y, z, face, item) + && placeFromFace(interaction, x, y, z, block, item, face, true, 0.5, 0.5, interaction.player.rotationYaw); + } + + private static boolean canUseSupport(PrinterInteraction interaction, int x, int y, int z, ForgeDirection face, + ItemStack item) { + final int sx = x - face.offsetX; + final int sy = y - face.offsetY; + final int sz = z - face.offsetZ; + final Block support = interaction.world.getBlock(sx, sy, sz); + return !support.isAir(interaction.world, sx, sy, sz) && !support.isReplaceable(interaction.world, sx, sy, sz) + && PrinterInteraction.canClickForPlacement(support, item, true); + } + + private static boolean placeFromFace(PrinterInteraction interaction, int x, int y, int z, Block block, + ItemStack item, ForgeDirection face, boolean adjacent, double across, double hitY, float yaw) { + if (PrinterInteraction.isBlacklisted(block, item) || !interaction.selectItem(item)) { + return false; + } + final int sx = adjacent ? x - face.offsetX : x; + final int sy = adjacent ? y - face.offsetY : y; + final int sz = adjacent ? z - face.offsetZ : z; + final Vec3 hit = Vec3.createVectorHelper( + sx + (face.offsetX == 0 ? across : (1 + face.offsetX) * 0.5), + sy + hitY + face.offsetY * 0.5, + sz + (face.offsetZ == 0 ? across : (1 + face.offsetZ) * 0.5)); + final BooleanSupplier click = () -> interaction.withSneaking( + true, + () -> interaction.place(interaction.player.getHeldItem(), sx, sy, sz, face.ordinal(), hit)); + return yaw == interaction.player.rotationYaw ? click.getAsBoolean() + : interaction.withLook(yaw, interaction.player.rotationPitch, click); + } + + private static ItemStack findHammer(PrinterInteraction interaction) { + return CarpentersHammerSupport + .findHammer(interaction.player.inventory.mainInventory, interaction::canSelectItem); + } + + private boolean placeGarageDoor(PrinterInteraction interaction, int x, int y, int z, Block block, ItemStack item, + float yaw) { + final World world = interaction.world; + final boolean consumesItem = !interaction.player.capabilities.isCreativeMode; + final ChunkPosition host = new ChunkPosition(x, y, z); + if ((consumesItem && (this.pendingGarageStock != null || this.deferredGarageHosts.contains(host))) + || PrinterInteraction.isBlacklisted(block, item) + || !PrinterInteraction.canClickForPlacement(world.getBlock(x, y + 1, z), item, true) + || !interaction.selectItem(item)) { + return false; + } + final InventoryPlayer inventory = interaction.player.inventory; + final int slot = inventory.currentItem; + final ItemStack held = inventory.getCurrentItem(); + final int count = held.stackSize; + // Client prediction creates the whole column, but a rejected server click only corrects the host cell. + final boolean sent = interaction.withSneaking( + true, + () -> interaction.withLook( + yaw, + interaction.player.rotationPitch, + () -> interaction.useBlockOnServer( + interaction.player.getHeldItem(), + x, + y + 1, + z, + ForgeDirection.DOWN.ordinal(), + Vec3.createVectorHelper(x + 0.5, y + 1, z + 0.5)))); + if (sent) { + this.pendingClicks.put( + host, + new PendingClick( + world, + this.currentPass, + () -> world.blockExists(x, y, z) && world.getBlock(x, y, z) == block)); + if (consumesItem) { + // A block update can arrive before the consumed item is removed from the selected slot. + final WeakReference inventoryRef = new WeakReference<>(inventory); + this.pendingGarageHost = host; + this.pendingGarageStock = new PendingClick(world, this.currentPass, () -> { + final InventoryPlayer current = inventoryRef.get(); + final ItemStack stack = current == null ? null : current.getStackInSlot(slot); + return stack == null || !stack.isItemEqual(item) || stack.stackSize < count; + }); + } + } + return sent; + } + + private static boolean placeShape(PrinterInteraction interaction, int x, int y, int z, Block block, TileEntity tile, + ItemStack item) { + if (PrinterInteraction.isBlacklisted(block, item)) { + return false; + } + final ItemStack wedge = CarpentersBlocksSupport.isSlope(block) ? CarpentersBlocksSupport.getWedgeItem(item) + : item; + final boolean usePreferred = interaction.canSelectItem(item); + final boolean useWedge = !wedge.isItemEqual(item) && interaction.canSelectItem(wedge); + if (!usePreferred && !useWedge) { + return false; + } + final ItemStack[] items = usePreferred ? (useWedge ? new ItemStack[] { item, wedge } : new ItemStack[] { item }) + : new ItemStack[] { wedge }; + final ForgeDirection[] supports = interaction.findSupports(x, y, z); + if (supports.length == 0 && ConfigurationHandler.placeAdjacent) { + return false; + } + final float originalYaw = interaction.player.rotationYaw; + final float[] yaws = { originalYaw, 0, 90, 180, 270 }; + final boolean[] clickModes = ConfigurationHandler.placeAdjacent ? new boolean[] { true } + : new boolean[] { true, false }; + for (boolean allowReshape : new boolean[] { false, true }) { + if (allowReshape && findHammer(interaction) == null) { + return false; + } + for (ItemStack candidate : items) { + final BooleanSupplier click = findShapeClick( + interaction, + x, + y, + z, + block, + tile, + candidate, + supports, + yaws, + clickModes, + allowReshape); + if (click != null) { + return interaction.selectItem(candidate) && click.getAsBoolean(); + } + } + } + return false; + } + + private static BooleanSupplier findShapeClick(PrinterInteraction interaction, int x, int y, int z, Block block, + TileEntity tile, ItemStack item, ForgeDirection[] supports, float[] yaws, boolean[] clickModes, + boolean allowReshape) { + final float originalYaw = interaction.player.rotationYaw; + final float pitch = interaction.player.rotationPitch; + for (boolean adjacent : clickModes) { + final ForgeDirection[] candidates = adjacent ? supports : ForgeDirection.VALID_DIRECTIONS; + for (float yaw : yaws) { + for (ForgeDirection support : candidates) { + final ForgeDirection face = support.getOpposite(); + final int clickedX = adjacent ? x + support.offsetX : x; + final int clickedY = adjacent ? y + support.offsetY : y; + final int clickedZ = adjacent ? z + support.offsetZ : z; + final Block clicked = interaction.world.getBlock(clickedX, clickedY, clickedZ); + if (!PrinterInteraction.canClickForPlacement(clicked, item, true) + || (!adjacent && clicked == Blocks.snow_layer + && face != ForgeDirection.UP + && (interaction.world.getBlockMetadata(clickedX, clickedY, clickedZ) & 7) == 0)) { + continue; + } + final Vec3 hit = findShapeHit( + interaction.world, + x, + y, + z, + block, + tile, + item, + yaw, + allowReshape, + face); + if (hit == null) { + continue; + } + final BooleanSupplier click = () -> interaction.withSneaking( + true, + () -> interaction.place( + interaction.player.getHeldItem(), + clickedX, + clickedY, + clickedZ, + face.ordinal(), + hit.addVector(clickedX, clickedY, clickedZ))); + return yaw == originalYaw ? click : () -> interaction.withLook(yaw, pitch, click); + } + } + } + return null; + } + + private static Vec3 findShapeHit(World world, int x, int y, int z, Block block, TileEntity tile, ItemStack item, + float yaw, boolean allowReshape, ForgeDirection face) { + for (float across : SHAPE_HIT_OFFSETS) { + for (float height : SHAPE_HIT_OFFSETS) { + final float hitX = face.offsetX == 0 ? across : (1 + face.offsetX) * 0.5f; + final float hitY = face.offsetY == 0 ? height : (1 + face.offsetY) * 0.5f; + final float hitZ = face.offsetZ == 0 ? across : (1 + face.offsetZ) * 0.5f; + final boolean matches = CarpentersBlocksSupport.isSlope(block) + ? CarpentersBlocksSupport + .matchesSlopePlacement(tile, item, face, hitX, hitY, hitZ, yaw, allowReshape) + : CarpentersBlocksSupport.matchesStairPlacement( + tile, + block, + world, + x, + y, + z, + face.ordinal(), + hitX, + hitY, + hitZ, + yaw, + allowReshape); + if (matches) { + return Vec3.createVectorHelper(hitX, hitY, hitZ); + } + } + } + return null; + } + + private static final class PendingClick { + + private final WeakReference world; + private final long retryPass; + private final BooleanSupplier confirmed; + private long lastChecked = Long.MIN_VALUE; + private boolean ready; + + private PendingClick(World world, long pass, BooleanSupplier confirmed) { + final int delay = Math.max(1, ConfigurationHandler.placeDelay); + final int timeout = Math.max(20, ConfigurationHandler.timeout); + this.world = new WeakReference<>(world); + // Keep the original retry interval in printer passes for clicks without a server update. + this.retryPass = pass + 2 + (timeout - 1) / delay; + this.confirmed = confirmed; + } + + private boolean allowsNextClick(World world, long pass) { + if (world != this.world.get() || pass >= this.retryPass) { + return true; + } + // Connected panels share a click. Check all of them once per printer pass. + if (pass != this.lastChecked) { + this.lastChecked = pass; + this.ready = this.confirmed.getAsBoolean(); + } + return this.ready; + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/MicroblockPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/MicroblockPrinter.java new file mode 100644 index 00000000..796cb3f3 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/MicroblockPrinter.java @@ -0,0 +1,85 @@ +package com.github.lunatrius.schematica.client.printer; + +import java.lang.ref.WeakReference; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.world.ChunkPosition; +import net.minecraft.world.World; + +import com.github.lunatrius.schematica.client.compat.MicroblockSupport; + +final class MicroblockPrinter { + + private static final long ACK_TIMEOUT = TimeUnit.SECONDS.toNanos(5); + + private final Map pendingPlacements = new HashMap<>(); + private WeakReference pendingWorld = new WeakReference<>(null); + + void beginPass(World world) { + if (this.pendingWorld.get() != world) { + this.pendingPlacements.clear(); + this.pendingWorld = new WeakReference<>(world); + } else if (!this.pendingPlacements.isEmpty()) { + final long now = System.nanoTime(); + this.pendingPlacements.values() + .removeIf(pending -> now - pending.sentAt >= ACK_TIMEOUT); + } + } + + boolean isWaiting(World world, int x, int y, int z) { + if (this.pendingPlacements.isEmpty()) { + return false; + } + final ChunkPosition cell = new ChunkPosition(x, y, z); + final PendingPlacement pending = this.pendingPlacements.get(cell); + if (pending == null) { + return false; + } + if (world.blockExists(x, y, z) && pending.click.isConfirmed(world.getTileEntity(x, y, z))) { + this.pendingPlacements.remove(cell); + return false; + } + return true; + } + + boolean place(PrinterInteraction interaction, TileEntity tile, int x, int y, int z) { + final MicroblockSupport.Click click = MicroblockSupport + .findPlacement(interaction.player, tile, x, y, z, interaction::canSelectItem); + if (click == null || !interaction.selectItem(click.item)) { + return false; + } + final MovingObjectPosition hit = click.hit; + // ItemMicroPart re-traces the clicked block from the player's aim on both sides. + if (!interaction.withSneaking( + click.sneaking, + () -> interaction.withLook( + click.yaw, + click.pitch, + () -> interaction.place( + interaction.player.getCurrentEquippedItem(), + hit.blockX, + hit.blockY, + hit.blockZ, + hit.sideHit, + hit.hitVec)))) { + return false; + } + // ForgeMultipart expands on the server. Keep the click pending across schematic moves and refreshes. + this.pendingPlacements.put(new ChunkPosition(x, y, z), new PendingPlacement(click)); + return true; + } + + private static final class PendingPlacement { + + private final MicroblockSupport.Click click; + private final long sentAt = System.nanoTime(); + + private PendingPlacement(MicroblockSupport.Click click) { + this.click = click; + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java new file mode 100644 index 00000000..40fa55f1 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/PrinterInteraction.java @@ -0,0 +1,325 @@ +package com.github.lunatrius.schematica.client.printer; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BooleanSupplier; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockLiquid; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.client.multiplayer.PlayerControllerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.init.Items; +import net.minecraft.item.ItemBucket; +import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemSword; +import net.minecraft.network.play.client.C03PacketPlayer.C05PacketPlayerLook; +import net.minecraft.network.play.client.C07PacketPlayerDigging; +import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement; +import net.minecraft.network.play.client.C0BPacketEntityAction; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.event.ForgeEventFactory; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; +import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; +import net.minecraftforge.fluids.BlockFluidBase; +import net.minecraftforge.fluids.IFluidBlock; + +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; +import com.github.lunatrius.schematica.client.util.BlockToItemStack; +import com.github.lunatrius.schematica.handler.ConfigurationHandler; +import com.github.lunatrius.schematica.proxy.ClientProxy; +import com.github.lunatrius.schematica.reference.Constants; +import com.github.lunatrius.schematica.reference.Mods; + +import cpw.mods.fml.common.eventhandler.Event.Result; + +final class PrinterInteraction { + + final World world; + final EntityClientPlayerMP player; + private final PlayerControllerMP controller; + private final InventoryPlayer inventory; + + PrinterInteraction(World world, EntityClientPlayerMP player, PlayerControllerMP controller) { + this.world = world; + this.player = player; + this.controller = controller; + this.inventory = player.inventory; + } + + double blockReach() { + return this.controller.getBlockReachDistance(); + } + + boolean canSelectItem(ItemStack item) { + final int slot = findItemSlot(item, false); + return (slot >= 0 && slot < Constants.Inventory.Size.HOTBAR) + || (!ConfigurationHandler.swapSlotsQueue.isEmpty() && (this.controller.isInCreativeMode() + || (slot >= 0 && this.player.openContainer == this.player.inventoryContainer))); + } + + boolean selectItem(ItemStack item) { + return selectItem(item, false); + } + + boolean selectBlockItem(ItemStack item) { + return selectItem(item, true); + } + + private boolean selectItem(ItemStack item, boolean blockStock) { + if (!selectItem(item, blockStock, true)) { + return false; + } + final ItemStack selected = this.inventory.getCurrentItem(); + return selected != null && matchesSelection(selected, item, blockStock); + } + + private boolean selectItem(ItemStack item, boolean blockStock, boolean allowInventorySwap) { + final int slot = findItemSlot(item, blockStock); + final boolean inHotbar = slot >= Constants.Inventory.InventoryOffset.HOTBAR + && slot < Constants.Inventory.InventoryOffset.HOTBAR + Constants.Inventory.Size.HOTBAR; + + if (this.controller.isInCreativeMode() && !inHotbar && !ConfigurationHandler.swapSlotsQueue.isEmpty()) { + this.inventory.currentItem = nextSwapSlot(); + this.inventory.setInventorySlotContents(this.inventory.currentItem, item.copy()); + this.controller.sendSlotPacket( + this.inventory.getStackInSlot(this.inventory.currentItem), + Constants.Inventory.SlotOffset.HOTBAR + this.inventory.currentItem); + return true; + } + + if (inHotbar) { + this.inventory.currentItem = slot; + return true; + } + return allowInventorySwap && slot >= Constants.Inventory.InventoryOffset.INVENTORY + && slot < Constants.Inventory.InventoryOffset.INVENTORY + Constants.Inventory.Size.INVENTORY + && swapIntoHotbar(slot) + && selectItem(item, blockStock, false); + } + + private int findItemSlot(ItemStack item, boolean blockStock) { + final boolean shape = Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeItem(item); + final int connections = shape ? ArchitectureCraftSupport.getDisabledConnections(item) : 0; + final boolean canSwap = !ConfigurationHandler.swapSlotsQueue.isEmpty() + && this.player.openContainer == this.player.inventoryContainer; + int fallback = -1; + for (int i = 0; i < this.inventory.mainInventory.length; i++) { + final ItemStack stack = this.inventory.mainInventory[i]; + if (stack != null && stack.stackSize > 0 && matchesSelection(stack, item, blockStock)) { + if (!shape || (ArchitectureCraftSupport.getDisabledConnections(stack) == connections + && (i < Constants.Inventory.Size.HOTBAR || canSwap))) { + return i; + } + if (fallback < 0) { + fallback = i; + } + } + } + // Creative can make an exact stack. Survival can use the sawbench shape and adjust its connections by hand. + return shape && this.controller.isInCreativeMode() && !ConfigurationHandler.swapSlotsQueue.isEmpty() ? -1 + : fallback; + } + + private static boolean matchesSelection(ItemStack stack, ItemStack target, boolean blockStock) { + return blockStock ? BlockToItemStack.matchesBlockStock(stack, target) : BlockToItemStack.matches(stack, target); + } + + private boolean swapIntoHotbar(int sourceSlot) { + if (this.player.openContainer != this.player.inventoryContainer + || ConfigurationHandler.swapSlotsQueue.isEmpty()) { + return false; + } + this.controller + .windowClick(this.player.inventoryContainer.windowId, sourceSlot, nextSwapSlot(), 2, this.player); + return true; + } + + private static int nextSwapSlot() { + final int slot = ConfigurationHandler.swapSlotsQueue.poll() % Constants.Inventory.Size.HOTBAR; + ConfigurationHandler.swapSlotsQueue.offer(slot); + return slot; + } + + static boolean isBlacklisted(Block block, ItemStack item) { + return block instanceof IFluidBlock || block instanceof BlockLiquid + || item.getItem() instanceof ItemBucket + || item.getItem() == Items.sign + || ClientProxy.lotrProxy.isBlackListed(block, item); + } + + ForgeDirection[] findSupports(int x, int y, int z) { + final List supports = new ArrayList<>(); + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + final int sx = x + side.offsetX; + final int sy = y + side.offsetY; + final int sz = z + side.offsetZ; + final Block block = this.world.getBlock(sx, sy, sz); + if (block != null && !block.isAir(this.world, sx, sy, sz) + && !(block instanceof BlockFluidBase) + && !block.isReplaceable(this.world, sx, sy, sz)) { + supports.add(side); + } + } + return supports.toArray(new ForgeDirection[supports.size()]); + } + + static boolean canClickForPlacement(Block clicked, ItemStack item, boolean sneaking) { + return !Mods.CARPENTERS_BLOCKS || CarpentersBlocksSupport.allowsPlacementClick(clicked, item, sneaking); + } + + boolean place(ItemStack held, int x, int y, int z, int side, Vec3 hit) { + return held != null && canClickForPlacement(this.world.getBlock(x, y, z), held, this.player.isSneaking()) + && useBlock(held, x, y, z, side, hit); + } + + boolean useBlock(ItemStack held, int x, int y, int z, int side, Vec3 hit) { + if (prepareBlockUse(held, x, y, z, side) == null) { + return false; + } + final boolean success = this.controller.onPlayerRightClick(this.player, this.world, held, x, y, z, side, hit); + if (success) { + this.player.swingItem(); + } + return success; + } + + boolean useBlockOnServer(ItemStack held, int x, int y, int z, int side, Vec3 hit) { + final PlayerInteractEvent event = prepareBlockUse(held, x, y, z, side); + if (event == null || event.useItem == Result.DENY) { + return false; + } + this.player.sendQueue.addToSendQueue( + new C08PacketPlayerBlockPlacement( + x, + y, + z, + side, + held, + (float) (hit.xCoord - x), + (float) (hit.yCoord - y), + (float) (hit.zCoord - z))); + this.player.swingItem(); + return true; + } + + boolean breakBlock(int x, int y, int z) { + if (!this.controller.isInCreativeMode()) { + return false; + } + final int originalSlot = this.inventory.currentItem; + int breakSlot = originalSlot; + if (!canBreakWith(this.inventory.getCurrentItem())) { + for (breakSlot = 0; breakSlot < Constants.Inventory.Size.HOTBAR; breakSlot++) { + if (canBreakWith(this.inventory.getStackInSlot(breakSlot))) { + break; + } + } + if (breakSlot == Constants.Inventory.Size.HOTBAR) { + return false; + } + } + this.inventory.currentItem = breakSlot; + try { + return withSneaking(false, () -> { + this.controller.syncCurrentPlayItem(); + this.controller.clickBlock(x, y, z, ForgeDirection.DOWN.ordinal()); + return true; + }); + } finally { + this.inventory.currentItem = originalSlot; + } + } + + private static boolean canBreakWith(ItemStack held) { + return held == null || (!(held.getItem() instanceof ItemSword) + && (!Mods.CARPENTERS_BLOCKS || !CarpentersBlocksSupport.isCarpenterTool(held))); + } + + boolean activateCarpenterBlock(ItemStack held, int x, int y, int z, int side) { + if (!isStillHolding(held) || !CarpentersBlocksSupport.isCoverable(this.world.getBlock(x, y, z)) + || !CarpentersBlocksSupport.canConfigure(this.world.getTileEntity(x, y, z), this.player)) { + return false; + } + this.controller.syncCurrentPlayItem(); + // Carpenter's activation packet runs a Forge interaction check on the server before changing the tile. + CarpentersBlocksSupport.sendActivation(x, y, z, side); + this.player.swingItem(); + return true; + } + + boolean tapBlock(ItemStack held, int x, int y, int z, int side) { + if (!isStillHolding(held) || (!this.controller.isInCreativeMode() && this.world.getBlock(x, y, z) + .getPlayerRelativeBlockHardness(this.player, this.world, x, y, z) >= 1)) { + return false; + } + this.controller.syncCurrentPlayItem(); + final PlayerInteractEvent event = ForgeEventFactory + .onPlayerInteract(this.player, Action.LEFT_CLICK_BLOCK, x, y, z, side, this.world); + if (event.isCanceled() || event.useBlock == Result.DENY || !isStillHolding(held)) { + return false; + } + // Carpenter's handles the hammer on the first click. Abort before mining can progress. + this.player.sendQueue.addToSendQueue(new C07PacketPlayerDigging(0, x, y, z, side)); + this.player.sendQueue.addToSendQueue(new C07PacketPlayerDigging(1, x, y, z, side)); + this.player.swingItem(); + return true; + } + + private PlayerInteractEvent prepareBlockUse(ItemStack held, int x, int y, int z, int side) { + if (!isStillHolding(held)) { + return null; + } + // Interaction listeners can send packets before PlayerControllerMP handles the vanilla click. + this.controller.syncCurrentPlayItem(); + final PlayerInteractEvent event = ForgeEventFactory + .onPlayerInteract(this.player, Action.RIGHT_CLICK_BLOCK, x, y, z, side, this.world); + return event.isCanceled() || !isStillHolding(held) ? null : event; + } + + private boolean isStillHolding(ItemStack item) { + return item != null && item.stackSize > 0 && item == this.player.getHeldItem(); + } + + private void syncSneaking(boolean sneaking) { + this.player.setSneaking(sneaking); + this.player.sendQueue.addToSendQueue(new C0BPacketEntityAction(this.player, sneaking ? 1 : 2)); + } + + boolean withSneaking(boolean sneaking, BooleanSupplier action) { + final boolean previousInput = this.player.movementInput.sneak; + final boolean wasSneaking = this.player.isSneaking(); + this.player.movementInput.sneak = sneaking; + if (sneaking != wasSneaking) { + syncSneaking(sneaking); + } + try { + return action.getAsBoolean(); + } finally { + this.player.movementInput.sneak = previousInput; + if (sneaking != wasSneaking) { + syncSneaking(wasSneaking); + } + } + } + + boolean withLook(float yaw, float pitch, BooleanSupplier action) { + final float previousYaw = this.player.rotationYaw; + final float previousPitch = this.player.rotationPitch; + syncLook(yaw, pitch); + try { + return action.getAsBoolean(); + } finally { + syncLook(previousYaw, previousPitch); + } + } + + private void syncLook(float yaw, float pitch) { + this.player.rotationYaw = yaw; + this.player.rotationPitch = pitch; + this.player.sendQueue.addToSendQueue(new C05PacketPlayerLook(yaw, pitch, this.player.onGround)); + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java index 38156a62..0d7a883d 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/SchematicPrinter.java @@ -1,35 +1,31 @@ package com.github.lunatrius.schematica.client.printer; -import java.util.ArrayList; -import java.util.List; - import net.minecraft.block.Block; -import net.minecraft.block.BlockLiquid; import net.minecraft.block.BlockPistonBase; +import net.minecraft.block.BlockSlab; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.init.Items; -import net.minecraft.item.ItemBucket; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemSlab; import net.minecraft.item.ItemStack; -import net.minecraft.network.play.client.C0BPacketEntityAction; +import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.event.ForgeEventFactory; -import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; -import net.minecraftforge.fluids.BlockFluidBase; -import net.minecraftforge.fluids.IFluidBlock; import com.github.lunatrius.core.util.vector.Vector3i; +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; +import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.client.printer.registry.PlacementData; import com.github.lunatrius.schematica.client.printer.registry.PlacementRegistry; import com.github.lunatrius.schematica.client.util.BlockToItemStack; import com.github.lunatrius.schematica.client.world.SchematicWorld; import com.github.lunatrius.schematica.handler.ConfigurationHandler; import com.github.lunatrius.schematica.proxy.ClientProxy; -import com.github.lunatrius.schematica.reference.Constants; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; import cpw.mods.fml.common.registry.FMLControlledNamespacedRegistry; @@ -39,14 +35,15 @@ public class SchematicPrinter { public static final SchematicPrinter INSTANCE = new SchematicPrinter(); public static final FMLControlledNamespacedRegistry BLOCK_REGISTRY = GameData.getBlockRegistry(); - private final Minecraft minecraft = Minecraft.getMinecraft(); + private final MicroblockPrinter microblocks = new MicroblockPrinter(); + private final CarpentersPrinter carpenters = new CarpentersPrinter(); + private final ArchitectureCraftPrinter architectureCraft = new ArchitectureCraftPrinter(); private boolean isEnabled; private boolean isPrinting; - - private SchematicWorld schematic = null; - private byte[][][] timeout = null; + private SchematicWorld schematic; + private byte[][][] retryDelay; public boolean isEnabled() { return this.isEnabled; @@ -76,22 +73,28 @@ public SchematicWorld getSchematic() { public void setSchematic(SchematicWorld schematic) { this.isPrinting = false; this.schematic = schematic; + if (schematic == null) { + this.carpenters.reset(); + } refresh(); } public void refresh() { if (this.schematic != null) { - this.timeout = new byte[this.schematic.getWidth()][this.schematic.getHeight()][this.schematic.getLength()]; + this.retryDelay = new byte[this.schematic.getWidth()][this.schematic.getHeight()][this.schematic + .getLength()]; } else { - this.timeout = null; + this.retryDelay = null; } } public boolean print() { final EntityClientPlayerMP player = this.minecraft.thePlayer; final World world = this.minecraft.theWorld; - - syncSneaking(player, true); + final PrinterInteraction interaction = new PrinterInteraction(world, player, this.minecraft.playerController); + this.microblocks.beginPass(world); + this.carpenters.beginPass(world); + this.architectureCraft.beginPass(world); final Vector3i trans = ClientProxy.playerPosition.clone() .sub(this.schematic.position.x, this.schematic.position.y, this.schematic.position.z) @@ -103,191 +106,257 @@ public boolean print() { final int minZ = Math.max(0, trans.z - 3); final int maxZ = Math.min(this.schematic.getLength(), trans.z + 4); - final int slot = player.inventory.currentItem; - final boolean isSneaking = player.isSneaking(); - - final boolean isRenderingLayer = this.schematic.isRenderingLayer; - final int renderingLayer = this.schematic.renderingLayer; - for (int y = minY; y < maxY; y++) { - if (isRenderingLayer && y != renderingLayer) { - continue; - } - - for (int x = minX; x < maxX; x++) { - for (int z = minZ; z < maxZ; z++) { - try { - if (placeBlock(world, player, x, y, z)) { - player.inventory.currentItem = slot; - syncSneaking(player, isSneaking); - return true; + try { + final boolean isRenderingLayer = this.schematic.isRenderingLayer; + final int renderingLayer = this.schematic.renderingLayer; + for (int y = minY; y < maxY; y++) { + if (isRenderingLayer && renderingLayer != y) { + continue; + } + for (int x = minX; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + final int selectedSlot = player.inventory.currentItem; + try { + if (printCell(interaction, x, y, z)) { + return true; + } + } finally { + player.inventory.currentItem = selectedSlot; } - } catch (Exception e) { - Reference.logger.error("Could not place block!", e); - player.inventory.currentItem = slot; - syncSneaking(player, isSneaking); - return false; } } } + this.carpenters.finishPass(); + return true; + } catch (Exception e) { + Reference.logger.error("Could not place block!", e); + return false; } - - player.inventory.currentItem = slot; - syncSneaking(player, isSneaking); - return true; } - private boolean placeBlock(World world, EntityPlayer player, int x, int y, int z) { - if (this.timeout[x][y][z] > 0) { - this.timeout[x][y][z] -= ConfigurationHandler.placeDelay; + // Returns true when placement should end the current pass. + private boolean printCell(PrinterInteraction interaction, int x, int y, int z) { + final World world = interaction.world; + final EntityClientPlayerMP player = interaction.player; + final int worldX = this.schematic.position.x + x; + final int worldY = this.schematic.position.y + y; + final int worldZ = this.schematic.position.z + z; + + if (this.carpenters.isWaiting(worldX, worldY, worldZ) + || this.microblocks.isWaiting(world, worldX, worldY, worldZ)) { + return false; + } + if (this.retryDelay[x][y][z] > 0) { + this.retryDelay[x][y][z] -= Math.max(1, ConfigurationHandler.placeDelay); return false; } - - final int wx = this.schematic.position.x + x; - final int wy = this.schematic.position.y + y; - final int wz = this.schematic.position.z + z; final Block block = this.schematic.getBlock(x, y, z); - final Block realBlock = world.getBlock(wx, wy, wz); + final Block placedBlock = world.getBlock(worldX, worldY, worldZ); final int metadata = this.schematic.getBlockMetadata(x, y, z); - final int realMetadata = world.getBlockMetadata(wx, wy, wz); - if (block == realBlock && metadata == realMetadata) { - return false; + if (Mods.FORGE_MICROBLOCK && MicroblockSupport.isMultipartBlock(block)) { + final TileEntity tile = this.schematic.getTileEntity(x, y, z); + if (MicroblockSupport.hasMicroblocks(tile)) { + if (this.microblocks.place(interaction, tile, worldX, worldY, worldZ)) { + return !ConfigurationHandler.placeInstantly; + } + // Preserve existing parts and leave room for placements that need stock or support. + if (MicroblockSupport.isMultipartBlock(placedBlock) || world.isAirBlock(worldX, worldY, worldZ) + || placedBlock.isReplaceable(world, worldX, worldY, worldZ)) { + return false; + } + } } - if (ConfigurationHandler.destroyBlocks && !world.isAirBlock(wx, wy, wz) - && this.minecraft.playerController.isInCreativeMode()) { - this.minecraft.playerController.clickBlock(wx, wy, wz, 0); - - this.timeout[x][y][z] = (byte) ConfigurationHandler.timeout; - - return !ConfigurationHandler.destroyInstantly; + final boolean carpenterBlock = Mods.CARPENTERS_BLOCKS && CarpentersBlocksSupport.isCoverable(block); + if (carpenterBlock && block == placedBlock) { + return this.carpenters.configureBlock( + interaction, + this.schematic, + block, + this.schematic.getTileEntity(x, y, z), + worldX, + worldY, + worldZ) && !ConfigurationHandler.placeInstantly; } - if (this.schematic.isAirBlock(x, y, z)) { + final boolean architectureShape = Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeBlock(block); + final TileEntity architectureTile = architectureShape ? this.schematic.getTileEntity(x, y, z) : null; + final TileEntity placedArchitectureTile = architectureShape && block == placedBlock + ? world.getTileEntity(worldX, worldY, worldZ) + : null; + if (architectureShape && ArchitectureCraftSupport.needsHammerTurn(placedArchitectureTile, architectureTile)) { + if (this.architectureCraft.rotateCapital(interaction, placedArchitectureTile, worldX, worldY, worldZ)) { + this.retryDelay[x][y][z] = (byte) ConfigurationHandler.timeout; + return !ConfigurationHandler.placeInstantly; + } return false; } - - if (!realBlock.isReplaceable(world, wx, wy, wz)) { + if (block == placedBlock + && BlockToItemStack.matchesSavedState(block, player, world, worldX, worldY, worldZ, this.schematic, x, y, z) + && (!architectureShape + || ArchitectureCraftSupport.matches(placedArchitectureTile, architectureTile, block))) { return false; } - final ItemStack itemStack = BlockToItemStack.getItemStack(player, block, this.schematic, x, y, z); - if (itemStack == null || itemStack.getItem() == null) { - Reference.logger.debug("{} is missing a mapping!", BLOCK_REGISTRY.getNameForObject(block)); + // Native slab merges cannot recreate the seamless double-stone-slab variant. + if (block == Blocks.double_stone_slab && (metadata & 8) != 0) { return false; } - if (placeBlock(world, player, wx, wy, wz, block, metadata, itemStack)) { - this.timeout[x][y][z] = (byte) ConfigurationHandler.timeout; - - if (!ConfigurationHandler.placeInstantly) { - return true; + if (block instanceof BlockSlab && block.isOpaqueCube() + && placedBlock instanceof BlockSlab + && !placedBlock.isOpaqueCube()) { + final ItemStack slab = BlockToItemStack.getItemStack(player, block, this.schematic, x, y, z); + if (slab != null && slab.getItem() instanceof ItemSlab + && BlockToItemStack.matchesHalfSlab(world, worldX, worldY, worldZ, slab) + && BlockToItemStack.matchesPaint(block, world, worldX, worldY, worldZ, this.schematic, x, y, z)) { + if (interaction.selectItem(slab) + && mergeSlab(interaction, worldX, worldY, worldZ, player.getHeldItem())) { + this.retryDelay[x][y][z] = (byte) ConfigurationHandler.timeout; + return !ConfigurationHandler.placeInstantly; + } + return false; } } - return false; - } - - private boolean isSolid(World world, int x, int y, int z, ForgeDirection side) { - x += side.offsetX; - y += side.offsetY; - z += side.offsetZ; + if (ConfigurationHandler.destroyBlocks && !world.isAirBlock(worldX, worldY, worldZ) + && interaction.breakBlock(worldX, worldY, worldZ)) { + this.retryDelay[x][y][z] = (byte) ConfigurationHandler.timeout; - Block block = world.getBlock(x, y, z); - - if (block == null) { - return false; + return !ConfigurationHandler.destroyInstantly; } - if (block.isAir(world, x, y, z)) { + if (this.schematic.isAirBlock(x, y, z)) { return false; } - if (block instanceof BlockFluidBase) { + if (!placedBlock.isReplaceable(world, worldX, worldY, worldZ)) { return false; } - if (block.isReplaceable(world, x, y, z)) { + final ItemStack itemStack = BlockToItemStack.getItemStack(player, block, this.schematic, x, y, z); + if (itemStack == null || itemStack.getItem() == null) { + Reference.logger.debug("{} is missing a mapping!", BLOCK_REGISTRY.getNameForObject(block)); return false; } - return true; - } - - private ForgeDirection[] getSolidSides(World world, int x, int y, int z) { - List list = new ArrayList<>(); + final boolean success; + if (architectureShape) { + success = ArchitectureCraftPrinter.place(interaction, worldX, worldY, worldZ, architectureTile, itemStack); + } else if (carpenterBlock) { + success = this.carpenters.place( + interaction, + this.schematic, + block, + x, + y, + z, + itemStack, + () -> placeVanillaBlock(interaction, worldX, worldY, worldZ, block, metadata, itemStack)); + } else { + success = placeVanillaBlock(interaction, worldX, worldY, worldZ, block, metadata, itemStack); + } + if (success) { + this.retryDelay[x][y][z] = (byte) ConfigurationHandler.timeout; - for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { - if (isSolid(world, x, y, z, side)) { - list.add(side); + if (!ConfigurationHandler.placeInstantly) { + return true; } } - ForgeDirection[] sides = new ForgeDirection[list.size()]; - return list.toArray(sides); + return false; } - private boolean placeBlock(World world, EntityPlayer player, int x, int y, int z, Block block, int metadata, + private boolean placeVanillaBlock(PrinterInteraction interaction, int x, int y, int z, Block block, int metadata, ItemStack itemStack) { - if (isBlacklisted(block, itemStack)) { + final World world = interaction.world; + if (PrinterInteraction.isBlacklisted(block, itemStack)) { return false; } - PlacementData data = PlacementRegistry.INSTANCE.getPlacementData(block, itemStack); + final PlacementData data = PlacementRegistry.INSTANCE.getPlacementData(block, itemStack); - if (!isValidOrientation(player, x, y, z, data, metadata)) { + if (!isValidOrientation(interaction.player, x, y, z, data, metadata)) { return false; } - ForgeDirection[] solidSides = getSolidSides(world, x, y, z); + final ForgeDirection[] solidSides = interaction.findSupports(x, y, z); + final ForgeDirection[] validSides = data == null ? solidSides : data.getValidDirections(solidSides, metadata); + final boolean slab = block instanceof BlockSlab && itemStack.getItem() instanceof ItemSlab; + final boolean halfSlab = slab && !block.isOpaqueCube(); ForgeDirection direction = ForgeDirection.UNKNOWN; - float offsetY = 0.0f; - int extraClicks = 0; - - if (solidSides.length > 0) { - if (data != null) { - ForgeDirection[] validDirections = data.getValidDirections(solidSides, metadata); - if (validDirections.length > 0) { - direction = validDirections[0]; - } - - offsetY = data.getOffsetFromMetadata(metadata); - extraClicks = data.getExtraClicks(block, metadata); - } else { - direction = solidSides[0]; + for (ForgeDirection support : validSides) { + if ((!halfSlab || placesSlabHalf(metadata, support)) && PrinterInteraction.canClickForPlacement( + world.getBlock(x + support.offsetX, y + support.offsetY, z + support.offsetZ), + itemStack, + true) && (!slab || !wouldMergeSupportingSlab(world, x, y, z, support, itemStack))) { + direction = support; + break; } + } - if (!swapToItem(player.inventory, itemStack)) { + final boolean adjacent = direction != ForgeDirection.UNKNOWN; + if (!adjacent) { + final boolean needsMappedSupport = data != null && data.type == PlacementData.PlacementType.BLOCK + && !data.mapping.isEmpty() + && !data.allowsDirectClick(); + if ((ConfigurationHandler.placeAdjacent && solidSides.length == 0) + || (needsMappedSupport && validSides.length == 0) + || !(itemStack.getItem() instanceof ItemBlock)) { + return false; + } + final ForgeDirection[] valid = needsMappedSupport ? validSides + : data == null ? ForgeDirection.VALID_DIRECTIONS + : data.getValidDirections(ForgeDirection.VALID_DIRECTIONS, metadata); + // ItemBlock forces an upward click when replacing a single layer of snow. + final boolean snowForcesUp = world.getBlock(x, y, z) == Blocks.snow_layer + && (world.getBlockMetadata(x, y, z) & 7) == 0; + for (ForgeDirection side : valid) { + // ItemSlab checks the block across the clicked face before placing into the clicked cell. + if ((!snowForcesUp || side == ForgeDirection.DOWN) && (!halfSlab || placesSlabHalf(metadata, side)) + && (!slab || !BlockToItemStack + .matchesHalfSlab(world, x - side.offsetX, y - side.offsetY, z - side.offsetZ, itemStack))) { + direction = side; + break; + } + } + if (direction == ForgeDirection.UNKNOWN) { return false; } } - if (direction != ForgeDirection.UNKNOWN || !ConfigurationHandler.placeAdjacent) { - return placeBlock(world, player, x, y, z, direction, 0.0f, offsetY, 0.0f, extraClicks); - } - - return false; + final float offsetY = data == null || data.maskOffset == 0 ? 0.5f : data.getOffsetFromMetadata(metadata); + final int extraClicks = data == null ? 0 : data.getExtraClicks(block, metadata); + return interaction.selectBlockItem(itemStack) + && placeAgainstSupport(interaction, x, y, z, direction, adjacent, offsetY, extraClicks); } - private boolean isBlacklisted(Block block, ItemStack itemStack) { - if (block instanceof IFluidBlock || block instanceof BlockLiquid) { - return true; - } - - if (itemStack.getItem() instanceof ItemBucket) { - return true; - } - - if (itemStack.getItem() == Items.sign) { - return true; - } + static boolean placesSlabHalf(int metadata, ForgeDirection support) { + return support.offsetY == 0 + || ((metadata & 8) != 0 ? support == ForgeDirection.UP : support == ForgeDirection.DOWN); + } - if (ClientProxy.lotrProxy.isBlackListed(block, itemStack)) { - return true; + private boolean wouldMergeSupportingSlab(World world, int x, int y, int z, ForgeDirection support, ItemStack slab) { + if (support.offsetY == 0 || !BlockToItemStack.matchesHalfSlab(world, x, y + support.offsetY, z, slab)) { + return false; } + final boolean top = (world.getBlockMetadata(x, y + support.offsetY, z) & 8) != 0; + return top ? support == ForgeDirection.UP : support == ForgeDirection.DOWN; + } - return false; + private boolean mergeSlab(PrinterInteraction interaction, int x, int y, int z, ItemStack slab) { + final boolean top = (interaction.world.getBlockMetadata(x, y, z) & 8) != 0; + return interaction.withSneaking( + true, + () -> interaction.place( + slab, + x, + y, + z, + top ? ForgeDirection.DOWN.ordinal() : ForgeDirection.UP.ordinal(), + Vec3.createVectorHelper(x + 0.5, y + 0.5, z + 0.5))); } private boolean isValidOrientation(EntityPlayer player, int x, int y, int z, PlacementData data, int metadata) { @@ -320,116 +389,47 @@ private boolean isValidOrientation(EntityPlayer player, int x, int y, int z, Pla return true; } - private boolean placeBlock(World world, EntityPlayer player, int x, int y, int z, ForgeDirection direction, - float offsetX, float offsetY, float offsetZ, int extraClicks) { - ItemStack itemStack = player.getCurrentEquippedItem(); + private boolean placeAgainstSupport(PrinterInteraction interaction, int x, int y, int z, ForgeDirection direction, + boolean adjacent, float offsetY, int extraClicks) { + final EntityClientPlayerMP player = interaction.player; + final ItemStack itemStack = player.getCurrentEquippedItem(); if (!this.minecraft.playerController.isInCreativeMode() && itemStack != null + && !(itemStack.getItem() instanceof ItemSlab) && itemStack.stackSize <= extraClicks) { return false; } - x += direction.offsetX; - y += direction.offsetY; - z += direction.offsetZ; - - int side = direction.getOpposite() - .ordinal(); - final Vec3 hitVec = Vec3.createVectorHelper(x + offsetX, y + offsetY, z + offsetZ); - - boolean success = placeBlock(world, player, itemStack, x, y, z, side, hitVec); - for (int i = 0; success && i < extraClicks; i++) { - success = placeBlock(world, player, itemStack, x, y, z, side, hitVec); - } - - if (itemStack != null && itemStack.stackSize == 0 && success) { - player.inventory.mainInventory[player.inventory.currentItem] = null; - } - - return success; - } - - private boolean placeBlock(World world, EntityPlayer player, ItemStack itemStack, int x, int y, int z, int side, - Vec3 hitVec) { - boolean success = !ForgeEventFactory.onPlayerInteract(player, Action.RIGHT_CLICK_BLOCK, x, y, z, side, world) - .isCanceled(); - if (success) { - success = this.minecraft.playerController - .onPlayerRightClick(player, world, itemStack, x, y, z, side, hitVec); - if (success) { - player.swingItem(); - } - } - - return success; - } - - private void syncSneaking(EntityClientPlayerMP player, boolean isSneaking) { - player.setSneaking(isSneaking); - player.sendQueue.addToSendQueue(new C0BPacketEntityAction(player, isSneaking ? 1 : 2)); - } - - private boolean swapToItem(InventoryPlayer inventory, ItemStack itemStack) { - return swapToItem(inventory, itemStack, true); - } - - private boolean swapToItem(InventoryPlayer inventory, ItemStack itemStack, boolean swapSlots) { - int slot = getInventorySlotWithItem(inventory, itemStack); - - if (this.minecraft.playerController.isInCreativeMode() - && (slot < Constants.Inventory.InventoryOffset.HOTBAR - || slot >= Constants.Inventory.InventoryOffset.HOTBAR + Constants.Inventory.Size.HOTBAR) - && !ConfigurationHandler.swapSlotsQueue.isEmpty()) { - inventory.currentItem = getNextSlot(); - inventory.setInventorySlotContents(inventory.currentItem, itemStack.copy()); - this.minecraft.playerController.sendSlotPacket( - inventory.getStackInSlot(inventory.currentItem), - Constants.Inventory.SlotOffset.HOTBAR + inventory.currentItem); - return true; - } - - if (slot >= Constants.Inventory.InventoryOffset.HOTBAR - && slot < Constants.Inventory.InventoryOffset.HOTBAR + Constants.Inventory.Size.HOTBAR) { - inventory.currentItem = slot; - return true; - } else if (swapSlots && slot >= Constants.Inventory.InventoryOffset.INVENTORY - && slot < Constants.Inventory.InventoryOffset.INVENTORY + Constants.Inventory.Size.INVENTORY) { - if (swapSlots(inventory, slot)) { - return swapToItem(inventory, itemStack, false); + final int clickedX = adjacent ? x + direction.offsetX : x; + final int clickedY = adjacent ? y + direction.offsetY : y; + final int clickedZ = adjacent ? z + direction.offsetZ : z; + final ForgeDirection face = direction.getOpposite(); + final int side = face.ordinal(); + final Vec3 hit = Vec3.createVectorHelper( + clickedX + 0.5 + face.offsetX * 0.5, + clickedY + (face.offsetY == 0 ? offsetY : (1 + face.offsetY) * 0.5), + clickedZ + 0.5 + face.offsetZ * 0.5); + + final boolean success = interaction.withSneaking(true, () -> { + boolean placed = interaction.place(itemStack, clickedX, clickedY, clickedZ, side, hit); + if (placed && extraClicks > 0 && itemStack.getItem() instanceof ItemSlab) { + // The existing-half path can finish on a later pass when the remaining slab is in another slot. + if (itemStack.stackSize > 0 + && BlockToItemStack.matchesHalfSlab(interaction.world, x, y, z, itemStack)) { + mergeSlab(interaction, x, y, z, itemStack); } + return true; } - return false; - } - - private int getInventorySlotWithItem(final InventoryPlayer inventory, final ItemStack itemStack) { - for (int i = 0; i < inventory.mainInventory.length; i++) { - if (inventory.mainInventory[i] != null && inventory.mainInventory[i].isItemEqual(itemStack)) { - return i; + for (int i = 0; placed && i < extraClicks; i++) { + placed = interaction.place(itemStack, clickedX, clickedY, clickedZ, side, hit); } - } - return -1; - } - - private boolean swapSlots(InventoryPlayer inventory, int from) { - if (!ConfigurationHandler.swapSlotsQueue.isEmpty()) { - int slot = getNextSlot(); + return placed; + }); - swapSlots(from, slot); - return true; + if (itemStack != null && itemStack.stackSize == 0 && success) { + player.inventory.mainInventory[player.inventory.currentItem] = null; } - return false; - } - - private int getNextSlot() { - int slot = ConfigurationHandler.swapSlotsQueue.poll() % Constants.Inventory.Size.HOTBAR; - ConfigurationHandler.swapSlotsQueue.offer(slot); - return slot; - } - - private boolean swapSlots(final int from, final int to) { - return this.minecraft.playerController - .windowClick(this.minecraft.thePlayer.inventoryContainer.windowId, from, to, 2, this.minecraft.thePlayer) - == null; + return success; } } diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementData.java b/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementData.java index 43fd6301..2c8ba16f 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementData.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementData.java @@ -24,6 +24,7 @@ public enum PlacementType { public float offsetHighY = 1.0f; public int maskMeta = 0xF; public final Map mapping = new HashMap<>(); + private boolean directClick; private IExtraClick extraClick; public PlacementData(PlacementType type, int... metadata) { @@ -52,6 +53,16 @@ public float getOffsetFromMetadata(int metadata) { return (metadata & this.maskOffset) == 0 ? this.offsetLowY : this.offsetHighY; } + /** Lets a mapped face set orientation through a click on the target cell itself. */ + public PlacementData allowDirectClick() { + this.directClick = true; + return this; + } + + public boolean allowsDirectClick() { + return this.directClick; + } + public ForgeDirection[] getValidDirections(ForgeDirection[] solidSides, int metadata) { List list = new ArrayList<>(); diff --git a/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementRegistry.java b/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementRegistry.java index 27478d60..a1931ea2 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementRegistry.java +++ b/src/main/java/com/github/lunatrius/schematica/client/printer/registry/PlacementRegistry.java @@ -13,13 +13,17 @@ import net.minecraft.block.BlockPistonBase; import net.minecraft.block.BlockPumpkin; import net.minecraft.block.BlockRotatedPillar; +import net.minecraft.block.BlockSlab; import net.minecraft.block.BlockStairs; import net.minecraft.block.BlockTorch; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; +import net.minecraft.item.ItemSlab; import net.minecraft.item.ItemStack; +import cpw.mods.fml.common.registry.GameRegistry; + public class PlacementRegistry { public static final PlacementRegistry INSTANCE = new PlacementRegistry(); @@ -27,14 +31,16 @@ public class PlacementRegistry { private final Map, PlacementData> classPlacementMap = new HashMap<>(); private final Map blockPlacementMap = new HashMap<>(); private final Map itemPlacementMap = new HashMap<>(); + private final PlacementData halfSlab = new PlacementData(PlacementData.PlacementType.BLOCK) + .setOffset(0x8, 0.25f, 0.75f); + private final PlacementData doubleSlab = new PlacementData(PlacementData.PlacementType.BLOCK) + .setExtraClick((block, metadata) -> 1); public void populatePlacementMaps() { this.classPlacementMap.clear(); this.blockPlacementMap.clear(); this.itemPlacementMap.clear(); - final IExtraClick extraClickDoubleSlab = (block, metadata) -> block.isOpaqueCube() ? 1 : 0; - addPlacementMapping( BlockButton.class, new PlacementData(PlacementData.PlacementType.BLOCK, -1, -1, 3, 4, 1, 2).setMaskMeta(0x7)); @@ -52,7 +58,8 @@ public void populatePlacementMaps() { new PlacementData(PlacementData.PlacementType.PLAYER, -1, -1, 3, 2, 5, 4)); addPlacementMapping( BlockHopper.class, - new PlacementData(PlacementData.PlacementType.BLOCK, 0, 1, 2, 3, 4, 5).setMaskMeta(0x7)); + new PlacementData(PlacementData.PlacementType.BLOCK, 0, 1, 2, 3, 4, 5).setMaskMeta(0x7) + .allowDirectClick()); addPlacementMapping( BlockPistonBase.class, new PlacementData(PlacementData.PlacementType.PISTON, 0, 1, 2, 3, 4, 5).setMaskMeta(0x7)); @@ -61,7 +68,8 @@ public void populatePlacementMaps() { new PlacementData(PlacementData.PlacementType.PLAYER, -1, -1, 0, 2, 3, 1).setMaskMeta(0xF)); addPlacementMapping( BlockRotatedPillar.class, - new PlacementData(PlacementData.PlacementType.BLOCK, 0, 0, 8, 8, 4, 4).setMaskMeta(0xC)); + new PlacementData(PlacementData.PlacementType.BLOCK, 0, 0, 8, 8, 4, 4).setMaskMeta(0xC) + .allowDirectClick()); addPlacementMapping( BlockStairs.class, new PlacementData(PlacementData.PlacementType.PLAYER, -1, -1, 3, 2, 1, 0).setOffset(0x4, 0.0f, 1.0f) @@ -76,13 +84,6 @@ public void populatePlacementMaps() { addPlacementMapping(Blocks.wool, new PlacementData(PlacementData.PlacementType.BLOCK)); addPlacementMapping(Blocks.yellow_flower, new PlacementData(PlacementData.PlacementType.BLOCK)); addPlacementMapping(Blocks.red_flower, new PlacementData(PlacementData.PlacementType.BLOCK)); - addPlacementMapping( - Blocks.double_stone_slab, - new PlacementData(PlacementData.PlacementType.BLOCK).setExtraClick(extraClickDoubleSlab)); - addPlacementMapping( - Blocks.stone_slab, - new PlacementData(PlacementData.PlacementType.BLOCK).setOffset(0x8, 0.0f, 1.0f) - .setMaskMeta(0x7)); addPlacementMapping(Blocks.stained_glass, new PlacementData(PlacementData.PlacementType.BLOCK)); addPlacementMapping(Blocks.ladder, new PlacementData(PlacementData.PlacementType.BLOCK, -1, -1, 3, 2, 5, 4)); addPlacementMapping( @@ -102,18 +103,15 @@ public void populatePlacementMaps() { addPlacementMapping( Blocks.fence_gate, new PlacementData(PlacementData.PlacementType.PLAYER, -1, -1, 2, 0, 1, 3).setMaskMeta(0x3)); - addPlacementMapping(Blocks.double_wooden_slab, new PlacementData(PlacementData.PlacementType.BLOCK)); - addPlacementMapping( - Blocks.wooden_slab, - new PlacementData(PlacementData.PlacementType.BLOCK).setOffset(0x8, 0.0f, 1.0f) - .setMaskMeta(0x7) - .setExtraClick(extraClickDoubleSlab)); addPlacementMapping( Blocks.anvil, new PlacementData(PlacementData.PlacementType.PLAYER, -1, -1, 1, 3, 0, 2).setMaskMeta(0x3)); addPlacementMapping(Blocks.stained_hardened_clay, new PlacementData(PlacementData.PlacementType.BLOCK)); addPlacementMapping(Blocks.carpet, new PlacementData(PlacementData.PlacementType.BLOCK)); addPlacementMapping(Blocks.stained_glass_pane, new PlacementData(PlacementData.PlacementType.BLOCK)); + addPlacementMapping( + GameRegistry.findBlock("etfuturum", "chain"), + new PlacementData(PlacementData.PlacementType.BLOCK, 0, 0, 2, 2, 1, 1).allowDirectClick()); addPlacementMapping( Items.wooden_door, new PlacementData(PlacementData.PlacementType.PLAYER, -1, -1, 3, 1, 2, 0).setMaskMeta(0x7)); @@ -163,6 +161,10 @@ public PlacementData getPlacementData(Block block, ItemStack itemStack) { return placementDataBlock; } + if (block instanceof BlockSlab && itemStack.getItem() instanceof ItemSlab) { + return block.isOpaqueCube() ? this.doubleSlab : this.halfSlab; + } + for (Class clazz : this.classPlacementMap.keySet()) { if (clazz.isInstance(block)) { return this.classPlacementMap.get(clazz); diff --git a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java index 4f1bf4d7..8bfe92f6 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java +++ b/src/main/java/com/github/lunatrius/schematica/client/renderer/RendererSchematicChunk.java @@ -14,18 +14,24 @@ import net.minecraft.profiler.Profiler; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; -import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.client.ForgeHooksClient; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL20; import com.github.lunatrius.core.util.vector.Vector3d; import com.github.lunatrius.core.util.vector.Vector3f; +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; +import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.client.renderer.shader.ShaderProgram; +import com.github.lunatrius.schematica.client.util.BlockToItemStack; import com.github.lunatrius.schematica.client.world.SchematicWorld; import com.github.lunatrius.schematica.handler.ConfigurationHandler; import com.github.lunatrius.schematica.proxy.ClientProxy; import com.github.lunatrius.schematica.reference.Constants; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; public class RendererSchematicChunk { @@ -145,8 +151,17 @@ public void updateRenderer() { } GL11.glNewList(this.glList + pass, GL11.GL_COMPILE); - renderBlocks(pass, minX, minY, minZ, maxX, maxY, maxZ); - GL11.glEndList(); + final int previousPass = ForgeHooksClient.getWorldRenderPass(); + try { + // Multipart uses Forge's chunk-building pass to choose the parts to render. + if (pass < 2) { + ForgeHooksClient.worldRenderPass = pass; + } + renderBlocks(pass, minX, minY, minZ, maxX, maxY, maxZ); + } finally { + ForgeHooksClient.worldRenderPass = previousPass; + GL11.glEndList(); + } GL11.glNewList(this.glListHighlight + pass, GL11.GL_COMPILE); int quadCount = RenderHelper.getQuadCount(); @@ -234,8 +249,9 @@ public void render(int renderPass) { } public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { - IBlockAccess mcWorld = this.minecraft.theWorld; + World mcWorld = this.minecraft.theWorld; RenderBlocks renderBlocks = RendererSchematicGlobal.INSTANCE.renderBlocks; + final boolean renderMicroblocks = renderPass < 2 && Mods.FORGE_MICROBLOCK; int x, y, z, wx, wy, wz; int sides; @@ -292,6 +308,15 @@ public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, || ConfigurationHandler.isExtraAirBlock(mcBlock); if (!isMcAirBlock) { + if (renderMicroblocks && block == mcBlock && MicroblockSupport.isMultipartBlock(block)) { + MicroblockSupport.renderMissingParts( + this.schematic, + mcWorld.getTileEntity(wx, wy, wz), + x, + y, + z, + renderPass); + } if (ConfigurationHandler.highlight && renderPass == 2) { if (isAirBlock && ConfigurationHandler.highlightAir) { zero.set(x, y, z); @@ -325,19 +350,16 @@ public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, if (ConfigurationHandler.drawLines) { RenderHelper.drawCuboidOutline(zero, size, sides, 1.0f, 0.0f, 0.0f, 0.25f); } - } else if (this.schematic.getBlockMetadata(x, y, z) - != mcWorld.getBlockMetadata(wx, wy, wz)) { - zero.set(x, y, z); - size.set(x + 1, y + 1, z + 1); - if (ConfigurationHandler.drawQuads) { - RenderHelper - .drawCuboidSurface(zero, size, sides, 0.75f, 0.35f, 0.0f, 0.25f); - } - if (ConfigurationHandler.drawLines) { - RenderHelper - .drawCuboidOutline(zero, size, sides, 0.75f, 0.35f, 0.0f, 0.25f); - } + } else if (!matchesBlockState(block, mcWorld, x, y, z, wx, wy, wz)) { + zero.set(x, y, z); + size.set(x + 1, y + 1, z + 1); + if (ConfigurationHandler.drawQuads) { + RenderHelper.drawCuboidSurface(zero, size, sides, 0.75f, 0.35f, 0.0f, 0.25f); + } + if (ConfigurationHandler.drawLines) { + RenderHelper.drawCuboidOutline(zero, size, sides, 0.75f, 0.35f, 0.0f, 0.25f); } + } } } else if (!isAirBlock) { if (ConfigurationHandler.highlight && renderPass == 2) { @@ -351,7 +373,7 @@ public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, } } - if (block != null && block.canRenderInPass(renderPass)) { + if (renderPass < 2 && block != null && block.canRenderInPass(renderPass)) { renderBlocks.renderBlockByRenderType(block, x, y, z); } } @@ -367,12 +389,29 @@ public void renderBlocks(int renderPass, int minX, int minY, int minZ, int maxX, this.minecraft.gameSettings.ambientOcclusion = ambientOcclusion; } + private boolean matchesBlockState(Block block, World world, int x, int y, int z, int wx, int wy, int wz) { + if (Mods.CARPENTERS_BLOCKS && CarpentersBlocksSupport.isCoverable(block)) { + return CarpentersBlocksSupport + .matches(block, this.schematic.getTileEntity(x, y, z), world.getTileEntity(wx, wy, wz)); + } + if (Mods.FORGE_MICROBLOCK && MicroblockSupport.isMultipartBlock(block) + && MicroblockSupport + .hasMissingOtherParts(this.schematic.getTileEntity(x, y, z), world.getTileEntity(wx, wy, wz))) { + return false; + } + return BlockToItemStack + .matchesSavedState(block, this.minecraft.thePlayer, world, wx, wy, wz, this.schematic, x, y, z) + && (!Mods.ARCHITECTURE_CRAFT || !ArchitectureCraftSupport.isShapeBlock(block) + || ArchitectureCraftSupport + .matchesPreview(world.getTileEntity(wx, wy, wz), this.schematic.getTileEntity(x, y, z), block)); + } + public void renderTileEntities(int renderPass) { if (renderPass != 0) { return; } - IBlockAccess mcWorld = this.minecraft.theWorld; + World mcWorld = this.minecraft.theWorld; int x, y, z; diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java index d23b0040..617fb0d6 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockList.java @@ -4,14 +4,24 @@ import java.util.List; import net.minecraft.block.Block; +import net.minecraft.block.BlockSlab; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemSlab; import net.minecraft.item.ItemStack; -import net.minecraft.util.MovingObjectPosition; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.Constants; -import com.github.lunatrius.core.entity.EntityHelper; +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; +import com.github.lunatrius.schematica.client.compat.CookingForBlockheadsSupport; +import com.github.lunatrius.schematica.client.compat.EnderIOSlabSupport; +import com.github.lunatrius.schematica.client.compat.MicroblockSupport; import com.github.lunatrius.schematica.client.world.SchematicWorld; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; public class BlockList { @@ -24,8 +34,6 @@ public List getList(final EntityPlayer player, final Schematic return blockList; } - final MovingObjectPosition movingObjectPosition = new MovingObjectPosition(player); - for (int y = 0; y < world.getHeight(); y++) { for (int x = 0; x < world.getWidth(); x++) { for (int z = 0; z < world.getLength(); z++) { @@ -42,52 +50,170 @@ public List getList(final EntityPlayer player, final Schematic final int wx = world.position.x + x; final int wy = world.position.y + y; final int wz = world.position.z + z; + if (Mods.FORGE_MICROBLOCK && MicroblockSupport.isMultipartBlock(block) + && MicroblockSupport.addMaterials( + world.getTileEntity(x, y, z), + mcWorld.getTileEntity(wx, wy, wz), + (stack, placed) -> addMaterial(blockList, stack, stack.stackSize, placed))) { + continue; + } final Block mcBlock = mcWorld.getBlock(wx, wy, wz); - final boolean isPlaced = block == mcBlock - && world.getBlockMetadata(x, y, z) == mcWorld.getBlockMetadata(wx, wy, wz); - - ItemStack stack = null; - - try { - stack = block.getPickBlock(movingObjectPosition, world, x, y, z, player); - } catch (final Exception e) { - Reference.logger.debug("Could not get the pick block for: {}", block, e); + final boolean carpenter = Mods.CARPENTERS_BLOCKS && CarpentersBlocksSupport.isCoverable(block); + final boolean garageDoor = carpenter && CarpentersBlocksSupport.isGarageDoor(block); + if (carpenter) { + CarpentersBlocksSupport.addMaterials( + world.getTileEntity(x, y, z), + block == mcBlock ? mcWorld.getTileEntity(wx, wy, wz) : null, + (material, placed) -> addMaterial(blockList, material, 1, placed)); + if (garageDoor && !CarpentersBlocksSupport.isGarageDoorHost(world.getTileEntity(x, y, z))) { + continue; + } } + final ItemStack stack = BlockToItemStack.getItemStack(player, block, world, x, y, z); if (stack == null || stack.getItem() == null) { Reference.logger.debug("Could not find the item for: {}", block); continue; } - final WrappedItemStack wrappedItemStack = findOrCreateWrappedItemStackFor(blockList, stack); - if (isPlaced) { - wrappedItemStack.placed++; + final ItemStack placed = block == mcBlock && (carpenter + || BlockToItemStack.matchesSavedState(block, player, mcWorld, wx, wy, wz, world, x, y, z)) + ? BlockToItemStack.getItemStack(player, mcBlock, mcWorld, wx, wy, wz) + : null; + final boolean complete = placed != null && BlockToItemStack.matches(placed, stack) + && (!garageDoor || CarpentersBlocksSupport.isGarageDoorHost(mcWorld.getTileEntity(wx, wy, wz))); + final WrappedItemStack blockMaterial = addMaterial(blockList, stack, 1, complete); + if (!complete) { + blockMaterial.pickedBlocksNeeded++; + } + if (block instanceof BlockSlab && block.isOpaqueCube() && stack.getItem() instanceof ItemSlab) { + if (complete || (BlockToItemStack.matchesHalfSlab(mcWorld, wx, wy, wz, stack) + && BlockToItemStack.matchesPaint(block, mcWorld, wx, wy, wz, world, x, y, z))) { + blockMaterial.placed++; + } else { + blockMaterial.pickedBlocksNeeded++; + } + blockMaterial.total++; + } + if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeBlock(block)) { + final ItemStack secondary = ArchitectureCraftSupport + .getSecondaryItem(world.getTileEntity(x, y, z)); + if (secondary != null) { + final ItemStack actual = block == mcBlock + ? ArchitectureCraftSupport.getSecondaryItem(mcWorld.getTileEntity(wx, wy, wz)) + : null; + addMaterial( + blockList, + secondary, + secondary.stackSize, + actual != null && BlockToItemStack.matches(actual, secondary)); + } + } + if (Mods.COOKING_FOR_BLOCKHEADS && block.hasTileEntity(world.getBlockMetadata(x, y, z))) { + CookingForBlockheadsSupport + .addDyeRequirement(world, x, y, z, mcWorld, wx, wy, wz, (stackDye, dyed) -> { + final WrappedItemStack dye = addMaterial(blockList, stackDye, 1, dyed); + if (!dyed) { + dye.kitchenDyesNeeded++; + } + }); } - wrappedItemStack.total++; } } } for (WrappedItemStack wrappedItemStack : blockList) { - if (player.capabilities.isCreativeMode) wrappedItemStack.inventory = -1; - else wrappedItemStack.inventory = EntityHelper.getItemCountInInventory( - player.inventory, - wrappedItemStack.itemStack.getItem(), - wrappedItemStack.itemStack.getItemDamage()); + final ItemStack target = wrappedItemStack.itemStack; + if (player.capabilities.isCreativeMode) { + wrappedItemStack.inventory = -1; + } else { + for (ItemStack stack : player.inventory.mainInventory) { + if (stack != null && BlockToItemStack.matches(stack, target)) { + wrappedItemStack.inventory += stack.stackSize; + } + } + } } + if (!player.capabilities.isCreativeMode) { + addLooseBlockStock(blockList, player.inventory.mainInventory); + if (Mods.COOKING_FOR_BLOCKHEADS && CookingForBlockheadsSupport.SUPPORTS_DYE_SUBSTITUTES) { + addKitchenDyeSubstitutes(blockList, player.inventory.mainInventory); + } + } return blockList; } + private void addLooseBlockStock(List materials, ItemStack[] inventory) { + for (WrappedItemStack row : materials) { + if (row.pickedBlocksNeeded == 0 || !(row.itemStack.getItem() instanceof ItemBlock)) { + continue; + } + int available = 0; + for (ItemStack stack : inventory) { + if (stack != null && matchesOnlyBlockStock(stack, row.itemStack)) { + available += stack.stackSize; + } + } + if (available == 0) { + continue; + } + // Tagged stock may be required as an exact ingredient in another row. + for (WrappedItemStack material : materials) { + if (matchesOnlyBlockStock(material.itemStack, row.itemStack)) { + available -= Math.min(material.inventory, material.total - material.placed); + } + } + row.inventory += Math.min(Math.max(available, 0), row.pickedBlocksNeeded); + } + } + + private static boolean matchesOnlyBlockStock(ItemStack candidate, ItemStack target) { + return BlockToItemStack.matchesBlockStock(candidate, target) && !BlockToItemStack.matches(candidate, target); + } + + private void addKitchenDyeSubstitutes(List materials, ItemStack[] inventory) { + for (WrappedItemStack dye : materials) { + if (dye.kitchenDyesNeeded == 0) { + continue; + } + final int damage = dye.itemStack.getItemDamage(); + int available = 0; + for (ItemStack stack : inventory) { + if (stack != null && !BlockToItemStack.matches(stack, dye.itemStack) + && CookingForBlockheadsSupport.getDyeDamage(stack) == damage) { + available += stack.stackSize; + } + } + // Reserve dyes that a different row needs as exact ingredients before counting substitutes. + for (WrappedItemStack material : materials) { + if (material != dye && CookingForBlockheadsSupport.getDyeDamage(material.itemStack) == damage) { + available -= Math.min(material.inventory, material.total - material.placed); + } + } + dye.inventory += Math.min(Math.max(available, 0), dye.kitchenDyesNeeded); + } + } + + private WrappedItemStack addMaterial(List blockList, ItemStack stack, int count, boolean placed) { + final WrappedItemStack entry = findOrCreateWrappedItemStackFor(blockList, stack); + if (placed) { + entry.placed += count; + } + entry.total += count; + return entry; + } + private WrappedItemStack findOrCreateWrappedItemStackFor(final List blockList, final ItemStack itemStack) { for (final WrappedItemStack wrappedItemStack : blockList) { - if (wrappedItemStack.itemStack.isItemEqual(itemStack)) { + if (BlockToItemStack.matches(wrappedItemStack.itemStack, itemStack)) { return wrappedItemStack; } } final WrappedItemStack wrappedItemStack = new WrappedItemStack(itemStack.copy()); + wrappedItemStack.itemStack.stackSize = 1; blockList.add(wrappedItemStack); return wrappedItemStack; } @@ -98,6 +224,8 @@ public static class WrappedItemStack { public int placed; public int total; public int inventory; + private int kitchenDyesNeeded; + private int pickedBlocksNeeded; public WrappedItemStack(final ItemStack itemStack) { this(itemStack, 0, 0); @@ -110,8 +238,49 @@ public WrappedItemStack(final ItemStack itemStack, final int placed, final int t } public String getItemStackDisplayName() { - return this.itemStack.getItem() - .getItemStackDisplayName(this.itemStack); + final String name = this.itemStack.getDisplayName(); + if (Mods.ARCHITECTURE_CRAFT) { + final String material = ArchitectureCraftSupport.getMaterialName(this.itemStack); + if (!material.isEmpty()) { + return name + " (" + material + ")"; + } + } + return name; + } + + public String getExportDisplayName() { + final String name = getItemStackDisplayName(); + if (Mods.ENDER_IO && EnderIOSlabSupport.isPaintedSlab(Block.getBlockFromItem(this.itemStack.getItem()))) { + return name + " (" + EnderIOSlabSupport.getPaintName(this.itemStack) + ")"; + } + if (this.itemStack.hasTagCompound() && BlockToItemStack.isBanner(this.itemStack)) { + final List patterns = getBannerPatternNames(); + if (!patterns.isEmpty()) { + return name + " (" + String.join(", ", patterns) + ")"; + } + } + return name; + } + + private List getBannerPatternNames() { + final List names = new ArrayList<>(); + final ItemStack sample = this.itemStack.copy(); + final NBTTagCompound tile = sample.getTagCompound() + .getCompoundTag("BlockEntityTag"); + final NBTTagList patterns = tile.getTagList("Patterns", Constants.NBT.TAG_COMPOUND); + // Et Futurum's tooltip lists six patterns, but imported banners can render more layers. + final int tooltipLimit = 6; + for (int start = 0; start < patterns.tagCount(); start += tooltipLimit) { + final NBTTagList batch = new NBTTagList(); + final int end = Math.min(start + tooltipLimit, patterns.tagCount()); + for (int i = start; i < end; i++) { + batch.appendTag(patterns.getCompoundTagAt(i)); + } + tile.setTag("Patterns", batch); + sample.getItem() + .addInformation(sample, null, names, false); + } + return names; } public String getFormattedAmount() { diff --git a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java index 89931918..c1202701 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java +++ b/src/main/java/com/github/lunatrius/schematica/client/util/BlockToItemStack.java @@ -1,27 +1,87 @@ package com.github.lunatrius.schematica.client.util; +import java.util.Objects; + import net.minecraft.block.Block; +import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTUtil; +import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.common.util.Constants; -import com.github.lunatrius.schematica.client.world.SchematicWorld; +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.client.compat.CarpentersBlocksSupport; +import com.github.lunatrius.schematica.client.compat.EnderIOSlabSupport; +import com.github.lunatrius.schematica.client.compat.MicroblockSupport; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; +import com.google.common.collect.Iterables; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.minecraft.MinecraftProfileTexture; +import com.mojang.authlib.properties.Property; + +import cpw.mods.fml.common.registry.GameRegistry; public class BlockToItemStack { - public static ItemStack getItemStack(final EntityPlayer player, final Block block, final SchematicWorld world, - final int x, final int y, final int z) { + private static final int PLAYER_SKULL = 3; + private static final String SKULL_OWNER = "SkullOwner"; + + public static ItemStack getItemStack(final EntityPlayer player, final Block block, final World world, final int x, + final int y, final int z) { try { + if (Mods.CARPENTERS_BLOCKS && CarpentersBlocksSupport.isSlope(block)) { + return CarpentersBlocksSupport.getSlopeItem(block, world.getTileEntity(x, y, z)); + } + if (Mods.ENDER_IO && EnderIOSlabSupport.isPaintedSlab(block)) { + return EnderIOSlabSupport.getItem(world.getTileEntity(x, y, z)); + } + if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeBlock(block)) { + final ItemStack shape = ArchitectureCraftSupport.getItem(world.getTileEntity(x, y, z), block); + if (shape != null) { + return shape; + } + } + if (block == Blocks.skull && world.getTileEntity(x, y, z) instanceof TileEntitySkull skull) { + final ItemStack item = new ItemStack(Items.skull, 1, skull.func_145904_a()); + final GameProfile owner = skull.func_152108_a(); + if (isPlayerHead(item) && owner != null) { + final NBTTagCompound ownerTag = new NBTTagCompound(); + NBTUtil.func_152460_a(ownerTag, owner); + item.setTagInfo(SKULL_OWNER, ownerTag); + } + return item; + } final ItemStack itemStack = block.getPickBlock( - new MovingObjectPosition(x, y, z, 0, Vec3.createVectorHelper(0, 0, 0)), + new MovingObjectPosition(x, y, z, 1, Vec3.createVectorHelper(x + 0.5, y + 1.0, z + 0.5)), world, x, y, z, player); - if (itemStack != null) { + if (itemStack != null && itemStack.getItem() != null) { + // Ignore facing damage when a non-subtyped item places the same metadata as its default stack. + if (itemStack.getItemDamage() != 0 && itemStack.getItem() instanceof ItemBlock + && !itemStack.getHasSubtypes() + && itemStack.getItem() + .getMetadata(itemStack.getItemDamage()) + == itemStack.getItem() + .getMetadata(0)) { + final ItemStack normalized = itemStack.copy(); + normalized.setItemDamage(0); + return normalized; + } return itemStack; } } catch (final Exception e) { @@ -30,4 +90,173 @@ public static ItemStack getItemStack(final EntityPlayer player, final Block bloc return null; } + + public static boolean matches(ItemStack stack, ItemStack target) { + return matches(stack, target, false); + } + + public static boolean matchesBlockStock(ItemStack stack, ItemStack target) { + return matches(stack, target, true); + } + + private static boolean matches(ItemStack stack, ItemStack target, boolean blockStock) { + if (stack.getItem() != target.getItem()) { + return false; + } + if ((stack.hasTagCompound() || target.hasTagCompound()) && isBanner(target)) { + return matchesBanner(stack, target); + } + if (stack.getItemDamage() != target.getItemDamage()) { + return false; + } + if (isPlayerHead(target)) { + try { + return matchesHeadOwner(getHeadOwner(stack), getHeadOwner(target)); + } catch (IllegalArgumentException e) { + return false; + } + } + if (Mods.FORGE_MICROBLOCK && MicroblockSupport.isMicroblockItem(target)) { + return MicroblockSupport.itemsMatch(stack, target); + } + if (Mods.ARCHITECTURE_CRAFT && ArchitectureCraftSupport.isShapeItem(target)) { + return ArchitectureCraftSupport.itemsMatch(stack, target); + } + if (Mods.ENDER_IO && EnderIOSlabSupport.isPaintedSlab(Block.getBlockFromItem(target.getItem()))) { + return EnderIOSlabSupport.itemsMatch(stack, target); + } + // Ordinary block picks can omit per-item data from stock, such as a dropped machine's configuration. + return ItemStack.areItemStackTagsEqual(stack, target) || (hasOnlyCosmeticTags(target) + && (hasOnlyCosmeticTags(stack) || (blockStock && target.getItem() instanceof ItemBlock))); + } + + static boolean isBanner(ItemStack stack) { + return stack.getItem() == GameRegistry.findItem("etfuturum", "banner"); + } + + private static boolean matchesBanner(ItemStack stack, ItemStack target) { + final NBTTagCompound actual = stack.hasTagCompound() ? stack.getTagCompound() + .getCompoundTag("BlockEntityTag") : new NBTTagCompound(); + final NBTTagCompound expected = target.hasTagCompound() ? target.getTagCompound() + .getCompoundTag("BlockEntityTag") : new NBTTagCompound(); + if (bannerColor(stack, actual) != bannerColor(target, expected)) { + return false; + } + final NBTTagList patterns = actual.getTagList("Patterns", Constants.NBT.TAG_COMPOUND); + final NBTTagList expectedPatterns = expected.getTagList("Patterns", Constants.NBT.TAG_COMPOUND); + return patterns.equals(expectedPatterns) || (patterns.tagCount() == 0 && expectedPatterns.tagCount() == 0); + } + + private static int bannerColor(ItemStack stack, NBTTagCompound tile) { + return tile.hasKey("Base", Constants.NBT.TAG_ANY_NUMERIC) ? tile.getInteger("Base") + : stack.getItemDamage() & 15; + } + + private static boolean isPlayerHead(ItemStack stack) { + return stack.getItem() == Items.skull && stack.getItemDamage() == PLAYER_SKULL; + } + + private static GameProfile getHeadOwner(ItemStack stack) { + final NBTTagCompound tag = stack.getTagCompound(); + if (tag == null) { + return null; + } + if (tag.hasKey(SKULL_OWNER, 10)) { + return NBTUtil.func_152459_a(tag.getCompoundTag(SKULL_OWNER)); + } + final String name = tag.hasKey(SKULL_OWNER, 8) ? tag.getString(SKULL_OWNER) : ""; + return name.isEmpty() ? null : new GameProfile(null, name); + } + + private static boolean matchesHeadOwner(GameProfile actual, GameProfile expected) { + if (actual == null || expected == null) { + return actual == expected; + } + // A legacy name cannot identify a saved UUID, particularly on heads with custom textures. + if (!Objects.equals(actual.getId(), expected.getId()) || (actual.getId() == null && !actual.getName() + .equalsIgnoreCase(expected.getName()))) { + return false; + } + // Vanilla renders the first texture property. Its timestamp and cape can change independently of the skin. + final Property actualTexture = Iterables.getFirst( + actual.getProperties() + .get("textures"), + null); + final Property expectedTexture = Iterables.getFirst( + expected.getProperties() + .get("textures"), + null); + if (actualTexture == null || expectedTexture == null) { + return actualTexture == expectedTexture; + } + if (actualTexture.getValue() + .equals(expectedTexture.getValue())) { + return true; + } + try { + return Objects.equals(getSkinUrl(actual), getSkinUrl(expected)); + } catch (RuntimeException e) { + // Some malformed texture payloads make Authlib throw instead of returning an empty map. + return false; + } + } + + private static String getSkinUrl(GameProfile owner) { + final MinecraftProfileTexture skin = Minecraft.getMinecraft() + .func_152347_ac() + .getTextures(owner, false) + .get(MinecraftProfileTexture.Type.SKIN); + return skin == null ? null : skin.getUrl(); + } + + private static boolean hasOnlyCosmeticTags(ItemStack stack) { + final NBTTagCompound tag = stack.getTagCompound(); + if (tag == null) { + return true; + } + // The vanilla anvil writes RepairCost when renaming an item. + final int cosmeticKeys = (tag.hasKey("display", 10) ? 1 : 0) + (tag.hasKey("RepairCost", 3) ? 1 : 0); + return tag.func_150296_c() + .size() == cosmeticKeys; + } + + public static boolean matchesMetadata(Block block, int actual, int saved) { + return actual == saved || (block.getClass() + .getName() + .equals("gregtech.common.blocks.GTBlockOre") && block.damageDropped(actual) == block.damageDropped(saved)); + } + + /** Compares base placement state once both locations have the same block. */ + public static boolean matchesSavedState(Block block, EntityPlayer player, World world, int x, int y, int z, + World schematic, int localX, int localY, int localZ) { + final int savedMetadata = schematic.getBlockMetadata(localX, localY, localZ); + if (!matchesMetadata(block, world.getBlockMetadata(x, y, z), savedMetadata) + || !matchesPaint(block, world, x, y, z, schematic, localX, localY, localZ)) { + return false; + } + if (block != Blocks.skull && (!block.hasTileEntity(savedMetadata) || !isBannerBlock(block))) { + return true; + } + final ItemStack actual = getItemStack(player, block, world, x, y, z); + final ItemStack expected = getItemStack(player, block, schematic, localX, localY, localZ); + return actual != null && expected != null && matches(actual, expected); + } + + private static boolean isBannerBlock(Block block) { + final Item banner = GameRegistry.findItem("etfuturum", "banner"); + return banner != null && block == Block.getBlockFromItem(banner); + } + + public static boolean matchesPaint(Block block, IBlockAccess world, int x, int y, int z, IBlockAccess schematic, + int localX, int localY, int localZ) { + return !Mods.ENDER_IO || !EnderIOSlabSupport.isPaintedSlab(block) + || EnderIOSlabSupport + .matchesPaint(world.getTileEntity(x, y, z), schematic.getTileEntity(localX, localY, localZ)); + } + + public static boolean matchesHalfSlab(World world, int x, int y, int z, ItemStack slab) { + final Block block = world.getBlock(x, y, z); + return block == Block.getBlockFromItem(slab.getItem()) && !block.isOpaqueCube() + && (world.getBlockMetadata(x, y, z) & 7) == slab.getItemDamage(); + } } diff --git a/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java b/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java index 42c4f52f..6f0ff99f 100644 --- a/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java +++ b/src/main/java/com/github/lunatrius/schematica/client/world/SchematicWorld.java @@ -20,8 +20,10 @@ import com.github.lunatrius.core.util.vector.Vector3f; import com.github.lunatrius.core.util.vector.Vector3i; +import com.github.lunatrius.schematica.FileFilterSchematic; import com.github.lunatrius.schematica.api.ISchematic; -import com.github.lunatrius.schematica.handler.ConfigurationHandler; +import com.github.lunatrius.schematica.client.compat.ArchitectureCraftSupport; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; import com.github.lunatrius.schematica.world.chunk.ChunkProviderSchematic; import com.github.lunatrius.schematica.world.storage.SaveHandlerSchematic; @@ -71,11 +73,7 @@ public SchematicWorld(ISchematic schematic) { public SchematicWorld(ISchematic schematic, String filename) { this(schematic); - if (ConfigurationHandler.useSchematicplusFormat) { - this.name = filename.replace(".schemplus", ""); - } else { - this.name = filename.replace(".schematic", ""); - } + this.name = FileFilterSchematic.stripExtension(filename); } @Override @@ -84,6 +82,10 @@ public Block getBlock(int x, int y, int z) { return Blocks.air; } + return getBlockIncludingHiddenLayers(x, y, z); + } + + public Block getBlockIncludingHiddenLayers(int x, int y, int z) { return this.schematic.getBlock(x, y, z); } @@ -230,6 +232,24 @@ public void refreshChests() { } public void flip(ForgeDirection direction) { + transformAllLayers(() -> flipSchematic(direction)); + } + + public void rotate(ForgeDirection direction) { + transformAllLayers(() -> rotateSchematic(direction)); + } + + private void transformAllLayers(Runnable transform) { + final boolean wasRenderingLayer = this.isRenderingLayer; + this.isRenderingLayer = false; + try { + transform.run(); + } finally { + this.isRenderingLayer = wasRenderingLayer; + } + } + + private void flipSchematic(ForgeDirection direction) { final ItemStack icon = this.schematic.getIcon(); final int width = this.schematic.getWidth(); final int height = this.schematic.getHeight(); @@ -310,10 +330,11 @@ public void flip(ForgeDirection direction) { } this.schematic = schematicFlipped; + transformShapeTiles(direction, true); refreshChests(); } - public void rotate(ForgeDirection direction) { + private void rotateSchematic(ForgeDirection direction) { final ItemStack icon = this.schematic.getIcon(); final int width = this.schematic.getWidth(); final int height = this.schematic.getHeight(); @@ -439,6 +460,16 @@ public void rotate(ForgeDirection direction) { break; default: Reference.logger.debug("Incorrect direction given to rotate function!"); + return; + } + transformShapeTiles(direction, false); + } + + private void transformShapeTiles(ForgeDirection direction, boolean mirror) { + if (Mods.ARCHITECTURE_CRAFT) { + for (TileEntity tile : this.schematic.getTileEntities()) { + ArchitectureCraftSupport.transform(tile, direction, mirror); + } } } diff --git a/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaDownload.java b/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaDownload.java index a3dd2ef8..b2f8f872 100644 --- a/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaDownload.java +++ b/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaDownload.java @@ -16,12 +16,9 @@ import com.github.lunatrius.schematica.FileFilterSchematic; import com.github.lunatrius.schematica.Schematica; import com.github.lunatrius.schematica.api.ISchematic; -import com.github.lunatrius.schematica.handler.ConfigurationHandler; import com.github.lunatrius.schematica.handler.DownloadHandler; -import com.github.lunatrius.schematica.network.transfer.SchematicTransfer; import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.reference.Reference; -import com.github.lunatrius.schematica.util.FileUtils; import com.github.lunatrius.schematica.world.schematic.SchematicFormat; public class CommandSchematicaDownload extends CommandSchematicaBase { @@ -70,23 +67,18 @@ public void processCommand(ICommandSender sender, String[] args) { throw new CommandException(Names.Command.Download.Message.PLAYERS_ONLY); } - final String filename; - if (ConfigurationHandler.useSchematicplusFormat) { - filename = args[0] + ".schemplus"; - } else { - filename = args[0] + ".schematic"; - } - final File directory = Schematica.proxy.getPlayerSchematicDirectory(player, true); - if (!FileUtils.contains(directory, filename)) { - Reference.logger.error("{} has tried to download the file {}", player.getDisplayName(), filename); + final File schematicFile = FileFilterSchematic.resolve(directory, args[0]); + if (schematicFile == null) { + Reference.logger.error("{} has tried to download the file {}", player.getDisplayName(), args[0]); throw new CommandException(Names.Command.Download.Message.DOWNLOAD_FAILED); } - final ISchematic schematic = SchematicFormat.readFromFile(directory, filename); + final String filename = schematicFile.getName(); + final ISchematic schematic = SchematicFormat.readFromFile(schematicFile); if (schematic != null) { - DownloadHandler.INSTANCE.transferMap.put(player, new SchematicTransfer(schematic, filename)); + DownloadHandler.INSTANCE.startDownload(player, schematic, filename); sender.addChatMessage( new ChatComponentTranslation(Names.Command.Download.Message.DOWNLOAD_STARTED, filename)); } else { diff --git a/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaRemove.java b/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaRemove.java index e8dd49de..d3c2d0d2 100644 --- a/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaRemove.java +++ b/src/main/java/com/github/lunatrius/schematica/command/CommandSchematicaRemove.java @@ -14,10 +14,10 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; +import com.github.lunatrius.schematica.FileFilterSchematic; import com.github.lunatrius.schematica.Schematica; import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.reference.Reference; -import com.github.lunatrius.schematica.util.FileUtils; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; @@ -67,11 +67,10 @@ public void processCommand(ICommandSender sender, String[] arguments) { } } - String filename = String.format("%s.schematic", name); File schematicDirectory = Schematica.proxy.getPlayerSchematicDirectory(player, true); - File file = new File(schematicDirectory, filename); - if (!FileUtils.contains(schematicDirectory, file)) { - Reference.logger.error("{} has tried to download the file {}", player.getDisplayName(), filename); + File file = FileFilterSchematic.resolve(schematicDirectory, name); + if (file == null) { + Reference.logger.error("{} has tried to remove the file {}", player.getDisplayName(), name); throw new CommandException(Names.Command.Remove.Message.SCHEMATIC_NOT_FOUND); } diff --git a/src/main/java/com/github/lunatrius/schematica/handler/ConfigurationHandler.java b/src/main/java/com/github/lunatrius/schematica/handler/ConfigurationHandler.java index 1d16f873..80263242 100644 --- a/src/main/java/com/github/lunatrius/schematica/handler/ConfigurationHandler.java +++ b/src/main/java/com/github/lunatrius/schematica/handler/ConfigurationHandler.java @@ -58,6 +58,7 @@ public class ConfigurationHandler { public static final boolean SERVERSIDE_SCHEMATICS_ENABLED_DEFAULT = true; public static boolean showDebugInfo = SHOW_DEBUG_INFO_DEFAULT; + /** Loaded for old configs. Saving and loading no longer branch on this flag. */ public static boolean useSchematicplusFormat = EXTENDED_ID_FORMAT_DEFAULT; public static boolean enableAlpha = ENABLE_ALPHA_DEFAULT; public static float alpha = (float) ALPHA_DEFAULT; @@ -293,6 +294,7 @@ public static void loadConfiguration() { EXTENDED_ID_FORMAT_DEFAULT, Names.Config.EXTENDED_ID_FORMAT_DESC); propUseSchematicplusFormat.setLanguageKey(Names.Config.LANG_PREFIX + "." + Names.Config.EXTENDED_ID_FORMAT); + propUseSchematicplusFormat.setShowInGui(false); useSchematicplusFormat = propUseSchematicplusFormat.getBoolean(EXTENDED_ID_FORMAT_DEFAULT); propSortType = configuration diff --git a/src/main/java/com/github/lunatrius/schematica/handler/DownloadHandler.java b/src/main/java/com/github/lunatrius/schematica/handler/DownloadHandler.java index 8070088c..108486d4 100644 --- a/src/main/java/com/github/lunatrius/schematica/handler/DownloadHandler.java +++ b/src/main/java/com/github/lunatrius/schematica/handler/DownloadHandler.java @@ -4,6 +4,8 @@ import java.util.Map; import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.StatCollector; import com.github.lunatrius.schematica.api.ISchematic; import com.github.lunatrius.schematica.network.PacketHandler; @@ -12,6 +14,7 @@ import com.github.lunatrius.schematica.network.message.MessageDownloadEnd; import com.github.lunatrius.schematica.network.transfer.SchematicTransfer; import com.github.lunatrius.schematica.reference.Constants; +import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.reference.Reference; import cpw.mods.fml.common.eventhandler.SubscribeEvent; @@ -19,11 +22,14 @@ public class DownloadHandler { + public static final int PROTOCOL_VERSION = 2; public static final DownloadHandler INSTANCE = new DownloadHandler(); - public ISchematic schematic = null; + // Version advertised by the connected server via MessageCapabilities. + public int serverProtocolVersion; + public ISchematic schematic; - public final Map transferMap = new LinkedHashMap<>(); + private final Map transferMap = new LinkedHashMap<>(); private DownloadHandler() {} @@ -36,7 +42,33 @@ public void onServerTick(TickEvent.ServerTickEvent event) { processQueue(); } - private void processQueue() { + public void startDownload(EntityPlayerMP player, ISchematic schematic, String name) { + final SchematicTransfer transfer = new SchematicTransfer(schematic, name); + synchronized (this) { + this.transferMap.put(player, transfer); + } + } + + public synchronized void cancelDownload(EntityPlayerMP player) { + this.transferMap.remove(player); + } + + public synchronized void confirmBegin(EntityPlayerMP player, int protocolVersion) { + final SchematicTransfer transfer = this.transferMap.get(player); + if (transfer != null && transfer.state == SchematicTransfer.State.BEGIN) { + transfer.clientProtocolVersion = protocolVersion; + transfer.setState(SchematicTransfer.State.CHUNK_WAIT); + } + } + + public synchronized void confirmChunk(EntityPlayerMP player, int x, int y, int z) { + final SchematicTransfer transfer = this.transferMap.get(player); + if (transfer != null && transfer.state == SchematicTransfer.State.CHUNK) { + transfer.confirmChunk(x, y, z); + } + } + + private synchronized void processQueue() { if (this.transferMap.isEmpty()) { return; } @@ -49,42 +81,54 @@ private void processQueue() { if (transfer == null) { return; } + this.transferMap.put(player, transfer); if (!transfer.state.isWaiting()) { if (++transfer.timeout >= Constants.Network.TIMEOUT) { if (++transfer.retries >= Constants.Network.RETRIES) { Reference.logger.warn("{}'s download was dropped!", player.getDisplayName()); + this.transferMap.remove(player); return; } Reference.logger .warn("{}'s download timed out, retrying (#{})", player.getDisplayName(), transfer.retries); - sendChunk(player, transfer); + if (transfer.state == SchematicTransfer.State.BEGIN) { + sendBegin(player, transfer); + } else { + sendChunk(player, transfer); + } transfer.timeout = 0; } } else if (transfer.state == SchematicTransfer.State.BEGIN_WAIT) { + transfer.setState(SchematicTransfer.State.BEGIN); sendBegin(player, transfer); } else if (transfer.state == SchematicTransfer.State.CHUNK_WAIT) { + if (transfer.clientProtocolVersion != PROTOCOL_VERSION) { + // Translate on the server because old clients do not have this key. + player.addChatMessage( + new ChatComponentText( + StatCollector.translateToLocalFormatted( + Names.Command.Download.Message.DOWNLOAD_REQUIRES_UPDATE, + transfer.name))); + this.transferMap.remove(player); + return; + } + transfer.setState(SchematicTransfer.State.CHUNK); sendChunk(player, transfer); } else if (transfer.state == SchematicTransfer.State.END_WAIT) { + this.transferMap.remove(player); sendEnd(player, transfer); - return; } - - this.transferMap.put(player, transfer); } private void sendBegin(EntityPlayerMP player, SchematicTransfer transfer) { - transfer.setState(SchematicTransfer.State.BEGIN); - MessageDownloadBegin message = new MessageDownloadBegin(transfer.schematic); PacketHandler.INSTANCE.sendTo(message, player); } private void sendChunk(EntityPlayerMP player, SchematicTransfer transfer) { - transfer.setState(SchematicTransfer.State.CHUNK); - Reference.logger.trace("Sending chunk {},{},{}", transfer.baseX, transfer.baseY, transfer.baseZ); MessageDownloadChunk message = new MessageDownloadChunk( transfer.schematic, diff --git a/src/main/java/com/github/lunatrius/schematica/handler/PlayerHandler.java b/src/main/java/com/github/lunatrius/schematica/handler/PlayerHandler.java index 8cfb4a37..b01bcfb8 100644 --- a/src/main/java/com/github/lunatrius/schematica/handler/PlayerHandler.java +++ b/src/main/java/com/github/lunatrius/schematica/handler/PlayerHandler.java @@ -33,8 +33,8 @@ public void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { @SubscribeEvent public void onPlayerLoggedOut(PlayerEvent.PlayerLoggedOutEvent event) { - if (event.player instanceof EntityPlayerMP) { - DownloadHandler.INSTANCE.transferMap.remove(event.player); + if (event.player instanceof EntityPlayerMP player) { + DownloadHandler.INSTANCE.cancelDownload(player); } } } diff --git a/src/main/java/com/github/lunatrius/schematica/handler/client/InputHandler.java b/src/main/java/com/github/lunatrius/schematica/handler/client/InputHandler.java index 3a6bbfa8..e8f4fbbf 100644 --- a/src/main/java/com/github/lunatrius/schematica/handler/client/InputHandler.java +++ b/src/main/java/com/github/lunatrius/schematica/handler/client/InputHandler.java @@ -12,13 +12,13 @@ import org.lwjgl.input.Keyboard; -import com.github.lunatrius.schematica.Schematica; import com.github.lunatrius.schematica.client.gui.control.GuiSchematicControl; import com.github.lunatrius.schematica.client.gui.load.GuiSchematicLoad; import com.github.lunatrius.schematica.client.gui.save.GuiSchematicSave; import com.github.lunatrius.schematica.client.renderer.RendererSchematicGlobal; import com.github.lunatrius.schematica.client.world.SchematicWorld; import com.github.lunatrius.schematica.proxy.ClientProxy; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.reference.Reference; @@ -31,15 +31,15 @@ public class InputHandler { private static final KeyBinding KEY_BINDING_LOAD = new KeyBinding( Names.Keys.LOAD, - Schematica.proxy.GTNH ? Keyboard.KEY_NONE : Keyboard.KEY_DIVIDE, + Mods.GTNH ? Keyboard.KEY_NONE : Keyboard.KEY_DIVIDE, Names.Keys.CATEGORY); private static final KeyBinding KEY_BINDING_SAVE = new KeyBinding( Names.Keys.SAVE, - Schematica.proxy.GTNH ? Keyboard.KEY_NONE : Keyboard.KEY_MULTIPLY, + Mods.GTNH ? Keyboard.KEY_NONE : Keyboard.KEY_MULTIPLY, Names.Keys.CATEGORY); private static final KeyBinding KEY_BINDING_CONTROL = new KeyBinding( Names.Keys.CONTROL, - Schematica.proxy.GTNH ? Keyboard.KEY_NONE : Keyboard.KEY_SUBTRACT, + Mods.GTNH ? Keyboard.KEY_NONE : Keyboard.KEY_SUBTRACT, Names.Keys.CATEGORY); private static final KeyBinding KEY_BINDING_LAYER_INC = new KeyBinding( Names.Keys.LAYER_INC, diff --git a/src/main/java/com/github/lunatrius/schematica/nbt/CarpentersBlocksNBT.java b/src/main/java/com/github/lunatrius/schematica/nbt/CarpentersBlocksNBT.java new file mode 100644 index 00000000..989e4829 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/nbt/CarpentersBlocksNBT.java @@ -0,0 +1,41 @@ +package com.github.lunatrius.schematica.nbt; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.Constants; + +import com.carpentersblocks.tileentity.TEBase; + +import cpw.mods.fml.common.registry.GameData; + +public final class CarpentersBlocksNBT { + + private static final String ITEM_REGISTRY_NAME = "cbUniqueId"; + + private CarpentersBlocksNBT() {} + + public static void remapAttributeItems(NBTTagCompound tile) { + final NBTTagList attributes = tile.getTagList(TEBase.TAG_ATTR_LIST, Constants.NBT.TAG_COMPOUND); + for (int i = 0; i < attributes.tagCount(); i++) { + final NBTTagCompound attribute = attributes.getCompoundTagAt(i); + final String name = attribute.getString(ITEM_REGISTRY_NAME); + if (!name.isEmpty()) { + final Item item = GameData.getItemRegistry() + .getObject(name); + // EndlessIDs can prefer idExt over the vanilla id. Copy the current stack's ID encoding only. + attribute.removeTag("idExt"); + if (item == null) { + attribute.setShort("id", (short) 0); + continue; + } + final NBTTagCompound stack = new ItemStack(item).writeToNBT(new NBTTagCompound()); + attribute.setTag("id", stack.getTag("id")); + if (stack.hasKey("idExt")) { + attribute.setTag("idExt", stack.getTag("idExt")); + } + } + } + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/nbt/ForgeMultipart.java b/src/main/java/com/github/lunatrius/schematica/nbt/ForgeMultipart.java index 9e3516ba..e6a0d672 100644 --- a/src/main/java/com/github/lunatrius/schematica/nbt/ForgeMultipart.java +++ b/src/main/java/com/github/lunatrius/schematica/nbt/ForgeMultipart.java @@ -10,10 +10,10 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.Constants; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Loader; import cpw.mods.fml.relauncher.ReflectionHelper; import scala.Option; import scala.collection.Iterable; @@ -28,15 +28,18 @@ public class ForgeMultipart { private static Map instancesTypeMap; private static Method methodMaterialID; private static Method methodCreatePart; + private static Object instanceMultiPartRegistry; + private static Method methodLoadRegisteredPart; private static Method methodLoad; private static Method methodOnPartChanged; + private static Class microblockPart; private static Object instanceMultipartGenerator$; private static Method methodGenerateCompositeTile; private static Method methodLoadParts; private static Method methodCreateFromNBT; public static void init() { - enabled = Loader.isModLoaded("ForgeMultipart"); + enabled = Mods.FORGE_MULTIPART; client = FMLCommonHandler.instance() .getSide() .isClient(); @@ -54,6 +57,13 @@ public static void init() { final Object instanceMultiPartRegistry$module$ = fieldMultiPartRegistry$module$ .get(classMultiPartRegistry$); instancesTypeMap = (Map) field$typeMap.get(instanceMultiPartRegistry$module$); + instanceMultiPartRegistry = instanceMultiPartRegistry$module$; + methodLoadRegisteredPart = ReflectionHelper.findMethod( + classMultiPartRegistry$, + null, + new String[] { "loadPart" }, + String.class, + NBTTagCompound.class); final Class classMicroMaterialRegistry = ReflectionHelper .getClass(classLoader, "codechicken.microblock.MicroMaterialRegistry"); @@ -62,6 +72,7 @@ public static void init() { final Class classMicroblockClass = ReflectionHelper .getClass(classLoader, "codechicken.microblock.MicroblockClass"); + microblockPart = ReflectionHelper.getClass(classLoader, "codechicken.microblock.Microblock"); methodCreatePart = ReflectionHelper .findMethod(classMicroblockClass, null, new String[] { "create" }, boolean.class, int.class); @@ -130,9 +141,7 @@ private static TileEntity createFromNBTClient(final NBTTagCompound tileEntityCom for (int i = 0; i < partList.tagCount(); i++) { final NBTTagCompound partTag = partList.getCompoundTagAt(i); final String partID = partTag.getString("id"); - final int materialID = materialID(partTag.getString("material")); - - final Object part = createPart(partID, client, materialID); + final Object part = createPart(partID, client, partTag); if (part != null) { load(part, partTag); parts.add(part); @@ -153,7 +162,10 @@ private static TileEntity createFromNBTClient(final NBTTagCompound tileEntityCom loadParts(tileEntity, parts); for (Object part : parts) { - onPartChanged(part, part); + // Microblocks recalculate render bounds here. Other parts may require an attached world. + if (microblockPart.isInstance(part)) { + onPartChanged(part, part); + } } return tileEntity; @@ -173,7 +185,7 @@ private static int materialID(final String material) throws ReflectiveOperationE return (Integer) methodMaterialID.invoke(null, material); } - private static Object createPart(final String partID, final boolean client, final int materialID) + private static Object createPart(final String partID, final boolean client, final NBTTagCompound partTag) throws ReflectiveOperationException { final Option option = instancesTypeMap.get(partID); if (option.isEmpty()) { @@ -181,7 +193,14 @@ private static Object createPart(final String partID, final boolean client, fina return null; } - return methodCreatePart.invoke(option.get(), client, materialID); + final Object factory = option.get(); + if (methodCreatePart.getDeclaringClass() + .isInstance(factory)) { + return methodCreatePart.invoke(factory, client, materialID(partTag.getString("material"))); + } + + // Other multipart factories load their own NBT and can share a tile with microblocks. + return methodLoadRegisteredPart.invoke(instanceMultiPartRegistry, partID, partTag); } private static Object load(final Object part, final NBTTagCompound partTag) throws ReflectiveOperationException { diff --git a/src/main/java/com/github/lunatrius/schematica/nbt/LegacyGregTechOre.java b/src/main/java/com/github/lunatrius/schematica/nbt/LegacyGregTechOre.java new file mode 100644 index 00000000..fcf7c4a7 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/nbt/LegacyGregTechOre.java @@ -0,0 +1,27 @@ +package com.github.lunatrius.schematica.nbt; + +import net.minecraft.init.Blocks; +import net.minecraft.nbt.NBTTagCompound; + +import com.github.lunatrius.schematica.api.ISchematic; +import com.gtnewhorizons.postea.utility.BlockInfo; +import com.gtnewhorizons.postea.utility.TransformerRegistry; + +public final class LegacyGregTechOre { + + private static final String TILE_ID = "GT_TileEntity_Ores"; + + private LegacyGregTechOre() {} + + public static boolean replace(ISchematic schematic, NBTTagCompound tag) { + for (var converter : TransformerRegistry.getTileEntityToNormalBlockTransformerFunction(TILE_ID)) { + // GregTech's ore converter needs only the material, host rock and natural flag from the tile tag. + final BlockInfo ore = converter.apply(tag, null, null); + if (ore != null && ore.block != Blocks.air && ore.tileTransformer == null) { + return schematic + .setBlock(tag.getInteger("x"), tag.getInteger("y"), tag.getInteger("z"), ore.block, ore.metadata); + } + } + return false; + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/network/message/MessageCapabilities.java b/src/main/java/com/github/lunatrius/schematica/network/message/MessageCapabilities.java index 08797ce6..d1c47ca9 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/message/MessageCapabilities.java +++ b/src/main/java/com/github/lunatrius/schematica/network/message/MessageCapabilities.java @@ -2,6 +2,7 @@ import com.github.lunatrius.schematica.Schematica; import com.github.lunatrius.schematica.client.printer.SchematicPrinter; +import com.github.lunatrius.schematica.handler.DownloadHandler; import com.github.lunatrius.schematica.proxy.ClientProxy; import com.github.lunatrius.schematica.reference.Reference; @@ -15,6 +16,7 @@ public class MessageCapabilities implements IMessage, IMessageHandler minecraft.ingameGUI.getChatGUI() + .printChatMessageWithOptionalDeletion( + new ChatComponentTranslation(messageKey), + messageKey.hashCode())); + return null; + } - return new MessageDownloadBeginAck(); + DownloadHandler.INSTANCE.schematic = new Schematic(message.icon, message.width, message.height, message.length); + return new MessageDownloadBeginAck(DownloadHandler.PROTOCOL_VERSION); } } diff --git a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadBeginAck.java b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadBeginAck.java index 5e4ef6c3..f6b0f956 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadBeginAck.java +++ b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadBeginAck.java @@ -3,7 +3,6 @@ import net.minecraft.entity.player.EntityPlayerMP; import com.github.lunatrius.schematica.handler.DownloadHandler; -import com.github.lunatrius.schematica.network.transfer.SchematicTransfer; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; @@ -12,23 +11,29 @@ public class MessageDownloadBeginAck implements IMessage, IMessageHandler { + private int protocolVersion; + + public MessageDownloadBeginAck() {} + + MessageDownloadBeginAck(int protocolVersion) { + this.protocolVersion = protocolVersion; + } + @Override public void fromBytes(ByteBuf buf) { - // NOOP + // The original acknowledgment has no payload. + this.protocolVersion = buf.readableBytes() == 1 ? buf.readUnsignedByte() : 0; } @Override public void toBytes(ByteBuf buf) { - // NOOP + buf.writeByte(this.protocolVersion); } @Override public IMessage onMessage(MessageDownloadBeginAck message, MessageContext ctx) { EntityPlayerMP player = ctx.getServerHandler().playerEntity; - SchematicTransfer transfer = DownloadHandler.INSTANCE.transferMap.get(player); - if (transfer != null) { - transfer.setState(SchematicTransfer.State.CHUNK_WAIT); - } + DownloadHandler.INSTANCE.confirmBegin(player, message.protocolVersion); return null; } diff --git a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunk.java b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunk.java index ea157427..833f671e 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunk.java +++ b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunk.java @@ -24,15 +24,17 @@ public class MessageDownloadChunk implements IMessage, IMessageHandler { public static final FMLControlledNamespacedRegistry BLOCK_REGISTRY = GameData.getBlockRegistry(); + private static final int CELL_COUNT = Constants.SchematicChunk.WIDTH * Constants.SchematicChunk.HEIGHT + * Constants.SchematicChunk.LENGTH; public int baseX; public int baseY; public int baseZ; - public short[][][] blocks; - public byte[][][] metadata; - public List tileEntities; - public List entities; + private final int[] blockIds = new int[CELL_COUNT]; + private final char[] metadata = new char[CELL_COUNT]; + private List tileEntities = new ArrayList<>(); + private List entities = new ArrayList<>(); public MessageDownloadChunk() {} @@ -41,18 +43,13 @@ public MessageDownloadChunk(ISchematic schematic, int baseX, int baseY, int base this.baseY = baseY; this.baseZ = baseZ; - this.blocks = new short[Constants.SchematicChunk.WIDTH][Constants.SchematicChunk.HEIGHT][Constants.SchematicChunk.LENGTH]; - this.metadata = new byte[Constants.SchematicChunk.WIDTH][Constants.SchematicChunk.HEIGHT][Constants.SchematicChunk.LENGTH]; - this.tileEntities = new ArrayList<>(); - this.entities = new ArrayList<>(); - + int index = 0; for (int x = 0; x < Constants.SchematicChunk.WIDTH; x++) { for (int y = 0; y < Constants.SchematicChunk.HEIGHT; y++) { - for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++) { + for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++, index++) { final Block block = schematic.getBlock(baseX + x, baseY + y, baseZ + z); - final int id = BLOCK_REGISTRY.getId(block); - this.blocks[x][y][z] = (short) id; - this.metadata[x][y][z] = (byte) schematic.getBlockMetadata(baseX + x, baseY + y, baseZ + z); + this.blockIds[index] = BLOCK_REGISTRY.getId(block); + this.metadata[index] = (char) schematic.getBlockMetadata(baseX + x, baseY + y, baseZ + z); final TileEntity tileEntity = schematic.getTileEntity(baseX + x, baseY + y, baseZ + z); if (tileEntity != null) { this.tileEntities.add(tileEntity); @@ -63,14 +60,12 @@ public MessageDownloadChunk(ISchematic schematic, int baseX, int baseY, int base } private void copyToSchematic(final ISchematic schematic) { + int index = 0; for (int x = 0; x < Constants.SchematicChunk.WIDTH; x++) { for (int y = 0; y < Constants.SchematicChunk.HEIGHT; y++) { - for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++) { - short id = this.blocks[x][y][z]; - byte meta = this.metadata[x][y][z]; - Block block = BLOCK_REGISTRY.getObjectById(id); - - schematic.setBlock(this.baseX + x, this.baseY + y, this.baseZ + z, block, meta); + for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++, index++) { + final Block block = BLOCK_REGISTRY.getObjectById(this.blockIds[index]); + schematic.setBlock(this.baseX + x, this.baseY + y, this.baseZ + z, block, this.metadata[index]); } } } @@ -86,18 +81,9 @@ public void fromBytes(ByteBuf buf) { this.baseY = buf.readShort(); this.baseZ = buf.readShort(); - this.blocks = new short[Constants.SchematicChunk.WIDTH][Constants.SchematicChunk.HEIGHT][Constants.SchematicChunk.LENGTH]; - this.metadata = new byte[Constants.SchematicChunk.WIDTH][Constants.SchematicChunk.HEIGHT][Constants.SchematicChunk.LENGTH]; - this.tileEntities = new ArrayList<>(); - this.entities = new ArrayList<>(); - - for (int x = 0; x < Constants.SchematicChunk.WIDTH; x++) { - for (int y = 0; y < Constants.SchematicChunk.HEIGHT; y++) { - for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++) { - this.blocks[x][y][z] = buf.readShort(); - this.metadata[x][y][z] = buf.readByte(); - } - } + for (int index = 0; index < CELL_COUNT; index++) { + this.blockIds[index] = buf.readInt(); + this.metadata[index] = (char) buf.readUnsignedShort(); } final NBTTagCompound compound = ByteBufUtils.readTag(buf); @@ -113,13 +99,9 @@ public void toBytes(ByteBuf buf) { buf.writeShort(this.baseY); buf.writeShort(this.baseZ); - for (int x = 0; x < Constants.SchematicChunk.WIDTH; x++) { - for (int y = 0; y < Constants.SchematicChunk.HEIGHT; y++) { - for (int z = 0; z < Constants.SchematicChunk.LENGTH; z++) { - buf.writeShort(this.blocks[x][y][z]); - buf.writeByte(this.metadata[x][y][z]); - } - } + for (int index = 0; index < CELL_COUNT; index++) { + buf.writeInt(this.blockIds[index]); + buf.writeShort(this.metadata[index]); } final NBTTagCompound compound = NBTHelper.writeTileEntitiesToCompound(this.tileEntities); @@ -131,7 +113,11 @@ public void toBytes(ByteBuf buf) { @Override public IMessage onMessage(MessageDownloadChunk message, MessageContext ctx) { - message.copyToSchematic(DownloadHandler.INSTANCE.schematic); + final ISchematic schematic = DownloadHandler.INSTANCE.schematic; + if (schematic == null) { + return null; + } + message.copyToSchematic(schematic); return new MessageDownloadChunkAck(message.baseX, message.baseY, message.baseZ); } diff --git a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunkAck.java b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunkAck.java index a6a3b703..6d409271 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunkAck.java +++ b/src/main/java/com/github/lunatrius/schematica/network/message/MessageDownloadChunkAck.java @@ -3,7 +3,6 @@ import net.minecraft.entity.player.EntityPlayerMP; import com.github.lunatrius.schematica.handler.DownloadHandler; -import com.github.lunatrius.schematica.network.transfer.SchematicTransfer; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; @@ -41,10 +40,7 @@ public void toBytes(ByteBuf buf) { @Override public IMessage onMessage(MessageDownloadChunkAck message, MessageContext ctx) { EntityPlayerMP player = ctx.getServerHandler().playerEntity; - SchematicTransfer transfer = DownloadHandler.INSTANCE.transferMap.get(player); - if (transfer != null) { - transfer.confirmChunk(message.baseX, message.baseY, message.baseZ); - } + DownloadHandler.INSTANCE.confirmChunk(player, message.baseX, message.baseY, message.baseZ); return null; } diff --git a/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java b/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java index 604afbe2..9db2a449 100644 --- a/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java +++ b/src/main/java/com/github/lunatrius/schematica/network/transfer/SchematicTransfer.java @@ -37,6 +37,7 @@ public boolean isWaiting() { public State state = State.BEGIN_WAIT; public int timeout = 0; public int retries = 0; + public int clientProtocolVersion; public int baseX = 0; public int baseY = 0; diff --git a/src/main/java/com/github/lunatrius/schematica/proxy/ClientProxy.java b/src/main/java/com/github/lunatrius/schematica/proxy/ClientProxy.java index f9b9277e..7c0f48e2 100644 --- a/src/main/java/com/github/lunatrius/schematica/proxy/ClientProxy.java +++ b/src/main/java/com/github/lunatrius/schematica/proxy/ClientProxy.java @@ -30,6 +30,7 @@ import com.github.lunatrius.schematica.compat.ILOTRPresent; import com.github.lunatrius.schematica.compat.NoLOTRProxy; import com.github.lunatrius.schematica.handler.ConfigurationHandler; +import com.github.lunatrius.schematica.handler.DownloadHandler; import com.github.lunatrius.schematica.handler.client.ChatEventHandler; import com.github.lunatrius.schematica.handler.client.InputHandler; import com.github.lunatrius.schematica.handler.client.OverlayHandler; @@ -37,6 +38,7 @@ import com.github.lunatrius.schematica.handler.client.TickHandler; import com.github.lunatrius.schematica.handler.client.WorldHandler; import com.github.lunatrius.schematica.reference.Constants; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Reference; import com.github.lunatrius.schematica.util.Coordinates; import com.github.lunatrius.schematica.world.schematic.SchematicFormat; @@ -47,7 +49,6 @@ import cpw.mods.fml.client.config.GuiConfigEntries; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; @@ -343,7 +344,7 @@ public void init(FMLInitializationEvent event) { public void postInit(FMLPostInitializationEvent event) { super.postInit(event); try { - if (Loader.isModLoaded("lotr")) { + if (Mods.LOTR) { Reference.logger.info("Lotr mod detected, creating proxy"); lotrProxy = Class.forName(Reference.LOTR_PROXY) .asSubclass(ILOTRPresent.class) @@ -372,6 +373,8 @@ public File getDataDirectory() { @Override public void resetSettings() { super.resetSettings(); + DownloadHandler.INSTANCE.serverProtocolVersion = 0; + DownloadHandler.INSTANCE.schematic = null; ChatEventHandler.INSTANCE.chatLines = 0; diff --git a/src/main/java/com/github/lunatrius/schematica/proxy/CommonProxy.java b/src/main/java/com/github/lunatrius/schematica/proxy/CommonProxy.java index 8c310a86..74721e36 100644 --- a/src/main/java/com/github/lunatrius/schematica/proxy/CommonProxy.java +++ b/src/main/java/com/github/lunatrius/schematica/proxy/CommonProxy.java @@ -30,7 +30,6 @@ import com.github.lunatrius.schematica.world.storage.Schematic; import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; @@ -40,10 +39,8 @@ public abstract class CommonProxy { public boolean isSaveEnabled = true; public boolean isLoadEnabled = true; - public boolean GTNH = false; public void preInit(FMLPreInitializationEvent event) { - GTNH = Loader.isModLoaded("dreamcraft"); Reference.logger = event.getModLog(); ConfigurationHandler.init(event.getSuggestedConfigurationFile()); } diff --git a/src/main/java/com/github/lunatrius/schematica/reference/Mods.java b/src/main/java/com/github/lunatrius/schematica/reference/Mods.java new file mode 100644 index 00000000..9753e6f8 --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/reference/Mods.java @@ -0,0 +1,21 @@ +package com.github.lunatrius.schematica.reference; + +import cpw.mods.fml.common.Loader; + +/** Snapshots mod presence on first use, after FML mod discovery. */ +public final class Mods { + + public static final String COOKING_FOR_BLOCKHEADS_ID = "cookingforblockheads"; + + public static final boolean ARCHITECTURE_CRAFT = Loader.isModLoaded("ArchitectureCraft"); + public static final boolean CARPENTERS_BLOCKS = Loader.isModLoaded("CarpentersBlocks"); + public static final boolean COOKING_FOR_BLOCKHEADS = Loader.isModLoaded(COOKING_FOR_BLOCKHEADS_ID); + public static final boolean ENDER_IO = Loader.isModLoaded("EnderIO"); + public static final boolean FORGE_MICROBLOCK = Loader.isModLoaded("ForgeMicroblock"); + public static final boolean FORGE_MULTIPART = Loader.isModLoaded("ForgeMultipart"); + public static final boolean GTNH = Loader.isModLoaded("dreamcraft"); + public static final boolean LOTR = Loader.isModLoaded("lotr"); + public static final boolean POSTEA = Loader.isModLoaded("postea"); + + private Mods() {} +} diff --git a/src/main/java/com/github/lunatrius/schematica/reference/Names.java b/src/main/java/com/github/lunatrius/schematica/reference/Names.java index 8590d37c..f860cb52 100644 --- a/src/main/java/com/github/lunatrius/schematica/reference/Names.java +++ b/src/main/java/com/github/lunatrius/schematica/reference/Names.java @@ -19,7 +19,7 @@ public static final class Category { public static final String SHOW_DEBUG_INFO = "showDebugInfo"; public static final String SHOW_DEBUG_INFO_DESC = "Display extra information on the debug screen (F3)."; public static final String EXTENDED_ID_FORMAT = "useSchematicplusFormat"; - public static final String EXTENDED_ID_FORMAT_DESC = "Save and load schematics with a different format that supports a much higher number of block ids. Only schematics in schemplus format will be loaded."; + public static final String EXTENDED_ID_FORMAT_DESC = "Unused. Block ids are stored automatically: classic 12-bit data when every id is below 4096, otherwise up to 24 bits. Both .schematic and .schemplus files are loaded."; public static final String ALPHA_ENABLED = "alphaEnabled"; public static final String ALPHA_ENABLED_DESC = "Enable transparent textures."; public static final String ALPHA = "alpha"; @@ -144,6 +144,8 @@ public static final class Message { public static final String DOWNLOAD_STARTED = "schematica.command.download.started"; public static final String DOWNLOAD_SUCCEEDED = "schematica.command.download.downloadSucceeded"; public static final String DOWNLOAD_FAILED = "schematica.command.download.downloadFail"; + public static final String DOWNLOAD_SERVER_REQUIRES_UPDATE = "schematica.command.download.serverRequiresUpdate"; + public static final String DOWNLOAD_REQUIRES_UPDATE = "schematica.command.download.requiresUpdate"; } public static final String NAME = "schematicaDownload"; @@ -231,7 +233,10 @@ public static final class NBT { public static final String ICON = "Icon"; public static final String BLOCKS = "Blocks"; public static final String DATA = "Data"; + public static final String DATA_HIGH = "SchematicaDataHigh"; public static final String ADD_BLOCKS = "AddBlocks"; + public static final String ADD_BLOCKS_HIGH = "AddBlocksHigh"; + public static final String BLOCK_ID_BYTES = "BlockIdBytes"; public static final String ADD_BLOCKS_SCHEMATICA = "Add"; public static final String WIDTH = "Width"; public static final String LENGTH = "Length"; diff --git a/src/main/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodec.java b/src/main/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodec.java new file mode 100644 index 00000000..bdc3fb8d --- /dev/null +++ b/src/main/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodec.java @@ -0,0 +1,177 @@ +package com.github.lunatrius.schematica.world.schematic; + +/** + * Block ids stored in a schematic, up to 24 bits. + * + *

+ * Classic files keep the low 8 bits in {@code Blocks} and the next 4 bits as nibbles in {@code AddBlocks}. That + * covers ids below 4096. Wider files store a full second byte per block in {@code AddBlocks} and, when any id is above + * 65535, a third byte in {@code AddBlocksHigh}. {@code BlockIdBytes} is 2 or 3 on those files so a one-block schematic + * is not read back as nibbles. + * + *

+ * Older {@code .schemplus} files use the full-byte {@code AddBlocks} layout and have no {@code BlockIdBytes} tag. A + * one-block file of that kind is only recognized when {@code schemplusFile} is true. Ids already saved by the old + * schemplus writer that were divisible by 256 dropped a byte on the way in; those files do not contain the missing + * bits, so loading them gives the value that was actually written. + */ +public final class BlockIdCodec { + + public static final int MAX_SAVED_ID = 0xFFFFFF; + public static final int CLASSIC_MAX_ID = 0xFFF; + public static final int TWO_BYTE_MAX_ID = 0xFFFF; + + private BlockIdCodec() {} + + public static final class Encoded { + + public final byte[] blocks; + public final byte[] addBlocks; + public final byte[] addBlocksHigh; + /** 1 = classic 8/12-bit, 2 = 16-bit, 3 = 24-bit. Classic files omit the tag. */ + public final int blockIdBytes; + + Encoded(byte[] blocks, byte[] addBlocks, byte[] addBlocksHigh, int blockIdBytes) { + this.blocks = blocks; + this.addBlocks = addBlocks; + this.addBlocksHigh = addBlocksHigh; + this.blockIdBytes = blockIdBytes; + } + } + + public static Encoded encode(int[] ids) { + int[] stored = new int[ids.length]; + int max = 0; + for (int i = 0; i < ids.length; i++) { + int id = ids[i]; + if (id < 0) { + id = 0; + } else if (id > MAX_SAVED_ID) { + id &= MAX_SAVED_ID; + } + stored[i] = id; + if (id > max) { + max = id; + } + } + + if (max <= CLASSIC_MAX_ID) { + return encodeClassic(stored); + } + return encodeWide(stored, max <= TWO_BYTE_MAX_ID ? 2 : 3); + } + + /** + * @param blockIdBytes value of the {@code BlockIdBytes} tag, or 0 when the tag is absent + * @param schemplusFile true when the file name ends in {@code .schemplus} + */ + public static int[] decode(byte[] blocks, byte[] addBlocks, byte[] legacyAdd, byte[] addHigh, int blockIdBytes, + boolean schemplusFile) { + if (blocks == null) { + throw new IllegalArgumentException("Blocks array is missing"); + } + int count = blocks.length; + if (count == 0) { + return new int[0]; + } + if (addHigh != null || blockIdBytes >= 3) { + return combine(blocks, addBlocks, addHigh); + } + if (blockIdBytes == 2) { + return combine(blocks, addBlocks != null ? addBlocks : legacyAdd, null); + } + if (blockIdBytes == 1) { + return addBlocks == null ? lowByte(blocks) : decodeNibbles(blocks, addBlocks); + } + // The former compatibility branch wrote Add alongside a packed preview in AddBlocks. + if (legacyAdd != null) { + return combine(blocks, legacyAdd, null); + } + if (addBlocks == null) { + return lowByte(blocks); + } + if (addBlocks.length == count && (count != 1 || schemplusFile)) { + return combine(blocks, addBlocks, null); + } + return decodeNibbles(blocks, addBlocks); + } + + private static Encoded encodeClassic(int[] ids) { + byte[] blocks = new byte[ids.length]; + boolean extra = false; + byte[] nibbles = new byte[ids.length]; + for (int i = 0; i < ids.length; i++) { + blocks[i] = (byte) ids[i]; + int high = (ids[i] >> 8) & 0xF; + nibbles[i] = (byte) high; + if (high != 0) { + extra = true; + } + } + if (!extra) { + return new Encoded(blocks, null, null, 1); + } + + byte[] packed = new byte[(ids.length + 1) / 2]; + for (int i = 0; i < packed.length; i++) { + int even = nibbles[i * 2] & 0xF; + int odd = (i * 2 + 1 < nibbles.length) ? (nibbles[i * 2 + 1] & 0xF) : 0; + packed[i] = (byte) ((even << 4) | odd); + } + return new Encoded(blocks, packed, null, 1); + } + + private static Encoded encodeWide(int[] ids, int blockIdBytes) { + byte[] blocks = new byte[ids.length]; + byte[] addBlocks = new byte[ids.length]; + byte[] addHigh = blockIdBytes == 3 ? new byte[ids.length] : null; + for (int i = 0; i < ids.length; i++) { + blocks[i] = (byte) ids[i]; + addBlocks[i] = (byte) (ids[i] >> 8); + if (addHigh != null) { + addHigh[i] = (byte) (ids[i] >> 16); + } + } + return new Encoded(blocks, addBlocks, addHigh, blockIdBytes); + } + + private static int[] lowByte(byte[] blocks) { + int[] ids = new int[blocks.length]; + for (int i = 0; i < blocks.length; i++) { + ids[i] = blocks[i] & 0xFF; + } + return ids; + } + + private static int[] decodeNibbles(byte[] blocks, byte[] packed) { + int[] ids = new int[blocks.length]; + for (int i = 0; i < blocks.length; i++) { + int packedIndex = i >>> 1; + int high = 0; + if (packedIndex < packed.length) { + int value = packed[packedIndex] & 0xFF; + high = (i & 1) == 0 ? (value >> 4) & 0xF : value & 0xF; + } + ids[i] = (blocks[i] & 0xFF) | (high << 8); + } + return ids; + } + + private static int[] combine(byte[] blocks, byte[] mid, byte[] high) { + if (mid == null || mid.length < blocks.length) { + throw new IllegalArgumentException("AddBlocks does not cover every block"); + } + if (high != null && high.length < blocks.length) { + throw new IllegalArgumentException("AddBlocksHigh does not cover every block"); + } + int[] ids = new int[blocks.length]; + for (int i = 0; i < blocks.length; i++) { + int id = (blocks[i] & 0xFF) | ((mid[i] & 0xFF) << 8); + if (high != null) { + id |= (high[i] & 0xFF) << 16; + } + ids[i] = id; + } + return ids; + } +} diff --git a/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java b/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java index 63e35ad9..ee5a89ac 100644 --- a/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java +++ b/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java @@ -3,14 +3,15 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTTagShort; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; @@ -18,8 +19,10 @@ import com.github.lunatrius.schematica.api.ISchematic; import com.github.lunatrius.schematica.api.event.PreSchematicSaveEvent; -import com.github.lunatrius.schematica.handler.ConfigurationHandler; +import com.github.lunatrius.schematica.nbt.CarpentersBlocksNBT; +import com.github.lunatrius.schematica.nbt.LegacyGregTechOre; import com.github.lunatrius.schematica.nbt.NBTHelper; +import com.github.lunatrius.schematica.reference.Mods; import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.reference.Reference; import com.github.lunatrius.schematica.world.storage.Schematic; @@ -33,342 +36,268 @@ public class SchematicAlpha extends SchematicFormat { @Override public ISchematic readFromNBT(NBTTagCompound tagCompound) { - if (ConfigurationHandler.useSchematicplusFormat) { - ItemStack icon = SchematicUtil.getIconFromNBT(tagCompound); - - byte[] localBlocks = tagCompound.getByteArray(Names.NBT.BLOCKS); - byte[] localMetadata = tagCompound.getByteArray(Names.NBT.DATA); - byte[] extraBlocks = tagCompound.getByteArray(Names.NBT.ADD_BLOCKS); - - short width = tagCompound.getShort(Names.NBT.WIDTH); - short length = tagCompound.getShort(Names.NBT.LENGTH); - short height = tagCompound.getShort(Names.NBT.HEIGHT); - - Short id; - Map oldToNew = new HashMap<>(); - if (tagCompound.hasKey(Names.NBT.MAPPING_SCHEMATICA)) { - NBTTagCompound mapping = tagCompound.getCompoundTag(Names.NBT.MAPPING_SCHEMATICA); - Set names = mapping.func_150296_c(); - for (String name : names) { - oldToNew.put(mapping.getShort(name), (short) BLOCK_REGISTRY.getId(name)); - } - } - - ISchematic schematic = new Schematic(icon, width, height, length); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - for (int z = 0; z < length; z++) { - int index = x + (y * length + z) * width; - int blockID = (localBlocks[index] & 0xFF) | ((extraBlocks[index] & 0xFF) * 256); - int meta = localMetadata[index] & 0xFF; + return readFromNBT(tagCompound, false); + } - if ((id = oldToNew.get((short) blockID)) != null) { - blockID = id; - } + public ISchematic readFromNBT(NBTTagCompound tagCompound, boolean schemplusFile) { + ItemStack icon = SchematicUtil.getIconFromNBT(tagCompound); + + byte[] localBlocks = tagCompound.getByteArray(Names.NBT.BLOCKS); + byte[] localMetadata = tagCompound.getByteArray(Names.NBT.DATA); + byte[] addBlocks = byteArrayOrNull(tagCompound, Names.NBT.ADD_BLOCKS); + byte[] legacyAdd = byteArrayOrNull(tagCompound, Names.NBT.ADD_BLOCKS_SCHEMATICA); + byte[] addBlocksHigh = byteArrayOrNull(tagCompound, Names.NBT.ADD_BLOCKS_HIGH); + int blockIdBytes = tagCompound.hasKey(Names.NBT.BLOCK_ID_BYTES) + ? tagCompound.getByte(Names.NBT.BLOCK_ID_BYTES) & 0xFF + : 0; + + int width = tagCompound.getShort(Names.NBT.WIDTH); + int length = tagCompound.getShort(Names.NBT.LENGTH); + int height = tagCompound.getShort(Names.NBT.HEIGHT); + int size = width * length * height; + if (localBlocks.length < size || localMetadata.length < size) { + throw new IllegalArgumentException( + "Schematic block arrays have " + localBlocks.length + " entries, expected at least " + size); + } - schematic.setBlock(x, y, z, BLOCK_REGISTRY.getObjectById(blockID), meta); + byte[] highMetadata = readHighMetadata(tagCompound, localMetadata.length); + int[] blockIds = BlockIdCodec + .decode(localBlocks, addBlocks, legacyAdd, addBlocksHigh, blockIdBytes, schemplusFile); + Map oldToNew = readMapping(tagCompound); + + ISchematic schematic = new Schematic(icon, width, height, length); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + for (int z = 0; z < length; z++) { + int index = index(x, y, z, width, length); + int blockId = blockIds[index]; + Integer mapped = oldToNew.get(blockId); + if (mapped != null) { + blockId = mapped; } - } - } - - NBTTagList tileEntitiesList = tagCompound.getTagList(Names.NBT.TILE_ENTITIES, Constants.NBT.TAG_COMPOUND); - - for (int i = 0; i < tileEntitiesList.tagCount(); i++) { - try { - TileEntity tileEntity = NBTHelper.readTileEntityFromCompound(tileEntitiesList.getCompoundTagAt(i)); - if (tileEntity != null) { - schematic.setTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, tileEntity); + int meta = localMetadata[index] & 0xFF; + if (highMetadata != null) { + meta |= (highMetadata[index] & 0xFF) << 8; } - } catch (Exception e) { - Reference.logger.error("TileEntity failed to load properly!", e); + schematic.setBlock(x, y, z, BLOCK_REGISTRY.getObjectById(blockId), meta); } } + } - return schematic; - } else { - ItemStack icon = SchematicUtil.getIconFromNBT(tagCompound); + loadTiles(tagCompound, schematic); + return schematic; + } - byte[] localBlocks = tagCompound.getByteArray(Names.NBT.BLOCKS); - byte[] localMetadata = tagCompound.getByteArray(Names.NBT.DATA); + private static byte[] readHighMetadata(NBTTagCompound tag, int length) { + if (!tag.hasKey(Names.NBT.DATA_HIGH)) { + return null; + } + if (!tag.hasKey(Names.NBT.DATA_HIGH, Constants.NBT.TAG_BYTE_ARRAY)) { + throw new IllegalArgumentException("Invalid " + Names.NBT.DATA_HIGH + " type"); + } + final byte[] metadata = tag.getByteArray(Names.NBT.DATA_HIGH); + if (metadata.length != length) { + throw new IllegalArgumentException("Invalid " + Names.NBT.DATA_HIGH + " length"); + } + return metadata; + } - boolean extra = false; - byte[] extraBlocks = null; - byte[] extraBlocksNibble; - if (tagCompound.hasKey(Names.NBT.ADD_BLOCKS)) { - extra = true; - extraBlocksNibble = tagCompound.getByteArray(Names.NBT.ADD_BLOCKS); - extraBlocks = new byte[extraBlocksNibble.length * 2]; - for (int i = 0; i < extraBlocksNibble.length; i++) { - extraBlocks[i * 2 + 0] = (byte) ((extraBlocksNibble[i] >> 4) & 0xF); - extraBlocks[i * 2 + 1] = (byte) (extraBlocksNibble[i] & 0xF); + private static void loadTiles(NBTTagCompound tagCompound, ISchematic schematic) { + final NBTTagList tiles = tagCompound.getTagList(Names.NBT.TILE_ENTITIES, Constants.NBT.TAG_COMPOUND); + for (int i = 0; i < tiles.tagCount(); i++) { + final NBTTagCompound tag = tiles.getCompoundTagAt(i); + try { + if (Mods.POSTEA && "GT_TileEntity_Ores".equals(tag.getString("id")) + && LegacyGregTechOre.replace(schematic, tag)) { + continue; } - } else if (tagCompound.hasKey(Names.NBT.ADD_BLOCKS_SCHEMATICA)) { - extra = true; - extraBlocks = tagCompound.getByteArray(Names.NBT.ADD_BLOCKS_SCHEMATICA); + } catch (Exception e) { + Reference.logger.debug("Could not convert a legacy GregTech ore", e); } - - short width = tagCompound.getShort(Names.NBT.WIDTH); - short length = tagCompound.getShort(Names.NBT.LENGTH); - short height = tagCompound.getShort(Names.NBT.HEIGHT); - - Short id; - Map oldToNew = new HashMap<>(); - if (tagCompound.hasKey(Names.NBT.MAPPING_SCHEMATICA)) { - NBTTagCompound mapping = tagCompound.getCompoundTag(Names.NBT.MAPPING_SCHEMATICA); - Set names = mapping.func_150296_c(); - for (String name : names) { - oldToNew.put(mapping.getShort(name), (short) BLOCK_REGISTRY.getId(name)); + try { + if (Mods.CARPENTERS_BLOCKS) { + CarpentersBlocksNBT.remapAttributeItems(tag); } - } - - ISchematic schematic = new Schematic(icon, width, height, length); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - for (int z = 0; z < length; z++) { - int index = x + (y * length + z) * width; - int blockID = (localBlocks[index] & 0xFF) | (extra ? ((extraBlocks[index] & 0xFF) << 8) : 0); - int meta = localMetadata[index] & 0xFF; - - if ((id = oldToNew.get((short) blockID)) != null) { - blockID = id; - } - - schematic.setBlock(x, y, z, BLOCK_REGISTRY.getObjectById(blockID), meta); - } - } - } - - NBTTagList tileEntitiesList = tagCompound.getTagList(Names.NBT.TILE_ENTITIES, Constants.NBT.TAG_COMPOUND); - - for (int i = 0; i < tileEntitiesList.tagCount(); i++) { - try { - TileEntity tileEntity = NBTHelper.readTileEntityFromCompound(tileEntitiesList.getCompoundTagAt(i)); - if (tileEntity != null) { - schematic.setTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, tileEntity); - } - } catch (Exception e) { - Reference.logger.error("TileEntity failed to load properly!", e); + final TileEntity tileEntity = NBTHelper.readTileEntityFromCompound(tag); + if (tileEntity != null) { + schematic.setTileEntity(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, tileEntity); } + } catch (Exception e) { + Reference.logger.error("TileEntity failed to load properly!", e); } - - return schematic; } - } @Override public boolean writeToNBT(NBTTagCompound tagCompound, ISchematic schematic, World backupWorld) { - if (ConfigurationHandler.useSchematicplusFormat) { - NBTTagCompound tagCompoundIcon = new NBTTagCompound(); - ItemStack icon = schematic.getIcon(); - icon.writeToNBT(tagCompoundIcon); - tagCompound.setTag(Names.NBT.ICON, tagCompoundIcon); - - tagCompound.setShort(Names.NBT.WIDTH, (short) schematic.getWidth()); - tagCompound.setShort(Names.NBT.LENGTH, (short) schematic.getLength()); - tagCompound.setShort(Names.NBT.HEIGHT, (short) schematic.getHeight()); - - int size = schematic.getWidth() * schematic.getLength() * schematic.getHeight(); - byte[] localBlocks = new byte[size]; - byte[] localMetadata = new byte[size]; - byte[] extraBlocks = new byte[size]; - - Map mappings = new HashMap<>(); - for (int x = 0; x < schematic.getWidth(); x++) { - for (int y = 0; y < schematic.getHeight(); y++) { - for (int z = 0; z < schematic.getLength(); z++) { - final int index = x + (y * schematic.getLength() + z) * schematic.getWidth(); - final Block block = schematic.getBlock(x, y, z); - int blockId = BLOCK_REGISTRY.getId(block); - int tempblockId = blockId; - int numextra = 0; - for (int i = 1; tempblockId > 256; i++) { - tempblockId = tempblockId - 256; - numextra = i; + NBTTagCompound tagCompoundIcon = new NBTTagCompound(); + ItemStack icon = schematic.getIcon(); + icon.writeToNBT(tagCompoundIcon); + tagCompound.setTag(Names.NBT.ICON, tagCompoundIcon); + + int width = schematic.getWidth(); + int length = schematic.getLength(); + int height = schematic.getHeight(); + tagCompound.setShort(Names.NBT.WIDTH, (short) width); + tagCompound.setShort(Names.NBT.LENGTH, (short) length); + tagCompound.setShort(Names.NBT.HEIGHT, (short) height); + + int size = width * length * height; + int[] blockIds = new int[size]; + byte[] localMetadata = new byte[size]; + byte[] highMetadata = null; + Map mappings = new HashMap<>(); + boolean loggedTruncation = false; + + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + for (int z = 0; z < length; z++) { + int index = index(x, y, z, width, length); + Block block = schematic.getBlock(x, y, z); + int rawId = block == null ? -1 : BLOCK_REGISTRY.getId(block); + int blockId = rawId; + if (rawId < 0) { + blockId = 0; + } else if (rawId > BlockIdCodec.MAX_SAVED_ID) { + blockId = rawId & BlockIdCodec.MAX_SAVED_ID; + if (!loggedTruncation) { + Reference.logger.error( + "Block {} has id {}, above the 24-bit schematic limit. The saved id will be truncated.", + BLOCK_REGISTRY.getNameForObject(block), + rawId); + loggedTruncation = true; + } + } + blockIds[index] = blockId; + int metadata = schematic.getBlockMetadata(x, y, z); + localMetadata[index] = (byte) metadata; + if ((metadata >>> 8) != 0) { + if (highMetadata == null) { + highMetadata = new byte[size]; } - localBlocks[index] = (byte) tempblockId; - extraBlocks[index] = (byte) numextra; - localMetadata[index] = (byte) schematic.getBlockMetadata(x, y, z); + highMetadata[index] = (byte) (metadata >>> 8); + } + if (block != null) { String name = BLOCK_REGISTRY.getNameForObject(block); if (!mappings.containsKey(name)) { - mappings.put(name, (short) blockId); + mappings.put(name, blockId); } } } } + } - int count = 20; - NBTTagList tileEntitiesList = new NBTTagList(); - for (TileEntity tileEntity : schematic.getTileEntities()) { - try { - if (!tileEntity.hasWorldObj()) { - tileEntity.setWorldObj(backupWorld); - } - NBTTagCompound tileEntityTagCompound = NBTHelper.writeTileEntityToCompound(tileEntity); - tileEntitiesList.appendTag(tileEntityTagCompound); - } catch (Exception e) { - int pos = tileEntity.xCoord - + (tileEntity.yCoord * schematic.getLength() + tileEntity.zCoord) * schematic.getWidth(); - if (--count > 0) { - Block block = schematic.getBlock(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); - Reference.logger.error( - "Block {}[{}] with TileEntity %s failed to save! Replacing with bedrock...", - block, - block != null ? BLOCK_REGISTRY.getNameForObject(block) : "?", - tileEntity.getClass() - .getName(), - e); - } - localBlocks[pos] = (byte) BLOCK_REGISTRY.getId(Blocks.bedrock); - localMetadata[pos] = 0; - extraBlocks[pos] = 0; + int count = 20; + NBTTagList tileEntitiesList = new NBTTagList(); + for (TileEntity tileEntity : schematic.getTileEntities()) { + try { + if (!tileEntity.hasWorldObj()) { + tileEntity.setWorldObj(backupWorld); } - } - - final NBTTagList entityList = new NBTTagList(); - final List entities = schematic.getEntities(); - for (Entity entity : entities) { - try { - final NBTTagCompound entityCompound = NBTHelper.writeEntityToCompound(entity); - if (entityCompound != null) { - entityList.appendTag(entityCompound); - } - } catch (Throwable t) { - Reference.logger.error("Entity {} failed to save, skipping!", entity, t); + tileEntitiesList.appendTag(NBTHelper.writeTileEntityToCompound(tileEntity)); + } catch (Exception e) { + int pos = index(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, width, length); + if (--count > 0) { + Block block = schematic.getBlock(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); + Reference.logger.error( + "Block {}[{}] with TileEntity %s failed to save! Replacing with bedrock...", + block, + block != null ? BLOCK_REGISTRY.getNameForObject(block) : "?", + tileEntity.getClass() + .getName(), + e); } - } - - PreSchematicSaveEvent event = new PreSchematicSaveEvent(schematic, mappings); - MinecraftForge.EVENT_BUS.post(event); - - NBTTagCompound nbtMapping = new NBTTagCompound(); - for (Map.Entry entry : mappings.entrySet()) { - nbtMapping.setShort(entry.getKey(), entry.getValue()); - } - - tagCompound.setString(Names.NBT.MATERIALS, Names.NBT.FORMAT_ALPHA); - tagCompound.setByteArray(Names.NBT.BLOCKS, localBlocks); - tagCompound.setByteArray(Names.NBT.DATA, localMetadata); - tagCompound.setByteArray(Names.NBT.ADD_BLOCKS, extraBlocks); - tagCompound.setTag(Names.NBT.ENTITIES, entityList); - tagCompound.setTag(Names.NBT.TILE_ENTITIES, tileEntitiesList); - tagCompound.setTag(Names.NBT.MAPPING_SCHEMATICA, nbtMapping); - final NBTTagCompound extendedMetadata = event.extendedMetadata; - if (!extendedMetadata.hasNoTags()) { - tagCompound.setTag(Names.NBT.EXTENDED_METADATA, extendedMetadata); - } - - return true; - } else { - NBTTagCompound tagCompoundIcon = new NBTTagCompound(); - ItemStack icon = schematic.getIcon(); - icon.writeToNBT(tagCompoundIcon); - tagCompound.setTag(Names.NBT.ICON, tagCompoundIcon); - - tagCompound.setShort(Names.NBT.WIDTH, (short) schematic.getWidth()); - tagCompound.setShort(Names.NBT.LENGTH, (short) schematic.getLength()); - tagCompound.setShort(Names.NBT.HEIGHT, (short) schematic.getHeight()); - - int size = schematic.getWidth() * schematic.getLength() * schematic.getHeight(); - byte[] localBlocks = new byte[size]; - byte[] localMetadata = new byte[size]; - byte[] extraBlocks = new byte[size]; - byte[] extraBlocksNibble = new byte[(int) Math.ceil(size / 2.0)]; - boolean extra = false; - - Map mappings = new HashMap<>(); - for (int x = 0; x < schematic.getWidth(); x++) { - for (int y = 0; y < schematic.getHeight(); y++) { - for (int z = 0; z < schematic.getLength(); z++) { - final int index = x + (y * schematic.getLength() + z) * schematic.getWidth(); - final Block block = schematic.getBlock(x, y, z); - final int blockId = BLOCK_REGISTRY.getId(block); - localBlocks[index] = (byte) blockId; - localMetadata[index] = (byte) schematic.getBlockMetadata(x, y, z); - if ((extraBlocks[index] = (byte) (blockId >> 8)) > 0) { - extra = true; - } - - String name = BLOCK_REGISTRY.getNameForObject(block); - if (!mappings.containsKey(name)) { - mappings.put(name, (short) blockId); - } + if (pos >= 0 && pos < blockIds.length) { + int bedrockId = BLOCK_REGISTRY.getId(Blocks.bedrock); + blockIds[pos] = bedrockId < 0 ? 0 : bedrockId; + localMetadata[pos] = 0; + if (highMetadata != null) { + highMetadata[pos] = 0; } } } + } - int count = 20; - NBTTagList tileEntitiesList = new NBTTagList(); - for (TileEntity tileEntity : schematic.getTileEntities()) { - try { - if (!tileEntity.hasWorldObj()) { - tileEntity.setWorldObj(backupWorld); - } - NBTTagCompound tileEntityTagCompound = NBTHelper.writeTileEntityToCompound(tileEntity); - tileEntitiesList.appendTag(tileEntityTagCompound); - } catch (Exception e) { - int pos = tileEntity.xCoord - + (tileEntity.yCoord * schematic.getLength() + tileEntity.zCoord) * schematic.getWidth(); - if (--count > 0) { - Block block = schematic.getBlock(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); - Reference.logger.error( - "Block {}[{}] with TileEntity %s failed to save! Replacing with bedrock...", - block, - block != null ? BLOCK_REGISTRY.getNameForObject(block) : "?", - tileEntity.getClass() - .getName(), - e); - } - localBlocks[pos] = (byte) BLOCK_REGISTRY.getId(Blocks.bedrock); - localMetadata[pos] = 0; - extraBlocks[pos] = 0; + NBTTagList entityList = new NBTTagList(); + List entities = schematic.getEntities(); + for (Entity entity : entities) { + try { + NBTTagCompound entityCompound = NBTHelper.writeEntityToCompound(entity); + if (entityCompound != null) { + entityList.appendTag(entityCompound); } + } catch (Throwable t) { + Reference.logger.error("Entity {} failed to save, skipping!", entity, t); } + } - for (int i = 0; i < extraBlocksNibble.length; i++) { - if (i * 2 + 1 < extraBlocks.length) { - extraBlocksNibble[i] = (byte) ((extraBlocks[i * 2 + 0] << 4) | extraBlocks[i * 2 + 1]); - } else { - extraBlocksNibble[i] = (byte) (extraBlocks[i * 2 + 0] << 4); - } - } + PreSchematicSaveEvent event = new PreSchematicSaveEvent(schematic, mappings); + MinecraftForge.EVENT_BUS.post(event); - final NBTTagList entityList = new NBTTagList(); - final List entities = schematic.getEntities(); - for (Entity entity : entities) { - try { - final NBTTagCompound entityCompound = NBTHelper.writeEntityToCompound(entity); - if (entityCompound != null) { - entityList.appendTag(entityCompound); - } - } catch (Throwable t) { - Reference.logger.error("Entity {} failed to save, skipping!", entity, t); - } - } + BlockIdCodec.Encoded encoded = BlockIdCodec.encode(blockIds); + tagCompound.setString(Names.NBT.MATERIALS, Names.NBT.FORMAT_ALPHA); + tagCompound.setByteArray(Names.NBT.BLOCKS, encoded.blocks); + tagCompound.setByteArray(Names.NBT.DATA, localMetadata); + if (highMetadata != null) { + tagCompound.setByteArray(Names.NBT.DATA_HIGH, highMetadata); + } else { + tagCompound.removeTag(Names.NBT.DATA_HIGH); + } + tagCompound.removeTag(Names.NBT.ADD_BLOCKS_SCHEMATICA); + tagCompound.removeTag(Names.NBT.BLOCK_ID_BYTES); + tagCompound.removeTag(Names.NBT.ADD_BLOCKS); + tagCompound.removeTag(Names.NBT.ADD_BLOCKS_HIGH); + // A one-cell packed array otherwise looks like a legacy .schemplus high byte. + if (encoded.blockIdBytes > 1 || (size == 1 && encoded.addBlocks != null)) { + tagCompound.setByte(Names.NBT.BLOCK_ID_BYTES, (byte) encoded.blockIdBytes); + } + if (encoded.addBlocks != null) { + tagCompound.setByteArray(Names.NBT.ADD_BLOCKS, encoded.addBlocks); + } + if (encoded.addBlocksHigh != null) { + tagCompound.setByteArray(Names.NBT.ADD_BLOCKS_HIGH, encoded.addBlocksHigh); + } + tagCompound.setTag(Names.NBT.ENTITIES, entityList); + tagCompound.setTag(Names.NBT.TILE_ENTITIES, tileEntitiesList); + tagCompound.setTag(Names.NBT.MAPPING_SCHEMATICA, writeMapping(mappings)); + NBTTagCompound extendedMetadata = event.extendedMetadata; + if (!extendedMetadata.hasNoTags()) { + tagCompound.setTag(Names.NBT.EXTENDED_METADATA, extendedMetadata); + } else { + tagCompound.removeTag(Names.NBT.EXTENDED_METADATA); + } - PreSchematicSaveEvent event = new PreSchematicSaveEvent(schematic, mappings); - MinecraftForge.EVENT_BUS.post(event); + return true; + } - NBTTagCompound nbtMapping = new NBTTagCompound(); - for (Map.Entry entry : mappings.entrySet()) { - nbtMapping.setShort(entry.getKey(), entry.getValue()); - } + private static Map readMapping(NBTTagCompound tagCompound) { + Map oldToNew = new HashMap<>(); + if (!tagCompound.hasKey(Names.NBT.MAPPING_SCHEMATICA)) { + return oldToNew; + } - tagCompound.setString(Names.NBT.MATERIALS, Names.NBT.FORMAT_ALPHA); - tagCompound.setByteArray(Names.NBT.BLOCKS, localBlocks); - tagCompound.setByteArray(Names.NBT.DATA, localMetadata); - if (extra) { - tagCompound.setByteArray(Names.NBT.ADD_BLOCKS, extraBlocksNibble); - } - tagCompound.setTag(Names.NBT.ENTITIES, entityList); - tagCompound.setTag(Names.NBT.TILE_ENTITIES, tileEntitiesList); - tagCompound.setTag(Names.NBT.MAPPING_SCHEMATICA, nbtMapping); - final NBTTagCompound extendedMetadata = event.extendedMetadata; - if (!extendedMetadata.hasNoTags()) { - tagCompound.setTag(Names.NBT.EXTENDED_METADATA, extendedMetadata); - } + NBTTagCompound mapping = tagCompound.getCompoundTag(Names.NBT.MAPPING_SCHEMATICA); + for (String name : mapping.func_150296_c()) { + NBTBase stored = mapping.getTag(name); + int oldId = stored instanceof NBTTagShort ? mapping.getShort(name) & 0xFFFF : mapping.getInteger(name); + oldToNew.put(oldId, BLOCK_REGISTRY.getId(name)); + } + return oldToNew; + } - return true; + private static NBTTagCompound writeMapping(Map mappings) { + NBTTagCompound nbtMapping = new NBTTagCompound(); + for (Map.Entry entry : mappings.entrySet()) { + nbtMapping.setInteger(entry.getKey(), entry.getValue()); } + return nbtMapping; + } + + private static byte[] byteArrayOrNull(NBTTagCompound tagCompound, String key) { + return tagCompound.hasKey(key) ? tagCompound.getByteArray(key) : null; + } + + private static int index(int x, int y, int z, int width, int length) { + return x + (y * length + z) * width; } } diff --git a/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicFormat.java b/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicFormat.java index 1e75cae1..dfd5e701 100644 --- a/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicFormat.java +++ b/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicFormat.java @@ -11,6 +11,7 @@ import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; +import com.github.lunatrius.schematica.FileFilterSchematic; import com.github.lunatrius.schematica.api.ISchematic; import com.github.lunatrius.schematica.api.event.PostSchematicCaptureEvent; import com.github.lunatrius.schematica.reference.Names; @@ -35,6 +36,10 @@ public static ISchematic readFromFile(File file) { throw new UnsupportedFormatException(format); } + if (schematicFormat instanceof SchematicAlpha alphaFormat + && FileFilterSchematic.isSchemplusName(file.getName())) { + return alphaFormat.readFromNBT(tagCompound, true); + } return schematicFormat.readFromNBT(tagCompound); } catch (Exception ex) { Reference.logger.error("Failed to read schematic!", ex); diff --git a/src/main/java/com/github/lunatrius/schematica/world/storage/Schematic.java b/src/main/java/com/github/lunatrius/schematica/world/storage/Schematic.java index 680237f5..6e6bf1a6 100644 --- a/src/main/java/com/github/lunatrius/schematica/world/storage/Schematic.java +++ b/src/main/java/com/github/lunatrius/schematica/world/storage/Schematic.java @@ -21,8 +21,8 @@ public class Schematic implements ISchematic { private static final FMLControlledNamespacedRegistry BLOCK_REGISTRY = GameData.getBlockRegistry(); private ItemStack icon; - private final short[][][] blocks; - private final byte[][][] metadata; + private final int[][][] blocks; + private final char[][][] metadata; private final List tileEntities = new ArrayList<>(); private final List entities = new ArrayList<>(); private final int width; @@ -31,8 +31,8 @@ public class Schematic implements ISchematic { public Schematic(final ItemStack icon, final int width, final int height, final int length) { this.icon = icon; - this.blocks = new short[width][height][length]; - this.metadata = new byte[width][height][length]; + this.blocks = new int[width][height][length]; + this.metadata = new char[width][height][length]; this.width = width; this.height = height; @@ -64,7 +64,7 @@ public boolean setBlock(final int x, final int y, final int z, final Block block return false; } - this.blocks[x][y][z] = (short) id; + this.blocks[x][y][z] = id; setBlockMetadata(x, y, z, metadata); return true; } @@ -120,7 +120,7 @@ public boolean setBlockMetadata(final int x, final int y, final int z, final int return false; } - this.metadata[x][y][z] = (byte) (metadata & 0x0F); + this.metadata[x][y][z] = (char) metadata; return true; } diff --git a/src/main/resources/META-INF/schematica_at.cfg b/src/main/resources/META-INF/schematica_at.cfg index e2ba0869..f013db93 100644 --- a/src/main/resources/META-INF/schematica_at.cfg +++ b/src/main/resources/META-INF/schematica_at.cfg @@ -1,2 +1,10 @@ # Schematica public net.minecraft.nbt.NBTTagCompound func_150298_a(Ljava/lang/String;Lnet/minecraft/nbt/NBTBase;Ljava/io/DataOutput;)V # writeNamedTag +public net.minecraft.block.Block field_149759_B # minX +public net.minecraft.block.Block field_149760_C # minY +public net.minecraft.block.Block field_149754_D # minZ +public net.minecraft.block.Block field_149755_E # maxX +public net.minecraft.block.Block field_149756_F # maxY +public net.minecraft.block.Block field_149757_G # maxZ +public net.minecraftforge.client.ForgeHooksClient worldRenderPass +public net.minecraft.client.multiplayer.PlayerControllerMP func_78750_j()V # syncCurrentPlayItem diff --git a/src/main/resources/assets/schematica/lang/en_US.lang b/src/main/resources/assets/schematica/lang/en_US.lang index b850fad2..132defb5 100644 --- a/src/main/resources/assets/schematica/lang/en_US.lang +++ b/src/main/resources/assets/schematica/lang/en_US.lang @@ -158,3 +158,5 @@ schematica.command.download.usage=/schematicaDownload schematica.command.download.started=Started downloading %s... schematica.command.download.downloadSucceeded=Successfully downloaded %s. schematica.command.download.downloadFail=Download failed. +schematica.command.download.requiresUpdate=Update Schematica to download %s. Your client uses a different download format. +schematica.command.download.serverRequiresUpdate=The server uses a different Schematica download format. Update the server to download schematics. diff --git a/src/test/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodecTest.java b/src/test/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodecTest.java new file mode 100644 index 00000000..2aafac80 --- /dev/null +++ b/src/test/java/com/github/lunatrius/schematica/world/schematic/BlockIdCodecTest.java @@ -0,0 +1,117 @@ +package com.github.lunatrius.schematica.world.schematic; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import com.github.lunatrius.schematica.world.schematic.BlockIdCodec.Encoded; + +public class BlockIdCodecTest { + + private static final int[] SAMPLE_IDS = { 0, 255, 256, 4095, 4096, 11277, 32767, 32768, 65535, 65536, 16777215 }; + + @Test + public void classicFilesRoundTripWithoutTheWidthTag() { + int[] ids = { 0, 255, 256, 4095 }; + Encoded encoded = BlockIdCodec.encode(ids); + assertEquals(1, encoded.blockIdBytes); + int[] decoded = BlockIdCodec.decode(encoded.blocks, encoded.addBlocks, null, null, 0, false); + assertArrayEquals(ids, decoded); + } + + @Test + public void roundTripsUpTo24Bits() { + assertRoundTrip(SAMPLE_IDS, 3); + } + + @Test + public void keepsClassicLayoutWhenEveryIdFitsIn12Bits() { + int[] ids = { 0, 255, 256, 512, 4095 }; + Encoded encoded = assertRoundTrip(ids, 1); + assertNull(encoded.addBlocksHigh); + assertEquals(3, encoded.addBlocks.length); + assertEquals(0x00, encoded.blocks[2] & 0xFF); + assertEquals(0x12, encoded.addBlocks[1] & 0xFF); + } + + @Test + public void omitsAddBlocksWhenEveryIdFitsIn8Bits() { + Encoded encoded = assertRoundTrip(new int[] { 0, 1, 255 }, 1); + assertNull(encoded.addBlocks); + assertNull(encoded.addBlocksHigh); + } + + @Test + public void legacyTwelveBitFileDropsBitsAbove4095() { + byte[] blocks = { (byte) 0x0D }; + byte[] addBlocks = { (byte) 0xC0 }; + int[] ids = BlockIdCodec.decode(blocks, addBlocks, null, null, 0, false); + assertArrayEquals(new int[] { 3085 }, ids); + } + + @Test + public void writesTheReportedConcreteIdAsTwoBytes() { + Encoded encoded = assertRoundTrip(new int[] { 11277 }, 2); + assertEquals(0x0D, encoded.blocks[0] & 0xFF); + assertEquals(0x2C, encoded.addBlocks[0] & 0xFF); + assertNull(encoded.addBlocksHigh); + } + + @Test + public void oneBlockExtendedFileIsNotReadAsNibbles() { + Encoded encoded = BlockIdCodec.encode(new int[] { 4096 }); + assertEquals(2, encoded.blockIdBytes); + + int[] withTag = BlockIdCodec.decode(encoded.blocks, encoded.addBlocks, null, null, encoded.blockIdBytes, false); + assertArrayEquals(new int[] { 4096 }, withTag); + + int[] asClassicNibble = BlockIdCodec.decode(encoded.blocks, encoded.addBlocks, null, null, 0, false); + assertArrayEquals(new int[] { 256 }, asClassicNibble); + } + + @Test + public void readsLegacySchemplusBytesIncludingASingleBlock() { + byte[] blocks = { (byte) 0x0D }; + byte[] addBlocks = { (byte) 0x2C }; + int[] ids = BlockIdCodec.decode(blocks, addBlocks, null, null, 0, true); + assertArrayEquals(new int[] { 11277 }, ids); + } + + @Test + public void readsTheLegacyFullByteAddKey() { + byte[] blocks = { 0x00 }; + byte[] legacyAdd = { 0x02 }; + int[] ids = BlockIdCodec.decode(blocks, null, legacyAdd, null, 0, false); + assertArrayEquals(new int[] { 512 }, ids); + } + + @Test + public void readsAMultipleOf256ThatTheOldSchemplusWriterTruncated() { + byte[] blocks = { 0x00 }; + byte[] addBlocks = { 0x01 }; + int[] ids = BlockIdCodec.decode(blocks, addBlocks, null, null, 0, true); + assertArrayEquals(new int[] { 256 }, ids); + } + + @Test + public void omitsTheHighByteWhenNoIdNeedsIt() { + Encoded encoded = assertRoundTrip(new int[] { 1, 4096, 65535 }, 2); + assertNull(encoded.addBlocksHigh); + assertEquals(3, encoded.addBlocks.length); + } + + private static Encoded assertRoundTrip(int[] ids, int blockIdBytes) { + Encoded encoded = BlockIdCodec.encode(ids); + assertEquals(blockIdBytes, encoded.blockIdBytes); + int[] decoded = BlockIdCodec + .decode(encoded.blocks, encoded.addBlocks, null, encoded.addBlocksHigh, encoded.blockIdBytes, false); + assertArrayEquals(ids, decoded); + if (encoded.blockIdBytes == 1) { + int[] untagged = BlockIdCodec.decode(encoded.blocks, encoded.addBlocks, null, null, 0, false); + assertArrayEquals(ids, untagged); + } + return encoded; + } +} diff --git a/src/test/java/com/github/lunatrius/schematica/world/schematic/SchematicAlphaTest.java b/src/test/java/com/github/lunatrius/schematica/world/schematic/SchematicAlphaTest.java new file mode 100644 index 00000000..87a0d39c --- /dev/null +++ b/src/test/java/com/github/lunatrius/schematica/world/schematic/SchematicAlphaTest.java @@ -0,0 +1,210 @@ +package com.github.lunatrius.schematica.world.schematic; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.URL; +import java.util.Collections; + +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.init.Blocks; +import net.minecraft.init.Bootstrap; +import net.minecraft.item.ItemStack; +import net.minecraft.launchwrapper.Launch; +import net.minecraft.launchwrapper.LaunchClassLoader; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntitySkull; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import com.github.lunatrius.schematica.Schematica; +import com.github.lunatrius.schematica.api.ISchematic; +import com.github.lunatrius.schematica.client.util.BlockToItemStack; +import com.github.lunatrius.schematica.client.world.SchematicWorld; +import com.github.lunatrius.schematica.handler.DownloadHandler; +import com.github.lunatrius.schematica.network.message.MessageCapabilities; +import com.github.lunatrius.schematica.network.message.MessageDownloadBegin; +import com.github.lunatrius.schematica.network.message.MessageDownloadChunk; +import com.github.lunatrius.schematica.proxy.ServerProxy; +import com.github.lunatrius.schematica.reference.Names; +import com.github.lunatrius.schematica.world.storage.Schematic; + +import cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.network.ByteBufUtils; +import cpw.mods.fml.common.registry.FMLControlledNamespacedRegistry; +import cpw.mods.fml.common.registry.GameData; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; + +public class SchematicAlphaTest { + + @Rule + public final TemporaryFolder temp = new TemporaryFolder(); + + @Test + public void legacyFilesAndCurrentDownloadsPreserveWideBlockData() throws Exception { + runFixture("wideBlockData"); + } + + @Test + public void savedSkullOwnerMattersEvenWhenBlockMetadataMatches() throws Exception { + runFixture("skullOwners"); + } + + private void runFixture(String name) throws Exception { + // Forge's registry expects to be loaded by LaunchWrapper, including when no game is running. + final String[] entries = System.getProperty("java.class.path") + .split(File.pathSeparator); + final URL[] classpath = new URL[entries.length]; + for (int i = 0; i < entries.length; i++) { + classpath[i] = new File(entries[i]).toURI() + .toURL(); + } + final LaunchClassLoader previous = Launch.classLoader; + try (LaunchClassLoader loader = new LaunchClassLoader(classpath)) { + Launch.classLoader = loader; + loader.loadClass(Fixture.class.getName()) + .getMethod(name, File.class) + .invoke(null, this.temp.getRoot()); + } finally { + Launch.classLoader = previous; + } + } + + public static class Fixture { + + private static void bootstrap(File gameDir) throws ReflectiveOperationException { + Loader.injectData("7", "10", "99", "99", "1.7.10", "9.05", gameDir, Collections.emptyList()); + // Simulate a discovered mod list for compatibility checks in the headless fixture. + final Field namedMods = Loader.class.getDeclaredField("namedMods"); + namedMods.setAccessible(true); + namedMods.set(Loader.instance(), Collections.emptyMap()); + Bootstrap.func_151354_b(); + Schematica.proxy = new ServerProxy() { + + @Override + public File getDataDirectory() { + return gameDir; + } + }; + } + + public static void skullOwners(File gameDir) throws ReflectiveOperationException { + bootstrap(gameDir); + final SchematicWorld expected = skullWorld("Builder"); + final SchematicWorld different = skullWorld("Other"); + final SchematicWorld same = skullWorld("builder"); + assertFalse(BlockToItemStack.matchesSavedState(Blocks.skull, null, different, 0, 0, 0, expected, 0, 0, 0)); + assertTrue(BlockToItemStack.matchesSavedState(Blocks.skull, null, same, 0, 0, 0, expected, 0, 0, 0)); + } + + private static SchematicWorld skullWorld(String owner) { + final Schematic schematic = new Schematic(new ItemStack(Blocks.stone), 1, 1, 1); + assertTrue(schematic.setBlock(0, 0, 0, Blocks.skull, 1)); + final TileEntitySkull skull = new TileEntitySkull(); + final NBTTagCompound data = new NBTTagCompound(); + data.setByte("SkullType", (byte) 3); + final NBTTagCompound profile = new NBTTagCompound(); + profile.setString("Name", owner); + data.setTag("Owner", profile); + skull.readFromNBT(data); + schematic.setTileEntity(0, 0, 0, skull); + return new SchematicWorld(schematic); + } + + public static void wideBlockData(File gameDir) throws Exception { + bootstrap(gameDir); + final Method register = FMLControlledNamespacedRegistry.class + .getDeclaredMethod("addObjectRaw", int.class, String.class, Object.class); + register.setAccessible(true); + final int[] ids = { 0x10C, 0xFEBA, 0x20D, 0x1000, 0xFFFF, 0x10006 }; + final int[] metadata = { 3, 0xFF, 0x100, 0xABCD, 0xFFFF, 0xFE01 }; + final Block[] blocks = new Block[ids.length]; + final Schematic source = new Schematic(new ItemStack(Blocks.stone), ids.length, 1, 1); + for (int x = 0; x < ids.length; x++) { + blocks[x] = new Block(Material.rock) {}; + register.invoke(GameData.getBlockRegistry(), ids[x], "fixture:block" + x, blocks[x]); + assertTrue(source.setBlock(x, 0, 0, blocks[x], metadata[x])); + } + final SchematicAlpha format = new SchematicAlpha(); + final NBTTagCompound tags = new NBTTagCompound(); + + assertTrue(format.writeToNBT(tags, source, null)); + assertEquals(3, tags.getByte(Names.NBT.BLOCK_ID_BYTES)); + assertCells(format.readFromNBT(tags), blocks, metadata); + + // Older compatibility builds wrote Add with one high byte per cell and a packed preview. + final NBTTagCompound branchTags = new NBTTagCompound(); + branchTags.setShort(Names.NBT.WIDTH, (short) 2); + branchTags.setShort(Names.NBT.HEIGHT, (short) 1); + branchTags.setShort(Names.NBT.LENGTH, (short) 1); + branchTags.setByteArray(Names.NBT.BLOCKS, new byte[] { 0x0C, (byte) 0xBA }); + branchTags.setByteArray(Names.NBT.ADD_BLOCKS, new byte[] { 0x1E }); + branchTags.setByteArray(Names.NBT.ADD_BLOCKS_SCHEMATICA, new byte[] { 1, (byte) 0xFE }); + branchTags.setByteArray(Names.NBT.DATA, new byte[] { 3, (byte) 0xFF }); + assertCells(format.readFromNBT(branchTags), new Block[] { blocks[0], blocks[1] }, new int[] { 3, 0xFF }); + + final File download = new File(gameDir, "download.schemplus"); + final Schematic single = new Schematic(source.getIcon(), 1, 1, 1); + assertTrue(single.setBlock(0, 0, 0, blocks[0], 3)); + assertTrue(SchematicFormat.writeToFile(download, single, null)); + assertCells(SchematicFormat.readFromFile(download), new Block[] { blocks[0] }, new int[] { 3 }); + + assertTrue(format.writeToNBT(tags, single, null)); + assertEquals(1, tags.getByte(Names.NBT.BLOCK_ID_BYTES)); + assertFalse(tags.hasKey(Names.NBT.DATA_HIGH)); + assertFalse(tags.hasKey(Names.NBT.ADD_BLOCKS_HIGH)); + assertCells(format.readFromNBT(tags, true), new Block[] { blocks[0] }, new int[] { 3 }); + + assertDownloadRoundTrip(source, blocks, metadata); + } + + private static void assertDownloadRoundTrip(Schematic source, Block[] blocks, int[] metadata) throws Exception { + final ByteBuf packet = Unpooled.buffer(); + try { + new MessageCapabilities(true, true, true).toBytes(packet); + packet.skipBytes(3); + assertEquals(DownloadHandler.PROTOCOL_VERSION, packet.readUnsignedByte()); + packet.clear(); + new MessageDownloadBegin(source).toBytes(packet); + final ByteBuf legacyReader = packet.duplicate(); + ByteBufUtils.readItemStack(legacyReader); + assertEquals(0, legacyReader.readShort()); + assertEquals(0, legacyReader.readShort()); + assertEquals(0, legacyReader.readShort()); + final MessageDownloadBegin begin = new MessageDownloadBegin(); + begin.fromBytes(packet); + assertEquals(source.getWidth(), begin.width); + assertFalse(packet.isReadable()); + + packet.clear(); + new MessageDownloadChunk(source, 0, 0, 0).toBytes(packet); + final MessageDownloadChunk chunk = new MessageDownloadChunk(); + chunk.fromBytes(packet); + assertFalse(packet.isReadable()); + final Schematic result = new Schematic(source.getIcon(), begin.width, begin.height, begin.length); + final Method copy = MessageDownloadChunk.class.getDeclaredMethod("copyToSchematic", ISchematic.class); + copy.setAccessible(true); + copy.invoke(chunk, result); + assertCells(result, blocks, metadata); + } finally { + packet.release(); + } + } + + private static void assertCells(ISchematic schematic, Block[] blocks, int[] metadata) { + for (int x = 0; x < blocks.length; x++) { + assertSame(blocks[x], schematic.getBlock(x, 0, 0)); + assertEquals(metadata[x], schematic.getBlockMetadata(x, 0, 0)); + } + } + } +}