diff --git a/.gitignore b/.gitignore index 45ef58e4fd..e36e8909e8 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,7 @@ run_server #Custom code to inject the the dev environment custom +test-results #licnse_checker # Not in git because it contains names + emails. diff --git a/BuildCraftAPI b/BuildCraftAPI index 7959a191ac..fbd8c15d4f 160000 --- a/BuildCraftAPI +++ b/BuildCraftAPI @@ -1 +1 @@ -Subproject commit 7959a191acfc22bcc0eee25444744244036558dc +Subproject commit fbd8c15d4f0482cd98fef63245b5a6b8e362315b diff --git a/buildcraft_resources/assets/buildcraft/lang/en_US.lang b/buildcraft_resources/assets/buildcraft/lang/en_US.lang index f615f4259d..fdd8e73cc9 100644 --- a/buildcraft_resources/assets/buildcraft/lang/en_US.lang +++ b/buildcraft_resources/assets/buildcraft/lang/en_US.lang @@ -485,7 +485,7 @@ itemGroup.buildcraft.boards=BuildCraft Robots itemGroup.buildcraft.main=BuildCraft itemGroup.buildcraft.pipes=BuildCraft Pipes itemGroup.buildcraft.facades=BuildCraft Facades -itemGroup.buildcraft.gates=BuildCraft Gates +itemGroup.buildcraft.plugs=BuildCraft Pluggables tile.architectBlock.name=Architect Table tile.assemblyTableBlock.name=Assembly Table diff --git a/buildcraft_resources/assets/buildcrafttransport/models/plugs/blocker.json b/buildcraft_resources/assets/buildcrafttransport/models/plugs/blocker.json index 329226a2c8..b30bdf342f 100644 --- a/buildcraft_resources/assets/buildcrafttransport/models/plugs/blocker.json +++ b/buildcraft_resources/assets/buildcrafttransport/models/plugs/blocker.json @@ -3,11 +3,11 @@ "#all":"buildcrafttransport:pipes/plug", "particle":"#all" }, - "shade": true, "elements": [ { "from": [ 2, 4, 4 ], "to": [ 4, 12, 12 ], + "shade": true, "faces": { "down": { "uv": [ 2, 4, 4, 12 ], "texture": "#all" }, "up": { "uv": [ 2, 4, 4, 12 ], "texture": "#all" }, diff --git a/buildcraft_resources/assets/buildcrafttransport/models/plugs/daylight_sensor.json b/buildcraft_resources/assets/buildcrafttransport/models/plugs/daylight_sensor.json index 09221c73f0..38dbc69cb2 100644 --- a/buildcraft_resources/assets/buildcrafttransport/models/plugs/daylight_sensor.json +++ b/buildcraft_resources/assets/buildcrafttransport/models/plugs/daylight_sensor.json @@ -3,16 +3,16 @@ "#all":"buildcrafttransport:plugs/daylight_sensor", "particle":"#all" }, - "shade": true, "elements": [ { "from": [ 2, 5, 5 ], "to": [ 4, 11, 11 ], + "shade": true, "faces": { - "down": { "uv": [ 5, 11, 11, 13 ], "texture": "#all" }, - "up": { "uv": [ 5, 11, 11, 13 ], "texture": "#all" }, - "north": { "uv": [ 5, 11, 11, 13 ], "texture": "#all" }, - "south": { "uv": [ 5, 11, 11, 13 ], "texture": "#all" }, + "down": { "uv": [ 3, 5, 5, 11 ], "texture": "#all" }, + "up": { "uv": [ 3, 5, 5, 11 ], "texture": "#all" }, + "north": { "uv": [ 3, 5, 5, 11 ], "texture": "#all" }, + "south": { "uv": [ 3, 5, 5, 11 ], "texture": "#all" }, "west": { "uv": [ 5, 5, 11, 11 ], "texture": "#all" }, "east": { "uv": [ 5, 5, 11, 11 ], "texture": "#all" } } diff --git a/common/buildcraft/builders/BCBuilders.java b/common/buildcraft/builders/BCBuilders.java index 5235b930c6..652f114275 100644 --- a/common/buildcraft/builders/BCBuilders.java +++ b/common/buildcraft/builders/BCBuilders.java @@ -4,6 +4,8 @@ * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package buildcraft.builders; +import java.util.function.Consumer; + import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.*; import net.minecraftforge.fml.common.network.NetworkRegistry; @@ -12,6 +14,9 @@ import buildcraft.core.BCCore; import buildcraft.lib.BCLib; import buildcraft.lib.registry.RegistryHelper; +import buildcraft.lib.registry.TagManager; +import buildcraft.lib.registry.TagManager.EnumTagType; +import buildcraft.lib.registry.TagManager.TagEntry; //@formatter:off @Mod(modid = BCBuilders.MODID, @@ -56,4 +61,45 @@ public static void onServerStarting(FMLServerStartingEvent event) { public static void onServerStopping(FMLServerStoppingEvent event) { PerSaveBptStorage.onServerStopping(); } + + static { + startBatch(); + // Items + registerTag("item.schematic.single").reg("schematic_single").locale("schematicSingle").model("schematic_single/"); + registerTag("item.blueprint").reg("blueprint").locale("blueprintItem").model("blueprint/"); + // Item Blocks + registerTag("item.block.architect").reg("architect").locale("architectBlock").model("architect"); + registerTag("item.block.builder").reg("builder").locale("builderBlock").model("builder"); + registerTag("item.block.filler").reg("filler").locale("fillerBlock").model("filler"); + registerTag("item.block.library").reg("library").locale("libraryBlock").model("library"); + registerTag("item.block.frame").reg("frame").locale("frameBlock").model("frame"); + registerTag("item.block.quarry").reg("quarry").locale("quarryBlock").model("quarry"); + // Blocks + registerTag("block.architect").reg("architect").locale("architectBlock").model("architect"); + registerTag("block.builder").reg("builder").locale("builderBlock").model("builder"); + registerTag("block.filler").reg("filler").locale("fillerBlock").model("filler"); + registerTag("block.library").reg("library").locale("libraryBlock").model("library"); + registerTag("block.frame").reg("frame").locale("frameBlock").model("frame"); + registerTag("block.quarry").reg("quarry").locale("quarryBlock").model("quarry"); + // Tiles + registerTag("tile.architect").reg("architect"); + registerTag("tile.library").reg("library"); + registerTag("tile.builder").reg("builder"); + registerTag("tile.filler").reg("filler"); + registerTag("tile.quarry").reg("quarry"); + + endBatch(TagManager.prependTags("buildcraftbuilders:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION).andThen(TagManager.setTab("buildcraft.main"))); + } + + private static TagEntry registerTag(String id) { + return TagManager.registerTag(id); + } + + private static void startBatch() { + TagManager.startBatch(); + } + + private static void endBatch(Consumer consumer) { + TagManager.endBatch(consumer); + } } diff --git a/common/buildcraft/core/BCCore.java b/common/buildcraft/core/BCCore.java index 689fc30e98..9ab485c1f1 100644 --- a/common/buildcraft/core/BCCore.java +++ b/common/buildcraft/core/BCCore.java @@ -5,6 +5,7 @@ package buildcraft.core; import java.io.File; +import java.util.function.Consumer; import net.minecraft.init.Blocks; @@ -24,14 +25,17 @@ import buildcraft.lib.marker.MarkerCache; import buildcraft.lib.registry.CreativeTabManager; import buildcraft.lib.registry.CreativeTabManager.CreativeTabBC; +import buildcraft.lib.registry.TagManager; +import buildcraft.lib.registry.TagManager.EnumTagType; +import buildcraft.lib.registry.TagManager.TagEntry; @Mod(// - modid = BCCore.MODID,// - name = "BuildCraft Core",// - version = BCLib.VERSION,// - dependencies = "required-after:buildcraftlib@[" + BCLib.VERSION + "]",// - acceptedMinecraftVersions = "[1.11.2]",// - guiFactory = "buildcraft.core.client.ConfigGuiFactoryBC"// + modid = BCCore.MODID,// + name = "BuildCraft Core",// + version = BCLib.VERSION,// + dependencies = "required-after:buildcraftlib@[" + BCLib.VERSION + "]",// + acceptedMinecraftVersions = "[1.11.2]",// + guiFactory = "buildcraft.core.client.ConfigGuiFactoryBC"// ) public class BCCore { public static final String MODID = "buildcraftcore"; @@ -51,7 +55,7 @@ public static void preInit(FMLPreInitializationEvent event) { BCCoreConfig.preInit(cfgFolder); BCCoreProxy.getProxy().fmlPreInit(); - CreativeTabBC tab= CreativeTabManager.createTab("buildcraft.main"); + CreativeTabBC tab = CreativeTabManager.createTab("buildcraft.main"); BCCoreItems.preInit(); BCCoreBlocks.preInit(); @@ -82,4 +86,55 @@ public static void postInit(FMLPostInitializationEvent event) { BCCoreProxy.getProxy().fmlPostInit(); BCCoreConfig.postInit(); } + + static { + startBatch(); + // Items + registerTag("item.wrench").reg("wrench").locale("wrenchItem").oldReg("wrenchItem").model("wrench"); + registerTag("item.diamond.shard").reg("diamond_shard").locale("diamondShard").model("diamond_shard").tab("vanilla.materials"); + registerTag("item.gear.wood").reg("gear_wood").locale("woodenGearItem").oreDict("gearWood").oldReg("woodenGearItem").model("gears/wood"); + registerTag("item.gear.stone").reg("gear_stone").locale("stoneGearItem").oreDict("gearStone").oldReg("stoneGearItem").model("gears/stone"); + registerTag("item.gear.iron").reg("gear_iron").locale("ironGearItem").oreDict("gearIron").oldReg("ironGearItem").model("gears/iron"); + registerTag("item.gear.gold").reg("gear_gold").locale("goldGearItem").oreDict("gearGold").oldReg("goldGearItem").model("gears/gold"); + registerTag("item.gear.diamond").reg("gear_diamond").locale("diamondGearItem").oreDict("gearDiamond").oldReg("diamondGearItem").model("gears/diamond"); + registerTag("item.list").reg("list").locale("list").oldReg("listItem").model("list_"); + registerTag("item.map_location").reg("map_location").locale("mapLocation").oldReg("mapLocation").model("map_location/"); + registerTag("item.paintbrush").reg("paintbrush").locale("paintbrush").model("paintbrush/"); + registerTag("item.marker_connector").reg("marker_connector").locale("markerConnector").model("marker_connector"); + registerTag("item.volume_marker").reg("volume_marker").locale("volume_marker").model("volume_marker"); + // Item Blocks + registerTag("item.block.marker.volume").reg("marker_volume").locale("markerBlock").oldReg("markerBlock").model("marker_volume"); + registerTag("item.block.marker.path").reg("marker_path").locale("pathMarkerBlock").oldReg("pathMarkerBlock").model("marker_path"); + registerTag("item.block.spring").reg("spring").locale("spring").model("spring"); + registerTag("item.block.decorated").reg("decorated").locale("decorated").model("decorated/"); + registerTag("item.block.engine.bc").reg("engine").locale("engineBlock").model("engine/"); + // Blocks + registerTag("block.spring").reg("spring").locale("spring"); + registerTag("block.decorated").reg("decorated").locale("decorated"); + registerTag("block.engine.bc").reg("engine").locale("engineBlock").oldReg("engineBlock"); + registerTag("block.engine.bc.wood").locale("engineBlockWood"); + registerTag("block.engine.bc.stone").locale("engineBlockStone"); + registerTag("block.engine.bc.iron").locale("engineBlockIron"); + registerTag("block.engine.bc.creative").locale("engineBlockCreative"); + registerTag("block.marker.volume").reg("marker_volume").locale("markerBlock").oldReg("markerBlock").model("marker_volume"); + registerTag("block.marker.path").reg("marker_path").locale("pathMarkerBlock").oldReg("pathMarkerBlock").model("marker_path"); + // Tiles + registerTag("tile.marker.volume").reg("marker.volume").oldReg("buildcraft.builders.Marker", "Marker"); + registerTag("tile.marker.path").reg("marker.path"); + registerTag("tile.engine.wood").reg("engine.wood"); + + endBatch(TagManager.prependTags("buildcraftcore:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION).andThen(TagManager.setTab("buildcraft.main"))); + } + + private static TagEntry registerTag(String id) { + return TagManager.registerTag(id); + } + + private static void startBatch() { + TagManager.startBatch(); + } + + private static void endBatch(Consumer consumer) { + TagManager.endBatch(consumer); + } } diff --git a/common/buildcraft/core/item/ItemWrench_Neptune.java b/common/buildcraft/core/item/ItemWrench_Neptune.java index ab4a4d24e8..16ea11047c 100644 --- a/common/buildcraft/core/item/ItemWrench_Neptune.java +++ b/common/buildcraft/core/item/ItemWrench_Neptune.java @@ -40,7 +40,7 @@ public void wrenchUsed(EntityPlayer player, EnumHand hand, ItemStack wrench, Ray @Override public boolean doesSneakBypassUse(ItemStack stack, IBlockAccess world, BlockPos pos, EntityPlayer player) { - return true; + return false; } @Override diff --git a/common/buildcraft/energy/BCEnergy.java b/common/buildcraft/energy/BCEnergy.java index aca9d3787a..405c76f141 100644 --- a/common/buildcraft/energy/BCEnergy.java +++ b/common/buildcraft/energy/BCEnergy.java @@ -4,6 +4,8 @@ * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package buildcraft.energy; +import java.util.function.Consumer; + import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fml.common.Mod; @@ -20,6 +22,9 @@ import buildcraft.energy.generation.OilPopulate; import buildcraft.lib.BCLib; import buildcraft.lib.registry.RegistryHelper; +import buildcraft.lib.registry.TagManager; +import buildcraft.lib.registry.TagManager.EnumTagType; +import buildcraft.lib.registry.TagManager.TagEntry; //@formatter:off @Mod(modid = BCEnergy.MODID, @@ -63,4 +68,32 @@ public void postInit(FMLPostInitializationEvent evt) { MinecraftForge.EVENT_BUS.register(OilPopulate.INSTANCE); BCEnergyProxy.getProxy().fmlPostInit(); } + + static { + startBatch(); + // Items + registerTag("item.glob.oil").reg("glob_oil").locale("globOil").model("glob_oil"); + + // Item Blocks + + // Blocks + + // Tiles + registerTag("tile.engine.stone").reg("engine.stone"); + registerTag("tile.engine.iron").reg("engine.iron"); + + endBatch(TagManager.prependTags("buildcraftenergy:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION).andThen(TagManager.setTab("buildcraft.main"))); + } + + private static TagEntry registerTag(String id) { + return TagManager.registerTag(id); + } + + private static void startBatch() { + TagManager.startBatch(); + } + + private static void endBatch(Consumer consumer) { + TagManager.endBatch(consumer); + } } diff --git a/common/buildcraft/factory/BCFactory.java b/common/buildcraft/factory/BCFactory.java index 2525e8209a..8258833ff1 100644 --- a/common/buildcraft/factory/BCFactory.java +++ b/common/buildcraft/factory/BCFactory.java @@ -4,6 +4,8 @@ * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package buildcraft.factory; +import java.util.function.Consumer; + import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent; @@ -14,6 +16,9 @@ import buildcraft.core.BCCore; import buildcraft.lib.BCLib; import buildcraft.lib.registry.RegistryHelper; +import buildcraft.lib.registry.TagManager; +import buildcraft.lib.registry.TagManager.EnumTagType; +import buildcraft.lib.registry.TagManager.TagEntry; //@formatter:off @Mod(modid = BCFactory.MODID, @@ -35,7 +40,7 @@ public void preInit(FMLPreInitializationEvent evt) { BCFactoryBlocks.preInit(); NetworkRegistry.INSTANCE.registerGuiHandler(INSTANCE, BCFactoryProxy.getProxy()); - + MinecraftForge.EVENT_BUS.register(BCFactoryEventDist.INSTANCE); } @@ -49,4 +54,51 @@ public void init(FMLInitializationEvent evt) { public void postInit(FMLPostInitializationEvent evt) { } + + static { + + startBatch();// factory + // BC Factory Items + registerTag("item.plastic.sheet").reg("plastic_sheet").locale("plasticSheet").oldReg("plasticSheet").model("plastic_sheet"); + registerTag("item.water_gel_spawn").reg("water_gel_spawn").locale("waterGel").model("water_gel"); + registerTag("item.gel").reg("gel").locale("gel").model("gel"); + // BC Factory Item Blocks + registerTag("item.block.plastic").reg("plastic_block").locale("plasticBlock").model("plastic_block/"); + registerTag("item.block.autoworkbench.item").reg("autoworkbench_item").locale("autoWorkbenchBlock").model("autoworkbench_item"); + registerTag("item.block.mining_well").reg("mining_well").locale("miningWellBlock").model("mining_well"); + registerTag("item.block.pump").reg("pump").locale("pumpBlock").model("pump"); + registerTag("item.block.flood_gate").reg("flood_gate").locale("floodGateBlock").model("flood_gate"); + registerTag("item.block.tank").reg("tank").locale("tankBlock").model("tank"); + registerTag("item.block.chute").reg("chute").locale("chuteBlock").model("chute"); + // BC Factory Blocks + registerTag("block.plastic").reg("plastic").locale("plasticBlock").model("plastic"); + registerTag("block.autoworkbench.item").reg("autoworkbench_item").oldReg("autoWorkbenchBlock").locale("autoWorkbenchBlock").model("autoworkbench_item"); + registerTag("block.mining_well").reg("mining_well").oldReg("miningWellBlock").locale("miningWellBlock").model("mining_well"); + registerTag("block.pump").reg("pump").oldReg("pumpBlock").locale("pumpBlock").model("pump"); + registerTag("block.flood_gate").reg("flood_gate").oldReg("floodGateBlock").locale("floodGateBlock").model("flood_gate"); + registerTag("block.tank").reg("tank").oldReg("tankBlock").locale("tankBlock").model("tank"); + registerTag("block.chute").reg("chute").oldReg("chuteBlock").locale("chuteBlock").model("chute"); + registerTag("block.water_gel").reg("water_gel").locale("waterGel").model("water_gel"); + // BC Factory Tiles + registerTag("tile.autoworkbench.item").reg("autoworkbench_item"); + registerTag("tile.mining_well").reg("mining_well"); + registerTag("tile.pump").reg("pump"); + registerTag("tile.flood_gate").reg("flood_gate"); + registerTag("tile.tank").reg("tank"); + registerTag("tile.chute").reg("chute"); + + endBatch(TagManager.prependTags("buildcraftfactory:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION).andThen(TagManager.setTab("buildcraft.main"))); + } + + private static TagEntry registerTag(String id) { + return TagManager.registerTag(id); + } + + private static void startBatch() { + TagManager.startBatch(); + } + + private static void endBatch(Consumer consumer) { + TagManager.endBatch(consumer); + } } diff --git a/common/buildcraft/lib/BCLib.java b/common/buildcraft/lib/BCLib.java index fc167d72fd..c7be33cda2 100644 --- a/common/buildcraft/lib/BCLib.java +++ b/common/buildcraft/lib/BCLib.java @@ -4,6 +4,8 @@ * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package buildcraft.lib; +import java.util.function.Consumer; + import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.Instance; @@ -31,6 +33,9 @@ import buildcraft.lib.net.cache.BuildCraftObjectCaches; import buildcraft.lib.recipe.AssemblyRecipeRegistry; import buildcraft.lib.recipe.IntegrationRecipeRegistry; +import buildcraft.lib.registry.TagManager; +import buildcraft.lib.registry.TagManager.EnumTagType; +import buildcraft.lib.registry.TagManager.TagEntry; //@formatter:off @Mod(modid = BCLib.MODID, @@ -102,4 +107,23 @@ public static void postInit(FMLPostInitializationEvent evt) { public static void onServerStarted(FMLServerStartedEvent evt) { BCLibEventDist.onServerStarted(evt); } + + static { + startBatch(); + registerTag("item.guide").reg("guide").locale("guide").model("guide").tab("vanilla.misc"); + registerTag("item.debugger").reg("debugger").locale("debugger").model("debugger").tab("vanilla.misc"); + endBatch(TagManager.prependTags("buildcraftlib:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION)); + } + + private static TagEntry registerTag(String id) { + return TagManager.registerTag(id); + } + + private static void startBatch() { + TagManager.startBatch(); + } + + private static void endBatch(Consumer consumer) { + TagManager.endBatch(consumer); + } } diff --git a/common/buildcraft/lib/client/model/ModelUtil.java b/common/buildcraft/lib/client/model/ModelUtil.java index f6c7621aec..9935ebb300 100644 --- a/common/buildcraft/lib/client/model/ModelUtil.java +++ b/common/buildcraft/lib/client/model/ModelUtil.java @@ -36,22 +36,22 @@ public UvFaceData(float uMin, float uMax, float vMin, float vMax) { } public static MutableQuad createFace(EnumFacing face, Tuple3f a, Tuple3f b, Tuple3f c, Tuple3f d, UvFaceData uvs) { - MutableQuad mutable = new MutableQuad(-1, face); + MutableQuad quad = new MutableQuad(-1, face); if (uvs == null) { uvs = UvFaceData.DEFAULT; } if (face == null || shouldInvertForRender(face)) { - mutable.getVertex(0).positionv(a).texf(uvs.uMin, uvs.vMin); - mutable.getVertex(1).positionv(b).texf(uvs.uMin, uvs.vMax); - mutable.getVertex(2).positionv(c).texf(uvs.uMax, uvs.vMax); - mutable.getVertex(3).positionv(d).texf(uvs.uMax, uvs.vMin); + quad.vertex_0.positionv(a).texf(uvs.uMin, uvs.vMin); + quad.vertex_1.positionv(b).texf(uvs.uMin, uvs.vMax); + quad.vertex_2.positionv(c).texf(uvs.uMax, uvs.vMax); + quad.vertex_3.positionv(d).texf(uvs.uMax, uvs.vMin); } else { - mutable.getVertex(3).positionv(a).texf(uvs.uMin, uvs.vMin); - mutable.getVertex(2).positionv(b).texf(uvs.uMin, uvs.vMax); - mutable.getVertex(1).positionv(c).texf(uvs.uMax, uvs.vMax); - mutable.getVertex(0).positionv(d).texf(uvs.uMax, uvs.vMin); + quad.vertex_3.positionv(a).texf(uvs.uMin, uvs.vMin); + quad.vertex_2.positionv(b).texf(uvs.uMin, uvs.vMax); + quad.vertex_1.positionv(c).texf(uvs.uMax, uvs.vMax); + quad.vertex_0.positionv(d).texf(uvs.uMax, uvs.vMin); } - return mutable; + return quad; } public static MutableQuad createFace(EnumFacing face, T[] points, UvFaceData uvs) { @@ -64,12 +64,12 @@ public static MutableQuad createFace(EnumFacing face, Tuple3f center, Tuple3f ra } public static MutableQuad createInverseFace(EnumFacing face, Tuple3f center, Tuple3f radius, UvFaceData uvs) { - return createFace(face, center, radius, uvs).invertNormal(); + return createFace(face, center, radius, uvs).copyAndInvertNormal(); } public static MutableQuad[] createDoubleFace(EnumFacing face, Tuple3f center, Tuple3f radius, UvFaceData uvs) { MutableQuad norm = createFace(face, center, radius, uvs); - return new MutableQuad[] { norm, new MutableQuad(norm).invertNormal() }; + return new MutableQuad[] { norm, norm.copyAndInvertNormal() }; } public static Point3f[] getPointsForFace(EnumFacing face, Tuple3f center, Tuple3f radius) { diff --git a/common/buildcraft/lib/client/model/MutableQuad.java b/common/buildcraft/lib/client/model/MutableQuad.java index c044c8170f..ebebcce3f2 100644 --- a/common/buildcraft/lib/client/model/MutableQuad.java +++ b/common/buildcraft/lib/client/model/MutableQuad.java @@ -10,6 +10,9 @@ import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3i; +import buildcraft.lib.expression.VecDouble; +import buildcraft.lib.expression.VecLong; + /** Holds all of the information necessary to make a {@link BakedQuad}. This provides a variety of methods to quickly * set or get different elements. * @@ -17,12 +20,18 @@ public class MutableQuad { public static final MutableQuad[] EMPTY_ARRAY = new MutableQuad[0]; - private final MutableVertex[] verticies = new MutableVertex[4]; + public final MutableVertex vertex_0 = new MutableVertex(); + public final MutableVertex vertex_1 = new MutableVertex(); + public final MutableVertex vertex_2 = new MutableVertex(); + public final MutableVertex vertex_3 = new MutableVertex(); + private int tintIndex = -1; private EnumFacing face = null; private boolean shade = false; private TextureAtlasSprite sprite = null; + public MutableQuad() {} + public MutableQuad(int tintIndex, EnumFacing face) { this(tintIndex, face, false); } @@ -31,18 +40,10 @@ public MutableQuad(int tintIndex, EnumFacing face, boolean shade) { this.tintIndex = tintIndex; this.face = face; this.shade = shade; - for (int v = 0; v < 4; v++) { - verticies[v] = new MutableVertex(); - } } public MutableQuad(MutableQuad from) { - this.tintIndex = from.tintIndex; - this.face = from.face; - for (int i = 0; i < 4; i++) { - this.verticies[i] = new MutableVertex(from.verticies[i]); - } - this.sprite = from.sprite; + copyFrom(from); } public MutableQuad copyFrom(MutableQuad from) { @@ -50,9 +51,10 @@ public MutableQuad copyFrom(MutableQuad from) { face = from.face; shade = from.shade; sprite = from.sprite; - for (int i = 0; i < 4; i++) { - verticies[i].copyFrom(from.verticies[i]); - } + vertex_0.copyFrom(from.vertex_0); + vertex_1.copyFrom(from.vertex_1); + vertex_2.copyFrom(from.vertex_2); + vertex_3.copyFrom(from.vertex_3); return this; } @@ -92,19 +94,19 @@ public TextureAtlasSprite getSprite() { public BakedQuad toBakedBlock() { int[] data = new int[28]; - verticies[0].toBakedBlock(data, 0); - verticies[1].toBakedBlock(data, 7); - verticies[2].toBakedBlock(data, 14); - verticies[3].toBakedBlock(data, 21); + vertex_0.toBakedBlock(data, 0); + vertex_1.toBakedBlock(data, 7); + vertex_2.toBakedBlock(data, 14); + vertex_3.toBakedBlock(data, 21); return new BakedQuad(data, tintIndex, face, sprite, shade, DefaultVertexFormats.BLOCK); } public BakedQuad toBakedItem() { int[] data = new int[28]; - verticies[0].toBakedItem(data, 0); - verticies[1].toBakedItem(data, 7); - verticies[2].toBakedItem(data, 14); - verticies[3].toBakedItem(data, 21); + vertex_0.toBakedItem(data, 0); + vertex_1.toBakedItem(data, 7); + vertex_2.toBakedItem(data, 14); + vertex_3.toBakedItem(data, 21); return new BakedQuad(data, tintIndex, face, sprite, shade, DefaultVertexFormats.ITEM); } @@ -117,10 +119,10 @@ public MutableQuad fromBakedBlock(BakedQuad quad) { int[] data = quad.getVertexData(); int stride = data.length / 4; - verticies[0].fromBakedBlock(data, 0); - verticies[1].fromBakedBlock(data, stride); - verticies[2].fromBakedBlock(data, stride * 2); - verticies[3].fromBakedBlock(data, stride * 3); + vertex_0.fromBakedBlock(data, 0); + vertex_1.fromBakedBlock(data, stride); + vertex_2.fromBakedBlock(data, stride * 2); + vertex_3.fromBakedBlock(data, stride * 3); return this; } @@ -134,32 +136,27 @@ public MutableQuad fromBakedItem(BakedQuad quad) { int[] data = quad.getVertexData(); int stride = data.length / 4; - verticies[0].fromBakedItem(data, 0); - verticies[1].fromBakedItem(data, stride); - verticies[2].fromBakedItem(data, stride * 2); - verticies[3].fromBakedItem(data, stride * 3); + vertex_0.fromBakedItem(data, 0); + vertex_1.fromBakedItem(data, stride); + vertex_2.fromBakedItem(data, stride * 2); + vertex_3.fromBakedItem(data, stride * 3); return this; } public void render(VertexBuffer vb) { - for (MutableVertex v : verticies) { - v.render(vb); - } - } - - public MutableVertex getVertex(int v) { - return verticies[v & 0b11]; + vertex_0.render(vb); + vertex_1.render(vb); + vertex_2.render(vb); + vertex_3.render(vb); } public Vector3f getCalculatedNormal() { - Point3f[] positions = { getVertex(0).positionvf(), getVertex(1).positionvf(), getVertex(2).positionvf() }; - - Vector3f a = new Vector3f(positions[1]); - a.sub(positions[0]); + Vector3f a = new Vector3f(vertex_1.positionvf()); + a.sub(vertex_0.positionvf()); - Vector3f b = new Vector3f(positions[2]); - b.sub(positions[0]); + Vector3f b = new Vector3f(vertex_2.positionvf()); + b.sub(vertex_0.positionvf()); Vector3f c = new Vector3f(); c.cross(a, b); @@ -167,7 +164,7 @@ public Vector3f getCalculatedNormal() { } public void setCalculatedNormal() { - normalv(getCalculatedNormal()); + normalvf(getCalculatedNormal()); } public static float diffuseLight(Vector3f normal) { @@ -205,64 +202,340 @@ public void setCalculatedDiffuse() { colourf(diffuse, diffuse, diffuse, 1); } - /** Inverts this quad's normal so that it will render in the opposite direction. You will need to recall diffusion - * calculations if you had previously calculated the diffuse. */ - public MutableQuad invertNormal() { - MutableVertex[] newArray = new MutableVertex[4]; - newArray[0] = verticies[3]; - newArray[1] = verticies[2]; - newArray[2] = verticies[1]; - newArray[3] = verticies[0]; - for (int i = 0; i < 4; i++) - verticies[i] = newArray[i].invertNormal(); - return this; + /** Inverts a copy of this quad's normal so that it will render in the opposite direction. You will need to recall + * diffusion calculations if you had previously calculated the diffuse. */ + public MutableQuad copyAndInvertNormal() { + MutableQuad copy = new MutableQuad(this); + copy.vertex_0.copyFrom(vertex_3).invertNormal(); + copy.vertex_1.copyFrom(vertex_2).invertNormal(); + copy.vertex_2.copyFrom(vertex_1).invertNormal(); + copy.vertex_3.copyFrom(vertex_0).invertNormal(); + return copy; } public MutableQuad rotateTextureUp(int times) { - times = times % 4; - if (times <= 0) { - return this; - } - Point2f[] textures = new Point2f[4]; - for (int i = 0; i < 4; i++) { - textures[i] = verticies[i].tex(); + switch (times & 3) { + case 0: { + return this; + } + case 1: { + Point2f t = vertex_0.tex(); + vertex_0.texv(vertex_1.tex()); + vertex_1.texv(vertex_2.tex()); + vertex_2.texv(vertex_3.tex()); + vertex_3.texv(t); + return this; + } + case 2: { + Point2f t0 = vertex_0.tex(); + Point2f t1 = vertex_1.tex(); + vertex_0.texv(vertex_2.tex()); + vertex_1.texv(vertex_3.tex()); + vertex_2.texv(t0); + vertex_3.texv(t1); + return this; + } + case 3: { + Point2f t = vertex_3.tex(); + vertex_3.texv(vertex_2.tex()); + vertex_2.texv(vertex_1.tex()); + vertex_1.texv(vertex_0.tex()); + vertex_0.texv(t); + return this; + } + default: { + throw new IllegalStateException("'times & 3' was not 0, 1, 2 or 3!"); + } } - for (int i = 0; i < 4; i++) { - verticies[i].texv(textures[(i + times) % 4]); + } + + // ############################ + // + // Delegate vertex functions + // + // Basically a lot of functions that + // change every vertex in the same way + // + // ############################ + + /* Position */ + + // Note that you cannot set all of the position elements at once, so this is left empty + + /* Normal */ + + /** Sets the normal for all vertices to the specified float coordinates. */ + public MutableQuad normalf(float x, float y, float z) { + vertex_0.normalf(x, y, z); + vertex_1.normalf(x, y, z); + vertex_2.normalf(x, y, z); + vertex_3.normalf(x, y, z); + return this; + } + + /** Sets the normal for all vertices to the specified double coordinates. */ + public MutableQuad normald(double x, double y, double z) { + return normalf((float) x, (float) y, (float) z); + } + + /** Sets the normal for all vertices to the specified {@link Vector3f}. */ + public MutableQuad normalvf(Vector3f vec) { + return normalf(vec.x, vec.y, vec.z); + } + + /** Sets the normal for all vertices to the specified {@link Vec3d}. */ + public MutableQuad normalvd(Vec3d vec) { + return normald(vec.xCoord, vec.yCoord, vec.zCoord); + } + + /** Sets the normal for all vertices to the specified {@link VecDouble}, using + * {@link VecDouble#a},{@link VecDouble#b}, and {@link VecDouble#c} */ + public MutableQuad normalvd(VecDouble vec) { + return normald(vec.a, vec.b, vec.c); + } + + /** @return A new {@link Vector3f} with the normal of the first vertex. Only useful if the normal is expected to be + * the same for every vertex. */ + public Vector3f normalvf() { + return new Vector3f(vertex_0.normal_x, vertex_0.normal_y, vertex_0.normal_z); + } + + /** @return A new {@link Vec3d} with the normal of the first vertex. Only useful if the normal is expected to be the + * same for every vertex. */ + public Vec3d normalvd() { + return new Vec3d(vertex_0.normal_x, vertex_0.normal_y, vertex_0.normal_z); + } + + /* Colour */ + + public MutableQuad colouri(int r, int g, int b, int a) { + vertex_0.colouri(r, g, b, a); + vertex_1.colouri(r, g, b, a); + vertex_2.colouri(r, g, b, a); + vertex_3.colouri(r, g, b, a); + return this; + } + + public MutableQuad colouri(int rgba) { + vertex_0.colouri(rgba); + vertex_1.colouri(rgba); + vertex_2.colouri(rgba); + vertex_3.colouri(rgba); + return this; + } + + public MutableQuad colourf(float r, float g, float b, float a) { + vertex_0.colourf(r, g, b, a); + vertex_1.colourf(r, g, b, a); + vertex_2.colourf(r, g, b, a); + vertex_3.colourf(r, g, b, a); + return this; + } + + public MutableQuad colourvl(VecLong vec) { + return colouri((int) vec.a, (int) vec.b, (int) vec.c, (int) vec.d); + } + + public MutableQuad colourvf(Tuple4f vec) { + return colourf(vec.x, vec.y, vec.z, vec.w); + } + + public MutableQuad multColourd(double r, double g, double b, double a) { + vertex_0.multColourd(r, g, b, a); + vertex_1.multColourd(r, g, b, a); + vertex_2.multColourd(r, g, b, a); + vertex_3.multColourd(r, g, b, a); + return this; + } + + public MutableQuad multColourd(double by) { + int m = (int) (by * 255); + return multColouri(m); + } + + public MutableQuad multColouri(int by) { + vertex_0.multColouri(by); + vertex_1.multColouri(by); + vertex_2.multColouri(by); + vertex_3.multColouri(by); + return this; + } + + public MutableQuad multColouri(int r, int g, int b, int a) { + vertex_0.multColouri(r, g, b, a); + vertex_1.multColouri(r, g, b, a); + vertex_2.multColouri(r, g, b, a); + vertex_3.multColouri(r, g, b, a); + return this; + } + + /** Multiplies every vertex by {@link #diffuseLight(float, float, float)} for the normal, if {@link #isShade()} + * returns true. Also sets {@link #isShade()} to false. */ + public MutableQuad multShade() { + if (isShade()) { + setShade(false); + vertex_0.multShade(); + vertex_1.multShade(); + vertex_2.multShade(); + vertex_3.multShade(); } return this; } - /* A lot of delegate functions here. The actual documentation should be per-vertex. */ - // @formatter:off - public MutableQuad normalv(Vector3f vec) {for (MutableVertex v : verticies) v.normalv(vec); return this;} - public MutableQuad normalf(float x, float y, float z) {for (MutableVertex v : verticies) v.normalf(x, y, z); return this;} + /* Texture co-ords */ - public MutableQuad colourv(Tuple4f vec) {for (MutableVertex v : verticies) v.colourv(vec); return this;}; - public MutableQuad colourf(float r, float g, float b, float a) {for (MutableVertex v : verticies) v.colourf(r,g,b,a); return this;} - public MutableQuad colouri(int rgba) {for (MutableVertex v : verticies) v.colouri(rgba); return this;} - public MutableQuad colouri(int r, int g, int b, int a) {for (MutableVertex v : verticies) v.colouri(r, g, b, a); return this;} + public MutableQuad texFromSprite(TextureAtlasSprite sprite) { + vertex_0.texFromSprite(sprite); + vertex_1.texFromSprite(sprite); + vertex_2.texFromSprite(sprite); + vertex_3.texFromSprite(sprite); + return this; + } - public MutableQuad multColourd(double by) {for (MutableVertex v : verticies) v.multColourd(by); return this;} - public MutableQuad multColourd(double r, double g, double b, double a) {for (MutableVertex v : verticies) v.multColourd(r, g, b, a); return this;} - public MutableQuad multColouri(int rgba) {for (MutableVertex v : verticies) v.multColouri(rgba); return this;} - public MutableQuad multColouri(int r, int g, int b, int a) {for (MutableVertex v : verticies) v.multColouri(r, g, b, a); return this;} + /* Lightmap texture co-ords */ - public MutableQuad texFromSprite(TextureAtlasSprite s) {for (MutableVertex v : verticies) v.texFromSprite(s); return this;} + public MutableQuad lighti(int block, int sky) { + vertex_0.lighti(block, sky); + vertex_1.lighti(block, sky); + vertex_2.lighti(block, sky); + vertex_3.lighti(block, sky); + return this; + } - public MutableQuad lightv(Tuple2f vec) {for (MutableVertex v : verticies) v.lightv(vec); return this;} - public MutableQuad lightf(float block, float sky) {for (MutableVertex v : verticies) v.lightf(block, sky); return this;} - public MutableQuad lighti(int combined) {for (MutableVertex v : verticies) v.lighti(combined); return this;} - public MutableQuad lighti(int block, int sky) {for (MutableVertex v : verticies) v.lighti(block, sky); return this;} + public MutableQuad lighti(int combined) { + vertex_0.lighti(combined); + vertex_1.lighti(combined); + vertex_2.lighti(combined); + vertex_3.lighti(combined); + return this; + } - public MutableQuad transform(Matrix4f transformation) {for (MutableVertex v : verticies) v.transform(transformation); return this;} + public MutableQuad lightf(float block, float sky) { + return lighti((int) (block * 15), (int) (sky * 15)); + } - public MutableQuad translatei(int x, int y, int z) {for (MutableVertex v : verticies) v.translatei(x, y, z); return this;} - public MutableQuad translatef(float x, float y, float z) {for (MutableVertex v : verticies) v.translatef(x, y, z); return this;} - public MutableQuad translated(double x, double y, double z) {for (MutableVertex v : verticies) v.translated(x, y, z); return this;} - public MutableQuad translatevi(Vec3i vec) {for (MutableVertex v : verticies) v.translatevi(vec); return this;} - public MutableQuad translatevd(Vec3d vec) {for (MutableVertex v : verticies) v.translatevd(vec); return this;} - // @formatter:on + public MutableQuad lightvf(Tuple2f vec) { + return lightf(vec.x, vec.y); + } + + /** Sets the current light value of every vertex to be the maximum of the given in value, and the current value */ + public MutableQuad maxLighti(int block, int sky) { + vertex_0.maxLighti(block, sky); + vertex_1.maxLighti(block, sky); + vertex_2.maxLighti(block, sky); + vertex_3.maxLighti(block, sky); + return this; + } + + /* Transforms */ + + public MutableQuad transform(Matrix4f transformation) { + vertex_0.transform(transformation); + vertex_1.transform(transformation); + vertex_2.transform(transformation); + vertex_3.transform(transformation); + return this; + } + + public MutableQuad translatei(int x, int y, int z) { + return translatef(x, y, z); + } + + public MutableQuad translatef(float x, float y, float z) { + vertex_0.translatef(x, y, z); + vertex_1.translatef(x, y, z); + vertex_2.translatef(x, y, z); + vertex_3.translatef(x, y, z); + return this; + } + + public MutableQuad translated(double x, double y, double z) { + return translatef((float) x, (float) y, (float) z); + } + + public MutableQuad translatevi(Vec3i vec) { + return translatei(vec.getX(), vec.getY(), vec.getZ()); + } + + public MutableQuad translatevf(Vector3f vec) { + return translatef(vec.x, vec.y, vec.z); + } + + public MutableQuad translatevd(Vec3d vec) { + return translated(vec.xCoord, vec.yCoord, vec.zCoord); + } + + public MutableQuad scalef(float scale) { + vertex_0.scalef(scale); + vertex_1.scalef(scale); + vertex_2.scalef(scale); + vertex_3.scalef(scale); + return this; + } + + public MutableQuad scaled(double scale) { + return scalef((float) scale); + } + + public MutableQuad scalef(float x, float y, float z) { + vertex_0.scalef(x, y, z); + vertex_1.scalef(x, y, z); + vertex_2.scalef(x, y, z); + vertex_3.scalef(x, y, z); + return this; + } + + public MutableQuad scaled(double x, double y, double z) { + return scalef((float) x, (float) y, (float) z); + } + + public MutableQuad rotateX_90(float scale) { + vertex_0.rotateX_90(scale); + vertex_1.rotateX_90(scale); + vertex_2.rotateX_90(scale); + vertex_3.rotateX_90(scale); + return this; + } + + public MutableQuad rotateY_90(float scale) { + vertex_0.rotateY_90(scale); + vertex_1.rotateY_90(scale); + vertex_2.rotateY_90(scale); + vertex_3.rotateY_90(scale); + return this; + } + + public MutableQuad rotateZ_90(float scale) { + vertex_0.rotateZ_90(scale); + vertex_1.rotateZ_90(scale); + vertex_2.rotateZ_90(scale); + vertex_3.rotateZ_90(scale); + return this; + } + + public MutableQuad rotateX_180() { + vertex_0.rotateX_180(); + vertex_1.rotateX_180(); + vertex_2.rotateX_180(); + vertex_3.rotateX_180(); + return this; + } + + public MutableQuad rotateY_180() { + vertex_0.rotateY_180(); + vertex_1.rotateY_180(); + vertex_2.rotateY_180(); + vertex_3.rotateY_180(); + return this; + } + + public MutableQuad rotateZ_180() { + vertex_0.rotateZ_180(); + vertex_1.rotateZ_180(); + vertex_2.rotateZ_180(); + vertex_3.rotateZ_180(); + return this; + } @Override public String toString() { @@ -270,10 +543,6 @@ public String toString() { } private String vToS() { - StringBuilder builder = new StringBuilder(); - for (MutableVertex v : verticies) { - builder.append(v.toString() + "\n"); - } - return builder.toString(); + return "[ " + vertex_0 + ", " + vertex_1 + ", " + vertex_2 + ", " + vertex_3 + " ]"; } } diff --git a/common/buildcraft/lib/client/model/MutableVertex.java b/common/buildcraft/lib/client/model/MutableVertex.java index 5e04b5072a..67619510e7 100644 --- a/common/buildcraft/lib/client/model/MutableVertex.java +++ b/common/buildcraft/lib/client/model/MutableVertex.java @@ -49,7 +49,16 @@ public MutableVertex(MutableVertex from) { copyFrom(from); } - public void copyFrom(MutableVertex from) { + @Override + public String toString() { + return "{ pos = [ " + position_x + ", " + position_y + ", " + position_z // + + " ], norm = [ " + normal_x + ", " + normal_y + ", " + normal_z// + + " ], colour = [ " + colour_r + ", " + colour_g + ", " + colour_b + ", " + colour_a// + + " ], tex = [ " + tex_u + ", " + tex_v // + + " ], light_block = " + light_block + ", light_sky = " + light_sky + " }"; + } + + public MutableVertex copyFrom(MutableVertex from) { position_x = from.position_x; position_y = from.position_y; position_z = from.position_z; @@ -68,6 +77,7 @@ public void copyFrom(MutableVertex from) { light_block = from.light_block; light_sky = from.light_sky; + return this; } public void toBakedBlock(int[] data, int offset) { @@ -255,43 +265,47 @@ public Point4f colourv() { } public int colourRGBA() { - return (colour_r << 0)// - | (colour_g << 8)// - | (colour_b << 16)// - | (colour_a << 24); + int rgba = 0; + rgba |= (colour_r & 0xFF) << 0; + rgba |= (colour_g & 0xFF) << 8; + rgba |= (colour_b & 0xFF) << 16; + rgba |= (colour_a & 0xFF) << 24; + return rgba; } public int colourABGR() { - return (colour_r << 24)// - | (colour_g << 16)// - | (colour_b << 8)// - | (colour_a << 0); + int rgba = 0; + rgba |= (colour_r & 0xFF) << 24; + rgba |= (colour_g & 0xFF) << 16; + rgba |= (colour_b & 0xFF) << 8; + rgba |= (colour_a & 0xFF) << 0; + return rgba; } public MutableVertex multColourd(double d) { - return multColourd(d, d, d, 1); + int m = (int) (d * 255); + return multColouri(m); } public MutableVertex multColourd(double r, double g, double b, double a) { - return colouri(// - (int) (colour_r * r),// - (int) (colour_g * g),// - (int) (colour_b * b),// - (int) (colour_a * a) // - ); + return multColouri((int) (r * 255), (int) (g * 255), (int) (b * 255), (int) (a * 255)); } - public MutableVertex multColouri(int rgba) { - return multColouri(rgba, rgba >> 8, rgba >> 16, rgba >>> 24); + public MutableVertex multColouri(int by) { + return multColouri(by, by, by, 255); } public MutableVertex multColouri(int r, int g, int b, int a) { - return multColourd(// - (r & 255) / 255f,// - (g & 255) / 255f,// - (b & 255) / 255f,// - (a & 255) / 255f // - ); + colour_r = (short) (colour_r * r / 255); + colour_g = (short) (colour_g * g / 255); + colour_b = (short) (colour_b * b / 255); + colour_a = (short) (colour_a * a / 255); + return this; + } + + /** Multiplies the colour by {@link MutableQuad#diffuseLight(float, float, float)} for the normal. */ + public MutableVertex multShade() { + return multColourd(MutableQuad.diffuseLight(normal_x, normal_y, normal_z)); } public MutableVertex texFromSprite(TextureAtlasSprite sprite) { @@ -332,6 +346,10 @@ public MutableVertex lighti(int block, int sky) { return this; } + public MutableVertex maxLighti(int block, int sky) { + return lighti(Math.max(block, light_block), Math.max(sky, light_sky)); + } + public Point2f lightvf() { return new Point2f(light_block * 15f, light_sky * 15f); } @@ -383,4 +401,108 @@ public MutableVertex translatevi(Vec3i vec) { public MutableVertex translatevd(Vec3d vec) { return translated(vec.xCoord, vec.yCoord, vec.zCoord); } + + public MutableVertex scalef(float scale) { + position_x *= scale; + position_y *= scale; + position_z *= scale; + return this; + } + + public MutableVertex scaled(double scale) { + return scalef((float) scale); + } + + public MutableVertex scalef(float x, float y, float z) { + position_x *= x; + position_y *= y; + position_z *= z; + // TODO: scale normals? + return this; + } + + public MutableVertex scaled(double x, double y, double z) { + return scalef((float) x, (float) y, (float) z); + } + + /** Rotates this vertex around the X axis 90 degrees. + * + * @param scale The multiplier for scaling. Positive values will rotate clockwise, negative values rotate + * anti-clockwise. */ + public MutableVertex rotateX_90(float scale) { + float ym = scale; + float zm = -ym; + + float t = position_y * ym; + position_y = position_z * zm; + position_z = t; + + t = normal_y * ym; + normal_y = normal_z * zm; + normal_z = t; + return this; + } + + /** Rotates this vertex around the Y axis 90 degrees. + * + * @param scale The multiplier for scaling. Positive values will rotate clockwise, negative values rotate + * anti-clockwise. */ + public MutableVertex rotateY_90(float scale) { + float xm = scale; + float zm = -xm; + + float t = position_x * xm; + position_x = position_z * zm; + position_z = t; + + t = normal_x * xm; + normal_x = normal_z * zm; + normal_z = t; + return this; + } + + /** Rotates this vertex around the Z axis 90 degrees. + * + * @param scale The multiplier for scaling. Positive values will rotate clockwise, negative values rotate + * anti-clockwise. */ + public MutableVertex rotateZ_90(float scale) { + float ym = scale; + float xm = -ym; + + float t = position_x * xm; + position_x = position_y * ym; + position_y = t; + + t = normal_x * xm; + normal_x = normal_y * ym; + normal_y = t; + return this; + } + + /** Rotates this vertex around the X axis by 180 degrees. */ + public MutableVertex rotateX_180() { + position_y = -position_y; + position_z = -position_z; + normal_y = -normal_y; + normal_z = -normal_z; + return this; + } + + /** Rotates this vertex around the Y axis by 180 degrees. */ + public MutableVertex rotateY_180() { + position_x = -position_x; + position_z = -position_z; + normal_x = -normal_x; + normal_z = -normal_z; + return this; + } + + /** Rotates this vertex around the Z axis by 180 degrees. */ + public MutableVertex rotateZ_180() { + position_x = -position_x; + position_y = -position_y; + normal_x = -normal_x; + normal_y = -normal_y; + return this; + } } diff --git a/common/buildcraft/lib/client/model/json/JsonModelPart.java b/common/buildcraft/lib/client/model/json/JsonModelPart.java index 8a5894caff..b5d4bc66ca 100644 --- a/common/buildcraft/lib/client/model/json/JsonModelPart.java +++ b/common/buildcraft/lib/client/model/json/JsonModelPart.java @@ -4,10 +4,12 @@ import java.util.Arrays; import java.util.List; -import com.google.gson.*; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSyntaxException; import net.minecraft.client.renderer.block.model.BlockPart; -import net.minecraft.client.renderer.block.model.ModelRotation; import net.minecraft.util.EnumFacing; import net.minecraft.util.JsonUtils; @@ -39,18 +41,10 @@ public JsonModelPart(JsonElement json, ResourceLoaderContext ctx) { quads = readCuboid(obj); } } - + private JsonModelPart(JsonQuad[] quads) { this.quads = quads; } - - public JsonModelPart rotate(ModelRotation rot) { - JsonQuad[] nq = new JsonQuad[quads.length]; - for (int i = 0; i < nq.length; i++) { - nq[i] = quads[i].rotate(rot); - } - return new JsonModelPart(nq); - } private static JsonQuad[] readFace(JsonObject obj) { throw new AbstractMethodError("Implement this!"); diff --git a/common/buildcraft/lib/client/model/json/JsonModelRule.java b/common/buildcraft/lib/client/model/json/JsonModelRule.java index 6144d20f34..4efcbafe4c 100644 --- a/common/buildcraft/lib/client/model/json/JsonModelRule.java +++ b/common/buildcraft/lib/client/model/json/JsonModelRule.java @@ -9,13 +9,11 @@ import com.google.gson.JsonSyntaxException; import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumFacing.Axis; import net.minecraft.util.JsonUtils; import buildcraft.api.core.BCLog; import buildcraft.lib.client.model.MutableQuad; -import buildcraft.lib.client.model.MutableVertex; import buildcraft.lib.client.model.ResourceLoaderContext; import buildcraft.lib.expression.FunctionContext; import buildcraft.lib.expression.api.IExpressionNode.INodeBoolean; @@ -95,7 +93,6 @@ public void apply(List quads) { } // always rotate from "UP" - it simplifies the math a bit switch (faceFrom) { - default: case UP: break; case DOWN: @@ -105,7 +102,9 @@ public void apply(List quads) { case EAST: case NORTH: case SOUTH: - + throw new IllegalArgumentException("Not yet implemented - rotate from " + faceFrom); + default: + throw new IllegalArgumentException("Unknown EnumFacing " + faceFrom); } faceFrom = EnumFacing.UP; if (faceTo == EnumFacing.UP) return; @@ -113,50 +112,33 @@ public void apply(List quads) { float oy = (float) origin[1].evaluate(); float oz = (float) origin[2].evaluate(); - for (MutableQuad q : quads) { - for (int i = 0; i < 4; i++) { - MutableVertex v = q.getVertex(i); - v.position_x -= ox; - v.position_y -= oy; - v.position_z -= oz; - Axis axis = faceTo.getAxis(); - if (axis == Axis.X) { - float xm = faceTo.getFrontOffsetX(); - float ym = -xm; - - // rotate around the Z-axis - float t = v.position_y * xm; - v.position_y = v.position_x * ym; - v.position_x = t; - - t = v.normal_y * xm; - v.normal_y = v.normal_x * ym; - v.normal_x = t; - } else if (axis == Axis.Z) { - float zm = faceTo.getFrontOffsetZ(); - float ym = -zm; - - // rotate around the X-axis - float t = v.position_y * zm; - v.position_y = v.position_z * ym; - v.position_z = t; - - t = v.normal_y * zm; - v.normal_y = v.normal_z * ym; - v.normal_z = t; - } else {// axis == Axis.Y && faceTo == DOWN - // Invert the entire model - v.position_x = -v.position_x; - v.position_y = -v.position_y; - v.position_z = -v.position_z; - - v.normal_x = -v.normal_x; - v.normal_y = -v.normal_y; - v.normal_z = -v.normal_z; + switch (faceTo.getAxis()) { + case X: { + for (MutableQuad q : quads) { + q.translatef(-ox, -oy, -oz); + q.rotateZ_90(faceTo.getFrontOffsetX()); + q.translatef(ox, oy, oz); + } + break; + } + case Z: { + for (MutableQuad q : quads) { + q.translatef(-ox, -oy, -oz); + q.rotateX_90(faceTo.getFrontOffsetZ()); + q.translatef(ox, oy, oz); } - v.position_x += ox; - v.position_y += oy; - v.position_z += oz; + break; + } + case Y: { + for (MutableQuad q : quads) { + q.translatef(-ox, -oy, -oz); + q.rotateX_180(); + q.translatef(ox, oy, oz); + } + break; + } + default: { + throw new IllegalStateException("Unknown axis " + faceTo.getAxis()); } } } diff --git a/common/buildcraft/lib/client/model/json/JsonQuad.java b/common/buildcraft/lib/client/model/json/JsonQuad.java index a702a25e03..9a5bac017a 100644 --- a/common/buildcraft/lib/client/model/json/JsonQuad.java +++ b/common/buildcraft/lib/client/model/json/JsonQuad.java @@ -7,7 +7,6 @@ import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; -import net.minecraft.client.renderer.block.model.ModelRotation; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.util.EnumFacing; import net.minecraft.util.JsonUtils; @@ -44,38 +43,18 @@ public JsonQuad(JsonObject obj, float[] from, float[] to, EnumFacing face) { center.add(radius); MutableQuad quad = ModelUtil.createFace(face, center, radius, uvs); quad.rotateTextureUp(rotation); - vertices[0] = new JsonVertex(quad.getVertex(0)); - vertices[1] = new JsonVertex(quad.getVertex(1)); - vertices[2] = new JsonVertex(quad.getVertex(2)); - vertices[3] = new JsonVertex(quad.getVertex(3)); - } - - private JsonQuad(JsonQuad from, JsonVertex[] vs, EnumFacing face) { - this.shade = from.shade; - this.tint = from.tint; - this.texture = from.texture; - vertices[0] = vs[0]; - vertices[1] = vs[1]; - vertices[2] = vs[2]; - vertices[3] = vs[3]; - this.face = face; - } - - public JsonQuad rotate(ModelRotation rot) { - JsonVertex[] vs = new JsonVertex[4]; - for (int i = 0; i < 4; i++) { - vs[i] = vertices[i].rotate(rot); - } - EnumFacing f = rot.rotate(face); - return new JsonQuad(this, vs, f); + vertices[0] = new JsonVertex(quad.vertex_0); + vertices[1] = new JsonVertex(quad.vertex_1); + vertices[2] = new JsonVertex(quad.vertex_2); + vertices[3] = new JsonVertex(quad.vertex_3); } public MutableQuad toQuad(TextureAtlasSprite sprite) { MutableQuad quad = new MutableQuad(tint, face, shade); - vertices[0].loadInto(quad.getVertex(0)); - vertices[1].loadInto(quad.getVertex(1)); - vertices[2].loadInto(quad.getVertex(2)); - vertices[3].loadInto(quad.getVertex(3)); + vertices[0].loadInto(quad.vertex_0); + vertices[1].loadInto(quad.vertex_1); + vertices[2].loadInto(quad.vertex_2); + vertices[3].loadInto(quad.vertex_3); if (sprite != null) { quad.texFromSprite(sprite); quad.setSprite(sprite); diff --git a/common/buildcraft/lib/client/model/json/JsonVertex.java b/common/buildcraft/lib/client/model/json/JsonVertex.java index f13c76088d..1ef8b5d008 100644 --- a/common/buildcraft/lib/client/model/json/JsonVertex.java +++ b/common/buildcraft/lib/client/model/json/JsonVertex.java @@ -19,21 +19,9 @@ public JsonVertex(MutableVertex vertex) { uv = vertex.tex(); } - private JsonVertex(JsonVertex from, ModelRotation rot) { - pos = new Point3f(from.pos); - normal = new Vector3f(from.normal); - // TODO! -// rot.getMatrix4d() - uv = new Point2f(from.uv); - } - public void loadInto(MutableVertex vertex) { vertex.positionv(pos); vertex.normalv(normal); vertex.texv(uv); } - - public JsonVertex rotate(ModelRotation rot) { - return new JsonVertex(this, rot); - } } diff --git a/common/buildcraft/lib/client/render/ItemRenderUtil.java b/common/buildcraft/lib/client/render/ItemRenderUtil.java index 9531856a67..67f451c387 100644 --- a/common/buildcraft/lib/client/render/ItemRenderUtil.java +++ b/common/buildcraft/lib/client/render/ItemRenderUtil.java @@ -2,7 +2,6 @@ import java.util.concurrent.TimeUnit; -import javax.vecmath.Point3f; import javax.vecmath.Vector3f; import com.google.common.cache.CacheBuilder; @@ -30,7 +29,6 @@ import buildcraft.lib.BCLibConfig; import buildcraft.lib.client.model.MutableQuad; -import buildcraft.lib.client.model.MutableVertex; import buildcraft.lib.misc.ItemStackKey; public class ItemRenderUtil { @@ -51,9 +49,9 @@ public boolean shouldBob() { }; static { glListCache = CacheBuilder.newBuilder()// - .expireAfterAccess(40, TimeUnit.SECONDS)// - .removalListener(ItemRenderUtil::onStackRemove)// - .build(CacheLoader.from(ItemRenderUtil::makeItemGlList)); + .expireAfterAccess(40, TimeUnit.SECONDS)// + .removalListener(ItemRenderUtil::onStackRemove)// + .build(CacheLoader.from(ItemRenderUtil::makeItemGlList)); } private static Integer makeItemGlList(ItemStackKey item) { @@ -121,45 +119,36 @@ public static void renderItemStack(double x, double y, double z, ItemStack stack for (EnumPipePart part : EnumPipePart.VALUES) { for (BakedQuad quad : model.getQuads(null, part.face, 0)) { q.fromBakedItem(quad); + q.translated(-0.5, -0.5, -0.5); + q.scaled(scale); - for (int i = 0; i < 4; i++) { - MutableVertex v = q.getVertex(i); - Point3f pos = v.positionvf(); - Point3f nPos = new Point3f(pos); - switch (dir) { - case EAST: - nPos.x = (pos.z - 0.5f) * scale; - nPos.y = (pos.y - 0.5f) * scale; - nPos.z = (1 - pos.x - 0.5f) * scale; - break; - case WEST: - nPos.x = (1 - pos.z - 0.5f) * scale; - nPos.y = (pos.y - 0.5f) * scale; - nPos.z = (pos.x - 0.5f) * scale; - break; - case DOWN: - nPos.x = (pos.z - 0.5f) * scale; - nPos.y = (pos.x - 0.5f) * scale; - nPos.z = (pos.y - 0.5f) * scale; - break; - case UP: - nPos.x = (pos.x - 0.5f) * scale; - nPos.y = (pos.z - 0.5f) * scale; - nPos.z = (1 - pos.y - 0.5f) * scale; - break; - case NORTH: - nPos.x = (1 - pos.x - 0.5f) * scale; - nPos.y = (pos.y - 0.5f) * scale; - nPos.z = (1 - pos.z - 0.5f) * scale; - break; - default: - case SOUTH: - nPos.x = (pos.x - 0.5f) * scale; - nPos.y = (pos.y - 0.5f) * scale; - nPos.z = (pos.z - 0.5f) * scale; - break; + switch (dir) { + case EAST: { + q.rotateY_90(1); + break; + } + case WEST: { + q.rotateY_90(-1); + break; + } + case DOWN: { + q.rotateX_90(1); + break; + } + case UP: { + q.rotateX_90(-1); + break; + } + case NORTH: { + q.rotateY_180(); + break; + } + case SOUTH: { + break; + } + default: { + throw new IllegalStateException("Unknown EnumFacing" + dir); } - v.positionv(nPos); } if (quad.hasTintIndex()) { int colour = Minecraft.getMinecraft().getItemColors().getColorFromItemstack(stack, quad.getTintIndex()); @@ -170,10 +159,8 @@ public static void renderItemStack(double x, double y, double z, ItemStack stack } q.lighti(15, 15); Vector3f normal = q.getCalculatedNormal(); - q.normalv(normal); - if (quad.shouldApplyDiffuseLighting()) { - q.setDiffuse(normal); - } + q.normalvf(normal); + q.multShade(); q.render(vb); } } diff --git a/common/buildcraft/lib/client/render/laser/LaserContext.java b/common/buildcraft/lib/client/render/laser/LaserContext.java index 16cd86c84d..84a95b600e 100644 --- a/common/buildcraft/lib/client/render/laser/LaserContext.java +++ b/common/buildcraft/lib/client/render/laser/LaserContext.java @@ -16,11 +16,13 @@ public class LaserContext { private final ILaserRenderer renderer; public final double length; private final boolean useNormalColour, drawBothSides; + private final int minBlockLight; public LaserContext(ILaserRenderer renderer, LaserData_BC8 data, boolean useNormalColour, boolean isCullEnabled) { this.renderer = renderer; this.useNormalColour = useNormalColour; this.drawBothSides = isCullEnabled; + this.minBlockLight = data.minBlockLight; Vec3d delta = data.start.subtract(data.end); double dx = delta.xCoord; double dy = delta.yCoord; @@ -111,7 +113,7 @@ public void addPoint(double xIn, double yIn, double zIn, double uIn, double vIn) point.y = (float) yIn; point.z = (float) zIn; matrix.transform(point); - int lmap = LaserRenderer_BC8.computeLightmap(point.x, point.y, point.z); + int lmap = LaserRenderer_BC8.computeLightmap(point.x, point.y, point.z, minBlockLight); x[index] = point.x; y[index] = point.y; z[index] = point.z; diff --git a/common/buildcraft/lib/client/render/laser/LaserRenderer_BC8.java b/common/buildcraft/lib/client/render/laser/LaserRenderer_BC8.java index b64ca1d819..cecce77b26 100644 --- a/common/buildcraft/lib/client/render/laser/LaserRenderer_BC8.java +++ b/common/buildcraft/lib/client/render/laser/LaserRenderer_BC8.java @@ -88,10 +88,10 @@ private static void removeCompiledLaser(RemovalNotification= 15 ? 15 : Math.max(minBlockLight, getLightFor(world, EnumSkyBlock.BLOCK, x, y, z)); int skyLight = getLightFor(world, EnumSkyBlock.SKY, x, y, z); return skyLight << 20 | blockLight << 4; } diff --git a/common/buildcraft/lib/client/render/tile/RenderEngine_BC8.java b/common/buildcraft/lib/client/render/tile/RenderEngine_BC8.java index ed84e19a27..080654b43e 100644 --- a/common/buildcraft/lib/client/render/tile/RenderEngine_BC8.java +++ b/common/buildcraft/lib/client/render/tile/RenderEngine_BC8.java @@ -7,7 +7,6 @@ import net.minecraftforge.client.model.animation.FastTESR; import buildcraft.lib.client.model.MutableQuad; -import buildcraft.lib.client.model.MutableVertex; import buildcraft.lib.engine.TileEngineBase_BC8; public abstract class RenderEngine_BC8 extends FastTESR { @@ -29,18 +28,8 @@ public void renderTileEntityFast(T engine, double x, double y, double z, float p int light_sky = (lightc >> 20) & 15; for (MutableQuad q : quads) { copy.copyFrom(q); - for (int i = 0; i < 4; i++) { - MutableVertex v = copy.getVertex(i); - if (v.light_block < light_block) v.light_block = (byte) light_block; - v.light_sky = (byte) light_sky; - } - if (copy.isShade()) { - copy.setShade(false); - for (int i = 0; i < 4; i++) { - MutableVertex v = copy.getVertex(i); - v.multColourd(MutableQuad.diffuseLight(v.normal_x, v.normal_y, v.normal_z)); - } - } + copy.maxLighti(light_block, light_sky); + copy.multShade(); copy.render(vb); } vb.setTranslation(0, 0, 0); diff --git a/common/buildcraft/lib/expression/VecDouble.java b/common/buildcraft/lib/expression/VecDouble.java index d0a11b6a6a..f1c26b69c9 100644 --- a/common/buildcraft/lib/expression/VecDouble.java +++ b/common/buildcraft/lib/expression/VecDouble.java @@ -1,7 +1,11 @@ package buildcraft.lib.expression; -/** An immutable class the represents a 4 part vector of doubles. It is *highly* recommended that you have a way to - * convert this to a more specific implementation (for example another library provided Vector3d class) */ +import javax.vecmath.Vector3f; +import javax.vecmath.Vector4f; + +import net.minecraft.util.math.Vec3d; + +/** An immutable class the represents a 4 part vector of doubles. */ public class VecDouble { public static final VecDouble ZERO = new VecDouble(0, 0, 0, 0); @@ -93,4 +97,16 @@ public VecLong floorToLong() { public VecLong ceilToLong() { return new VecLong((long) Math.ceil(a), (long) Math.ceil(b), (long) Math.ceil(c), (long) Math.ceil(d)); } + + public Vec3d toVec3d() { + return new Vec3d(a, b, c); + } + + public Vector3f toVec3f() { + return new Vector3f((float) a, (float) b, (float) c); + } + + public Vector4f toVec4f() { + return new Vector4f((float) a, (float) b, (float) c, (float) d); + } } diff --git a/common/buildcraft/lib/gui/help/ElementHelpInfo.java b/common/buildcraft/lib/gui/help/ElementHelpInfo.java index 6771c1d70b..bf4281df7a 100644 --- a/common/buildcraft/lib/gui/help/ElementHelpInfo.java +++ b/common/buildcraft/lib/gui/help/ElementHelpInfo.java @@ -2,6 +2,9 @@ import java.util.List; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + import buildcraft.lib.gui.GuiBC8; import buildcraft.lib.gui.IGuiElement; import buildcraft.lib.gui.elem.GuiElementContainer; @@ -24,10 +27,12 @@ public ElementHelpInfo(String title, int colour, String... localeKeys) { this.localeKeys = localeKeys; } + @SideOnly(Side.CLIENT) public final HelpPosition target(IGuiArea target) { return new HelpPosition(this, target); } + @SideOnly(Side.CLIENT) public void addGuiElements(GuiElementContainer container) { GuiBC8 gui = container.gui; int y = 20; @@ -48,6 +53,7 @@ public void addGuiElements(GuiElementContainer container) { } /** Stores an {@link ElementHelpInfo} information, as well as the target area which the help element relates to. */ + @SideOnly(Side.CLIENT) public static final class HelpPosition { public final ElementHelpInfo info; public final IGuiArea target; diff --git a/common/buildcraft/lib/misc/MathUtil.java b/common/buildcraft/lib/misc/MathUtil.java index f61c3074ef..6b456882df 100644 --- a/common/buildcraft/lib/misc/MathUtil.java +++ b/common/buildcraft/lib/misc/MathUtil.java @@ -12,4 +12,8 @@ public static int clamp(int toClamp, int min, int max) { public static int clamp(double toClamp, int min, int max) { return clamp((int) toClamp, min, max); } + + public static long clamp(long toClamp, long min, long max) { + return Math.max(Math.min(toClamp, max), min); + } } diff --git a/common/buildcraft/lib/misc/data/CompactingBitSet.java b/common/buildcraft/lib/misc/data/CompactingBitSet.java index 7bbed3563c..27eabab401 100644 --- a/common/buildcraft/lib/misc/data/CompactingBitSet.java +++ b/common/buildcraft/lib/misc/data/CompactingBitSet.java @@ -11,6 +11,14 @@ public CompactingBitSet(int bits) { this.bits = bits; } + public void ensureCapacityValues(int values) { + ensureCapacityBits(values * bits); + } + + public void ensureCapacityBits(int totalBits) { + bytes.ensureCapacity(totalBits / 8 + 1); + } + private void appendBit(int bit) { if (bitIndex == 0) { bytes.add((byte) 0); diff --git a/common/buildcraft/lib/nbt/NBTSquishDebugging.java b/common/buildcraft/lib/nbt/NBTSquishDebugging.java deleted file mode 100644 index 47c67f6242..0000000000 --- a/common/buildcraft/lib/nbt/NBTSquishDebugging.java +++ /dev/null @@ -1,20 +0,0 @@ -package buildcraft.lib.nbt; - -import java.util.function.Supplier; - -public class NBTSquishDebugging { - public static boolean debug = false; - - @Deprecated - public static void log(Supplier supplier) { - if (debug) { - System.out.print(supplier.get() + "\n"); - } - } - - public static void log(String string) { - if (debug) { - System.out.print(string + "\n"); - } - } -} diff --git a/common/buildcraft/lib/nbt/NBTSquishMap.java b/common/buildcraft/lib/nbt/NBTSquishMap.java index cdef889843..eca40de785 100644 --- a/common/buildcraft/lib/nbt/NBTSquishMap.java +++ b/common/buildcraft/lib/nbt/NBTSquishMap.java @@ -11,8 +11,28 @@ import gnu.trove.list.array.*; /** Defines a map of commonly used tags. */ -@Deprecated public class NBTSquishMap { + // TODO: Try adding "ImmutableTagCompound" and "ImmutableTagList" to see if the equals() and hashCode() of compounds + // is a problem atm + // perhaps use "TCustomHashSet" with a simalir deduplicating functionality of FoamFix? + + + + + + + + + + + + + + + + + + // I'm not completely convinced that this one is necessary. // However it completes the set so, meh final TByteArrayList bytes = new TByteArrayList(); @@ -235,6 +255,22 @@ public NBTBase getTagForReading(int index) throws IOException { return value; } + public NBTTagCompound getFullyReadComp(int index) throws IOException { + NBTBase tag = getTagForReading(index); + if (tag instanceof NBTTagCompound) { + return (NBTTagCompound) tag; + } else { + throw new IOException("The tag at " + index + " was not a compound tag! (was " + tag + ")"); + } + } + + public String getStringForReading(int index) throws IOException { + if (index < 0 || index >= strings.size()) { + throw new IOException("Cannot handle index " + index); + } + return strings.get(index); + } + public int sizeOf(int tagType) { return size(1 << (tagType - 1)); } diff --git a/common/buildcraft/lib/nbt/NBTSquishMapReader.java b/common/buildcraft/lib/nbt/NBTSquishMapReader.java index 0d8adfd48e..41d134f3f9 100644 --- a/common/buildcraft/lib/nbt/NBTSquishMapReader.java +++ b/common/buildcraft/lib/nbt/NBTSquishMapReader.java @@ -10,68 +10,68 @@ import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; +import net.minecraft.network.PacketBuffer; import buildcraft.lib.misc.data.DecompactingBitSet; import gnu.trove.list.array.TByteArrayList; import gnu.trove.list.array.TIntArrayList; -import io.netty.buffer.ByteBuf; class NBTSquishMapReader { private final NBTSquishMap map = new NBTSquishMap(); - public static NBTSquishMap read(ByteBuf buf) throws IOException { + public static NBTSquishMap read(PacketBuffer buf) throws IOException { return new NBTSquishMapReader().readInternal(buf); } - private NBTSquishMap readInternal(ByteBuf buf) throws IOException { + private NBTSquishMap readInternal(PacketBuffer buf) throws IOException { WrittenType type = WrittenType.readType(buf); int flags = buf.readInt(); if (isFlag(flags, FLAG_HAS_BYTES)) { - int count = buf.readUnsignedShort(); + int count = buf.readVarInt(); for (int i = 0; i < count; i++) { map.bytes.add(buf.readByte()); } } if (isFlag(flags, FLAG_HAS_SHORTS)) { - int count = buf.readUnsignedShort(); + int count = buf.readVarInt(); for (int i = 0; i < count; i++) { map.shorts.add(buf.readShort()); } } if (isFlag(flags, FLAG_HAS_INTS)) { - int count = buf.readUnsignedShort(); + int count = buf.readVarInt(); for (int i = 0; i < count; i++) { map.ints.add(buf.readInt()); } } if (isFlag(flags, FLAG_HAS_LONGS)) { - int count = buf.readUnsignedShort(); + int count = buf.readVarInt(); for (int i = 0; i < count; i++) { map.longs.add(buf.readLong()); } } if (isFlag(flags, FLAG_HAS_FLOATS)) { - int count = buf.readUnsignedShort(); + int count = buf.readVarInt(); for (int i = 0; i < count; i++) { map.floats.add(buf.readFloat()); } } if (isFlag(flags, FLAG_HAS_DOUBLES)) { - int count = buf.readUnsignedShort(); + int count = buf.readVarInt(); for (int i = 0; i < count; i++) { map.doubles.add(buf.readDouble()); } } if (isFlag(flags, FLAG_HAS_BYTE_ARRAYS)) { - int count = buf.readUnsignedShort(); + int count = buf.readVarInt(); for (int i = 0; i < count; i++) { int arraySize = buf.readUnsignedShort(); TByteArrayList list = new TByteArrayList(); @@ -83,7 +83,7 @@ private NBTSquishMap readInternal(ByteBuf buf) throws IOException { } if (isFlag(flags, FLAG_HAS_INT_ARRAYS)) { - int count = buf.readUnsignedShort(); + int count = buf.readVarInt(); for (int i = 0; i < count; i++) { int arraySize = buf.readUnsignedShort(); TIntArrayList list = new TIntArrayList(); @@ -95,7 +95,7 @@ private NBTSquishMap readInternal(ByteBuf buf) throws IOException { } if (isFlag(flags, FLAG_HAS_STRINGS)) { - int count = buf.readUnsignedShort(); + int count = buf.readVarInt(); for (int i = 0; i < count; i++) { int length = buf.readUnsignedShort(); byte[] bytes = new byte[length]; @@ -105,7 +105,7 @@ private NBTSquishMap readInternal(ByteBuf buf) throws IOException { } if (isFlag(flags, FLAG_HAS_COMPLEX)) { - int count = buf.readUnsignedShort(); + int count = buf.readVarInt(); for (int i = 0; i < count; i++) { int complexType = buf.readUnsignedByte(); if (complexType == COMPLEX_COMPOUND) { @@ -127,20 +127,20 @@ private static boolean isFlag(int flags, int flag) { return (flags & flag) == flag; } - private NBTTagCompound readCompound(WrittenType type, ByteBuf buf) throws IOException { + private NBTTagCompound readCompound(WrittenType type, PacketBuffer buf) throws IOException { WrittenType stringType = WrittenType.getForSize(map.stringSize()); - int count = buf.readUnsignedShort(); + int count = buf.readVarInt(); NBTTagCompound nbt = new NBTTagCompound(); for (int i = 0; i < count; i++) { - String key = map.strings.get(stringType.readIndex(buf)); + String key = map.getStringForReading(stringType.readIndex(buf)); NBTBase value = map.getTagForReading(type.readIndex(buf)); nbt.setTag(key, value); } return nbt; } - private NBTTagList readNormalList(WrittenType type, ByteBuf buf) throws IOException { - int count = buf.readUnsignedShort(); + private NBTTagList readNormalList(WrittenType type, PacketBuffer buf) throws IOException { + int count = buf.readVarInt(); NBTTagList list = new NBTTagList(); for (int i = 0; i < count; i++) { @@ -151,9 +151,9 @@ private NBTTagList readNormalList(WrittenType type, ByteBuf buf) throws IOExcept return list; } - private NBTTagList readPackedList(WrittenType type, ByteBuf buf) throws IOException { + private NBTTagList readPackedList(WrittenType type, PacketBuffer buf) throws IOException { // First make the dictionary - int count = buf.readUnsignedShort(); + int count = buf.readVarInt(); List dictionary = new ArrayList<>(); for (int i = 0; i < count; i++) { int index = type.readIndex(buf); @@ -163,7 +163,7 @@ private NBTTagList readPackedList(WrittenType type, ByteBuf buf) throws IOExcept List list = new ArrayList<>(); TIntArrayList left = new TIntArrayList(); int bits = 1; - int entries = buf.readUnsignedMedium(); + int entries = buf.readVarInt(); for (int i = 0; i < entries; i++) { list.add(null); @@ -171,7 +171,7 @@ private NBTTagList readPackedList(WrittenType type, ByteBuf buf) throws IOExcept } while (!dictionary.isEmpty()) { - int bitsetSize = buf.readUnsignedShort(); + int bitsetSize = buf.readVarInt(); byte[] bitsetData = new byte[bitsetSize]; buf.readBytes(bitsetData); DecompactingBitSet decompactor = new DecompactingBitSet(bits, bitsetData); diff --git a/common/buildcraft/lib/nbt/NBTSquishMapWriter.java b/common/buildcraft/lib/nbt/NBTSquishMapWriter.java index 1fd258c2a7..9dd0884a2a 100644 --- a/common/buildcraft/lib/nbt/NBTSquishMapWriter.java +++ b/common/buildcraft/lib/nbt/NBTSquishMapWriter.java @@ -11,26 +11,41 @@ import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; +import net.minecraft.network.PacketBuffer; +import net.minecraft.profiler.Profiler; import buildcraft.lib.misc.data.CompactingBitSet; import gnu.trove.list.array.*; import gnu.trove.map.hash.TIntIntHashMap; import gnu.trove.set.hash.TIntHashSet; -import io.netty.buffer.ByteBuf; class NBTSquishMapWriter { + static boolean debug; + static final boolean sort = true; + static final Boolean packList = null; + static final Profiler profiler = NbtSquisher.profiler; private final NBTSquishMap map; + private static void log(String string) { + if (debug) { + System.out.println(string); + } else { + throw new IllegalArgumentException("Don't allocate a string if we aren't debugging!"); + } + } + public NBTSquishMapWriter(NBTSquishMap map) { this.map = map; } - public static void write(NBTSquishMap map, ByteBuf buf) { + public static void write(NBTSquishMap map, PacketBuffer buf) { new NBTSquishMapWriter(map).write(buf); } - private void write(ByteBuf buf) { + private void write(PacketBuffer buf) { + profiler.startSection("write"); + profiler.startSection("flags"); WrittenType type = map.getWrittenType(); type.writeType(buf); @@ -58,66 +73,67 @@ private void write(ByteBuf buf) { if (!strings.isEmpty()) flags |= FLAG_HAS_STRINGS; if (!complex.isEmpty()) flags |= FLAG_HAS_COMPLEX; - final int flags2 = flags; - NBTSquishDebugging.log("\nUsed flags = " + Integer.toBinaryString(flags2)); + if (debug) log("\nUsed flags = " + Integer.toBinaryString(flags)); buf.writeInt(flags); + profiler.endStartSection("bytes"); if (!bytes.isEmpty()) { - bytes.sort(); - NBTSquishDebugging.log("\nByte dictionary size = " + bytes.size()); - buf.writeShort(bytes.size()); + if (debug) log("\nByte dictionary size = " + bytes.size()); + if (sort) bytes.sort(); + buf.writeVarInt(bytes.size()); for (byte b : bytes.toArray()) { buf.writeByte(b); } } - + profiler.endStartSection("shorts"); if (!shorts.isEmpty()) { - shorts.sort(); - NBTSquishDebugging.log("\nShort dictionary size = " + shorts.size()); - buf.writeShort(shorts.size()); + if (debug) log("\nShort dictionary size = " + shorts.size()); + if (sort) shorts.sort(); + buf.writeVarInt(shorts.size()); for (short s : shorts.toArray()) { buf.writeShort(s); } } + profiler.endStartSection("integers"); if (!ints.isEmpty()) { - ints.sort(); - NBTSquishDebugging.log("\nInt dictionary size = " + ints.size()); - buf.writeShort(ints.size()); + if (debug) log("\nInt dictionary size = " + ints.size()); + if (sort) ints.sort(); + buf.writeVarInt(ints.size()); for (int i : ints.toArray()) { buf.writeInt(i); } } - + profiler.endStartSection("longs"); if (!longs.isEmpty()) { - longs.sort(); - NBTSquishDebugging.log("\nLong dictionary size = " + longs.size()); - buf.writeShort(longs.size()); + if (debug) log("\nLong dictionary size = " + longs.size()); + if (sort) longs.sort(); + buf.writeVarInt(longs.size()); for (long l : longs.toArray()) { buf.writeLong(l); } } - + profiler.endStartSection("floats"); if (!floats.isEmpty()) { - floats.sort(); - NBTSquishDebugging.log("\nFloat dictionary size = " + floats.size()); - buf.writeShort(floats.size()); + if (debug) log("\nFloat dictionary size = " + floats.size()); + if (sort) floats.sort(); + buf.writeVarInt(floats.size()); for (float f : floats.toArray()) { buf.writeFloat(f); } } + profiler.endStartSection("doubles"); if (!doubles.isEmpty()) { - doubles.sort(); - NBTSquishDebugging.log("\nDouble dictionary size = " + doubles.size()); - buf.writeShort(doubles.size()); + if (debug) log("\nDouble dictionary size = " + doubles.size()); + if (sort) doubles.sort(); + buf.writeVarInt(doubles.size()); for (double d : doubles.toArray()) { buf.writeDouble(d); } } - + profiler.endStartSection("byte_arrays"); if (!byteArrays.isEmpty()) { - // We don't sort arrays because they are more expensive. (and its not a one liner :P) - NBTSquishDebugging.log("\nByte Array dictionary size = " + byteArrays.size()); - buf.writeShort(byteArrays.size()); + if (debug) log("\nByte Array dictionary size = " + byteArrays.size()); + buf.writeVarInt(byteArrays.size()); for (TByteArrayList ba : byteArrays) { buf.writeShort(ba.size()); for (byte b : ba.toArray()) { @@ -125,10 +141,10 @@ private void write(ByteBuf buf) { } } } - + profiler.endStartSection("int_arrays"); if (!intArrays.isEmpty()) { - NBTSquishDebugging.log("\nInt Array dictionary size = " + intArrays.size()); - buf.writeShort(intArrays.size()); + if (debug) log("\nInt Array dictionary size = " + intArrays.size()); + buf.writeVarInt(intArrays.size()); for (TIntArrayList ia : intArrays) { buf.writeShort(ia.size()); for (int i : ia.toArray()) { @@ -136,24 +152,23 @@ private void write(ByteBuf buf) { } } } - + profiler.endStartSection("strings"); if (!strings.isEmpty()) { - // Sort strings beforehand. I don't know if this makes a difference or not, but it might help gzip to - // compress similar strings more (as they are closer). - Collections.sort(strings); - NBTSquishDebugging.log("\nString dictionary size = " + strings.size()); - buf.writeShort(strings.size()); - for (String s : strings) { + if (debug) log("\nString dictionary size = " + strings.size()); + if (sort) Collections.sort(strings); + buf.writeVarInt(strings.size()); + for (int i = 0; i < strings.size(); i++) { + String s = strings.get(i); + if (debug) log("\n String " + i + " = " + s); byte[] stringBytes = s.getBytes(StandardCharsets.UTF_8); - NBTSquishDebugging.log("\n " + stringBytes.length + " bytes for \"" + s + "\""); buf.writeShort(stringBytes.length); buf.writeBytes(stringBytes); } } - + profiler.endStartSection("complex"); if (!complex.isEmpty()) { - NBTSquishDebugging.log("\nComplex dictionary size = " + complex.size()); - buf.writeShort(complex.size()); + if (debug) log("\nComplex dictionary size = " + complex.size()); + buf.writeVarInt(complex.size()); for (NBTBase nbt : complex) { if (nbt instanceof NBTTagList) { NBTTagList list = (NBTTagList) nbt; @@ -164,11 +179,13 @@ private void write(ByteBuf buf) { } } } + profiler.endSection(); + profiler.endSection(); } - private void writeList(WrittenType type, NBTTagList list, ByteBuf buf) { + private void writeList(WrittenType type, NBTTagList list, PacketBuffer buf) { boolean pack = shouldPackList(list); - NBTSquishDebugging.log("\n List tag count = " + list.tagCount() + ", writing it " + (pack ? "PACKED" : "NORMAL")); + if (debug) log("\n List tag count = " + list.tagCount() + ", writing it " + (pack ? "PACKED" : "NORMAL")); if (pack) { writeListPacked(type, buf, list); } else { @@ -177,49 +194,78 @@ private void writeList(WrittenType type, NBTTagList list, ByteBuf buf) { } private boolean shouldPackList(NBTTagList list) { + if (packList != null) return packList.booleanValue(); + profiler.startSection("should_pack"); TIntHashSet indexes = new TIntHashSet(); for (int i = 0; i < list.tagCount(); i++) { indexes.add(map.indexOfTag(list.get(i))); } + profiler.endSection(); return indexes.size() * 2 < list.tagCount(); } - private void writeCompound(WrittenType type, NBTTagCompound compound, ByteBuf buf) { + private void writeCompound(WrittenType type, NBTTagCompound compound, PacketBuffer buf) { + profiler.startSection("compound"); WrittenType stringType = WrittenType.getForSize(map.strings.size()); - NBTSquishDebugging.log("\n Compound tag count = " + compound.getSize()); + if (debug) log("\n Compound tag count = " + compound.getSize()); buf.writeByte(COMPLEX_COMPOUND); - buf.writeShort(compound.getSize()); + buf.writeVarInt(compound.getSize()); for (String key : compound.getKeySet()) { + profiler.startSection("entry"); NBTBase nbt = compound.getTag(key); + profiler.startSection("index_value"); int index = map.indexOfTag(nbt); - NBTSquishDebugging.log("\n \"" + key + "\" -> " + index + " (" + safeToString(nbt) + ")"); + profiler.endSection(); + if (debug) log("\n \"" + key + "\" -> " + index + " (" + safeToString(nbt) + ")"); + profiler.startSection("index_key"); stringType.writeIndex(buf, map.strings.indexOf(key)); + profiler.endSection(); type.writeIndex(buf, index); + profiler.endSection(); } + profiler.endSection(); } - private void writeListNormal(WrittenType type, ByteBuf buf, NBTTagList list) { + private void writeListNormal(WrittenType type, PacketBuffer buf, NBTTagList list) { + profiler.startSection("list_normal"); buf.writeByte(COMPLEX_LIST); - buf.writeShort(list.tagCount()); + buf.writeVarInt(list.tagCount()); for (int i = 0; i < list.tagCount(); i++) { - type.writeIndex(buf, map.indexOfTag(list.get(i))); + profiler.startSection("entry"); + if (i % 100 == 0) { + if (debug) log("\n List items " + i + " to " + Math.min(i + 99, list.tagCount())); + } + profiler.startSection("index"); + int index = map.indexOfTag(list.get(i)); + profiler.endSection(); + type.writeIndex(buf, index); + profiler.endSection(); } + profiler.endSection(); } - private void writeListPacked(WrittenType type, ByteBuf buf, NBTTagList list) { + private void writeListPacked(WrittenType type, PacketBuffer buf, NBTTagList list) { + profiler.startSection("list_packed"); buf.writeByte(COMPLEX_LIST_PACKED); + profiler.startSection("header"); + profiler.startSection("init"); int[] data = new int[list.tagCount()]; TIntIntHashMap indexes = new TIntIntHashMap(); for (int i = 0; i < list.tagCount(); i++) { + profiler.startSection("entry"); + profiler.startSection("index"); int index = map.indexOfTag(list.get(i)); + profiler.endSection(); data[i] = index; if (!indexes.increment(index)) { indexes.put(index, 1); } + profiler.endSection(); } // First try to make a simple table // First sort the indexes into highest count first + profiler.endStartSection("sort"); List entries = new ArrayList<>(); for (int index : indexes.keys()) { int count = indexes.get(index); @@ -227,8 +273,9 @@ private void writeListPacked(WrittenType type, ByteBuf buf, NBTTagList list) { entries.add(entry); } entries.sort(Comparator.reverseOrder()); - NBTSquishDebugging.log("\n " + entries.size() + " List entries"); - buf.writeShort(entries.size()); + if (debug) log("\n " + entries.size() + " List entries"); + buf.writeVarInt(entries.size()); + profiler.endStartSection("write"); TIntArrayList sortedIndexes = new TIntArrayList(); int i = 0; @@ -237,8 +284,8 @@ private void writeListPacked(WrittenType type, ByteBuf buf, NBTTagList list) { NBTBase base = map.getTagForWriting(entry.index); String n = safeToString(base); - NBTSquishDebugging.log("\n List entry #" + j + " = " + entry.count + "x" + entry.index + " (" + n + ")"); - + if (debug) log("\n List entry #" + j + " = " + entry.count + "x" + entry.index + " (" + n + ")"); + sortedIndexes.add(entry.index); type.writeIndex(buf, entry.index); i++; @@ -246,27 +293,45 @@ private void writeListPacked(WrittenType type, ByteBuf buf, NBTTagList list) { TIntArrayList nextData = new TIntArrayList(); nextData.add(data); - buf.writeMedium(data.length); + buf.writeVarInt(data.length); + profiler.endSection(); + profiler.endStartSection("contents"); for (int b = 1; !nextData.isEmpty(); b++) { + profiler.startSection("entry"); CompactingBitSet bitset = new CompactingBitSet(b); + bitset.ensureCapacityValues(nextData.size()); TIntArrayList nextNextData = new TIntArrayList(); int maxVal = (1 << b) - 1; + profiler.startSection("iter"); for (int d : nextData.toArray()) { + // profiler.startSection("entry"); + // profiler.startSection("index"); int index = sortedIndexes.indexOf(d); + // profiler.endSection(); if (index < maxVal) { + // profiler.startSection("bitset_append"); bitset.append(index); + // profiler.endSection(); } else { + // profiler.startSection("bitset_append"); bitset.append(maxVal); + // profiler.endStartSection("next_add"); nextNextData.add(d); + // profiler.endSection(); } + // profiler.endSection(); } + profiler.endSection(); sortedIndexes.remove(0, Math.min(sortedIndexes.size(), maxVal)); byte[] bitsetBytes = bitset.getBytes(); - NBTSquishDebugging.log("\n List bitset #" + (bitset.bits - 1)); - buf.writeShort(bitsetBytes.length); + if (debug) log("\n List bitset #" + (bitset.bits - 1)); + buf.writeVarInt(bitsetBytes.length); buf.writeBytes(bitsetBytes); nextData = nextNextData; + profiler.endSection(); } + profiler.endSection(); + profiler.endSection(); } public static String safeToString(NBTBase base) { diff --git a/common/buildcraft/lib/nbt/NbtSquisher.java b/common/buildcraft/lib/nbt/NbtSquisher.java index bf29c3854b..9d721d436d 100644 --- a/common/buildcraft/lib/nbt/NbtSquisher.java +++ b/common/buildcraft/lib/nbt/NbtSquisher.java @@ -9,13 +9,17 @@ import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.PacketBuffer; +import net.minecraft.profiler.Profiler; import buildcraft.api.data.NBTSquishConstants; -import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; public class NbtSquisher { + public static boolean debug = false; + public static final Profiler profiler = new Profiler(); + /* Defines a compression program that can turn large, mostly-similar, dense, NBTTagCompounds into much smaller * variants. * @@ -81,19 +85,18 @@ public static byte[] squishBuildCraftV1Uncompressed(NBTTagCompound nbt) { private static byte[] squishBuildCraftV1_Internal(NBTTagCompound nbt, boolean writeId) { NBTSquishMap map = new NBTSquishMap(); map.addTag(nbt); - ByteBuf buf = Unpooled.buffer(); - if (NBTSquishDebugging.debug) { - buf = new PrintingByteBuf(buf); - } + PacketBuffer buf = new PacketBuffer(Unpooled.buffer()); if (writeId) { buf.writeByte(NBTSquishConstants.BUILDCRAFT_V1); } - + if (debug) { + buf = new PrintingByteBuf(buf); + } + NBTSquishMapWriter.debug = debug; NBTSquishMapWriter.write(map, buf); WrittenType type = map.getWrittenType(); type.writeIndex(buf, map.indexOfTag(nbt)); - NBTSquishDebugging.log("\nUsed type " + type + " (as there are " + map.size() + " object types)"); byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); return bytes; @@ -104,13 +107,13 @@ public static NBTTagCompound expand(byte[] bytes) throws IOException { int nbtWrittenType = bais.read(); if (nbtWrittenType == NBTSquishConstants.BUILDCRAFT_V1 || nbtWrittenType == NBTSquishConstants.BUILDCRAFT_V1_COMPRESSED) { - ByteBuf buf; + PacketBuffer buf; if (nbtWrittenType == NBTSquishConstants.BUILDCRAFT_V1_COMPRESSED) { try (GZIPInputStream gzip = new GZIPInputStream(bais)) { - buf = Unpooled.wrappedBuffer(IOUtils.toByteArray(gzip)); + buf = new PacketBuffer(Unpooled.wrappedBuffer(IOUtils.toByteArray(gzip))); } } else { - buf = Unpooled.wrappedBuffer(bytes); + buf = new PacketBuffer(Unpooled.wrappedBuffer(bytes)); buf.readByte(); } @@ -118,8 +121,7 @@ public static NBTTagCompound expand(byte[] bytes) throws IOException { NBTSquishMap map = NBTSquishMapReader.read(buf); WrittenType type = map.getWrittenType(); int index = type.readIndex(buf); - NBTBase nbt = map.getTagForReading(index); - return (NBTTagCompound) nbt; + return map.getFullyReadComp(index); } catch (IndexOutOfBoundsException ioobe) { throw new IOException("The byte buf was not big enough!", ioobe); } diff --git a/common/buildcraft/lib/nbt/PrintingByteBuf.java b/common/buildcraft/lib/nbt/PrintingByteBuf.java index 66c28e8663..c7d36795cf 100644 --- a/common/buildcraft/lib/nbt/PrintingByteBuf.java +++ b/common/buildcraft/lib/nbt/PrintingByteBuf.java @@ -1,12 +1,17 @@ package buildcraft.lib.nbt; +import net.minecraft.network.PacketBuffer; + import buildcraft.lib.net.PacketBufferBC; import io.netty.buffer.ByteBuf; public final class PrintingByteBuf extends PacketBufferBC { + private final PacketBufferBC wrapped; + public PrintingByteBuf(ByteBuf wrapped) { super(wrapped); + this.wrapped = PacketBufferBC.asPacketBufferBc(wrapped); } @Override @@ -54,6 +59,22 @@ public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { return this; } + @Override + public PacketBuffer writeVarInt(int value) { + System.out.print(" _var("); + super.writeVarInt(value); + System.out.print(" )"); + return this; + } + + @Override + public PacketBuffer writeVarLong(long value) { + System.out.print(" _var("); + super.writeVarLong(value); + System.out.print(" )"); + return this; + } + @Override public ByteBuf writeShort(int val) { System.out.print(padLength(4, val)); diff --git a/common/buildcraft/lib/nbt/WrittenType.java b/common/buildcraft/lib/nbt/WrittenType.java index 377384ef0c..5d923f6f00 100644 --- a/common/buildcraft/lib/nbt/WrittenType.java +++ b/common/buildcraft/lib/nbt/WrittenType.java @@ -5,8 +5,8 @@ import io.netty.buffer.ByteBuf; public enum WrittenType { - BYTE(1, Byte.MAX_VALUE), - SHORT(2, Short.MAX_VALUE), + BYTE(1, (1 << 8) - 1), + SHORT(2, (1 << 16) - 1), MEDIUM(3, (1 << 24) - 1), INT(4, Integer.MAX_VALUE); @@ -44,6 +44,9 @@ public static WrittenType readType(ByteBuf bytes) throws IOException { } public void writeIndex(ByteBuf bytes, int index) { + if (index > maxStorableValue) { + throw new IllegalArgumentException("Tried to write a value that was too large! (" + index + " > " + maxStorableValue + " for " + this + ")"); + } switch (this) { case BYTE: { bytes.writeByte(index); diff --git a/common/buildcraft/lib/registry/CreativeTabManager.java b/common/buildcraft/lib/registry/CreativeTabManager.java index 5fb311de27..9568ae91b3 100644 --- a/common/buildcraft/lib/registry/CreativeTabManager.java +++ b/common/buildcraft/lib/registry/CreativeTabManager.java @@ -58,7 +58,7 @@ public static void setItemStack(String name, ItemStack item) { public static class CreativeTabBC extends CreativeTabs { private ItemStack item = new ItemStack(Items.COMPARATOR); // Temp. - public CreativeTabBC(String name) { + private CreativeTabBC(String name) { super(name); } diff --git a/common/buildcraft/lib/registry/TagManager.java b/common/buildcraft/lib/registry/TagManager.java index 934dec6843..19dce9dff9 100644 --- a/common/buildcraft/lib/registry/TagManager.java +++ b/common/buildcraft/lib/registry/TagManager.java @@ -192,224 +192,4 @@ public static Consumer setTab(String creativeTab) { } }; } - - // ######################### - // - // BuildCraft definitions - // - // ######################### - - static { - startBatch();// BC - - startBatch(); // lib - registerTag("item.guide").reg("guide").locale("guide").model("guide").tab("vanilla.misc"); - registerTag("item.debugger").reg("debugger").locale("debugger").model("debugger").tab("vanilla.misc"); - endBatch(prependTags("lib:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION)); - - startBatch();// core - // BC Core Items - registerTag("item.wrench").reg("wrench").locale("wrenchItem").oldReg("wrenchItem").model("wrench"); - registerTag("item.diamond.shard").reg("diamond_shard").locale("diamondShard").model("diamond_shard").tab("vanilla.materials"); - registerTag("item.gear.wood").reg("gear_wood").locale("woodenGearItem").oreDict("gearWood").oldReg("woodenGearItem").model("gears/wood"); - registerTag("item.gear.stone").reg("gear_stone").locale("stoneGearItem").oreDict("gearStone").oldReg("stoneGearItem").model("gears/stone"); - registerTag("item.gear.iron").reg("gear_iron").locale("ironGearItem").oreDict("gearIron").oldReg("ironGearItem").model("gears/iron"); - registerTag("item.gear.gold").reg("gear_gold").locale("goldGearItem").oreDict("gearGold").oldReg("goldGearItem").model("gears/gold"); - registerTag("item.gear.diamond").reg("gear_diamond").locale("diamondGearItem").oreDict("gearDiamond").oldReg("diamondGearItem").model("gears/diamond"); - registerTag("item.list").reg("list").locale("list").oldReg("listItem").model("list_"); - registerTag("item.map_location").reg("map_location").locale("mapLocation").oldReg("mapLocation").model("map_location/"); - registerTag("item.paintbrush").reg("paintbrush").locale("paintbrush").model("paintbrush/"); - registerTag("item.marker_connector").reg("marker_connector").locale("markerConnector").model("marker_connector"); - registerTag("item.volume_marker").reg("volume_marker").locale("volume_marker").model("volume_marker"); - // BC Core ItemBlocks - registerTag("item.block.marker.volume").reg("marker_volume").locale("markerBlock").oldReg("markerBlock").model("marker_volume"); - registerTag("item.block.marker.path").reg("marker_path").locale("pathMarkerBlock").oldReg("pathMarkerBlock").model("marker_path"); - registerTag("item.block.spring").reg("spring").locale("spring").model("spring"); - registerTag("item.block.decorated").reg("decorated").locale("decorated").model("decorated/"); - registerTag("item.block.engine.bc").reg("engine").locale("engineBlock").model("engine/"); - // BC Core Blocks - registerTag("block.spring").reg("spring").locale("spring"); - registerTag("block.decorated").reg("decorated").locale("decorated"); - registerTag("block.engine.bc").reg("engine").locale("engineBlock").oldReg("engineBlock"); - registerTag("block.engine.bc.wood").locale("engineBlockWood"); - registerTag("block.engine.bc.stone").locale("engineBlockStone"); - registerTag("block.engine.bc.iron").locale("engineBlockIron"); - registerTag("block.engine.bc.creative").locale("engineBlockCreative"); - registerTag("block.marker.volume").reg("marker_volume").locale("markerBlock").oldReg("markerBlock").model("marker_volume"); - registerTag("block.marker.path").reg("marker_path").locale("pathMarkerBlock").oldReg("pathMarkerBlock").model("marker_path"); - // BC Core Tiles - registerTag("tile.marker.volume").reg("marker.volume").oldReg("buildcraft.builders.Marker", "Marker"); - registerTag("tile.marker.path").reg("marker.path"); - registerTag("tile.engine.wood").reg("engine.wood"); - - endBatch(prependTags("core:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION)); - - startBatch();// builders - // BC Builders Items - registerTag("item.schematic.single").reg("schematic_single").locale("schematicSingle").model("schematic_single/"); - registerTag("item.blueprint").reg("blueprint").locale("blueprintItem").model("blueprint/"); - // BC Builders Item Blocks - registerTag("item.block.architect").reg("architect").locale("architectBlock").model("architect"); - registerTag("item.block.builder").reg("builder").locale("builderBlock").model("builder"); - registerTag("item.block.filler").reg("filler").locale("fillerBlock").model("filler"); - registerTag("item.block.library").reg("library").locale("libraryBlock").model("library"); - registerTag("item.block.frame").reg("frame").locale("frameBlock").model("frame"); - registerTag("item.block.quarry").reg("quarry").locale("quarryBlock").model("quarry"); - // BC Builders Blocks - registerTag("block.architect").reg("architect").locale("architectBlock").model("architect"); - registerTag("block.builder").reg("builder").locale("builderBlock").model("builder"); - registerTag("block.filler").reg("filler").locale("fillerBlock").model("filler"); - registerTag("block.library").reg("library").locale("libraryBlock").model("library"); - registerTag("block.frame").reg("frame").locale("frameBlock").model("frame"); - registerTag("block.quarry").reg("quarry").locale("quarryBlock").model("quarry"); - // BC Builders Tiles - registerTag("tile.architect").reg("architect"); - registerTag("tile.library").reg("library"); - registerTag("tile.builder").reg("builder"); - registerTag("tile.filler").reg("filler"); - registerTag("tile.quarry").reg("quarry"); - - endBatch(prependTags("builders:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION)); - - startBatch();// energy - registerTag("item.glob.oil").reg("glob_oil").locale("globOil").model("glob_oil"); - // BC Energy Items - // BC Energy Item Blocks - // BC Energy Blocks - // BC Energy Tiles - registerTag("tile.engine.stone").reg("engine.stone"); - registerTag("tile.engine.iron").reg("engine.iron"); - - endBatch(prependTags("energy:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION)); - - startBatch();// factory - // BC Factory Items - registerTag("item.plastic.sheet").reg("plastic_sheet").locale("plasticSheet").oldReg("plasticSheet").model("plastic_sheet"); - registerTag("item.water_gel_spawn").reg("water_gel_spawn").locale("waterGel").model("water_gel"); - registerTag("item.gel").reg("gel").locale("gel").model("gel"); - // BC Factory Item Blocks - registerTag("item.block.plastic").reg("plastic_block").locale("plasticBlock").model("plastic_block/"); - registerTag("item.block.autoworkbench.item").reg("autoworkbench_item").locale("autoWorkbenchBlock").model("autoworkbench_item"); - registerTag("item.block.mining_well").reg("mining_well").locale("miningWellBlock").model("mining_well"); - registerTag("item.block.pump").reg("pump").locale("pumpBlock").model("pump"); - registerTag("item.block.flood_gate").reg("flood_gate").locale("floodGateBlock").model("flood_gate"); - registerTag("item.block.tank").reg("tank").locale("tankBlock").model("tank"); - registerTag("item.block.chute").reg("chute").locale("chuteBlock").model("chute"); - // BC Factory Blocks - registerTag("block.plastic").reg("plastic").locale("plasticBlock").model("plastic"); - registerTag("block.autoworkbench.item").reg("autoworkbench_item").oldReg("autoWorkbenchBlock").locale("autoWorkbenchBlock").model("autoworkbench_item"); - registerTag("block.mining_well").reg("mining_well").oldReg("miningWellBlock").locale("miningWellBlock").model("mining_well"); - registerTag("block.pump").reg("pump").oldReg("pumpBlock").locale("pumpBlock").model("pump"); - registerTag("block.flood_gate").reg("flood_gate").oldReg("floodGateBlock").locale("floodGateBlock").model("flood_gate"); - registerTag("block.tank").reg("tank").oldReg("tankBlock").locale("tankBlock").model("tank"); - registerTag("block.chute").reg("chute").oldReg("chuteBlock").locale("chuteBlock").model("chute"); - registerTag("block.water_gel").reg("water_gel").locale("waterGel").model("water_gel"); - // BC Factory Tiles - registerTag("tile.autoworkbench.item").reg("autoworkbench_item"); - registerTag("tile.mining_well").reg("mining_well"); - registerTag("tile.pump").reg("pump"); - registerTag("tile.flood_gate").reg("flood_gate"); - registerTag("tile.tank").reg("tank"); - registerTag("tile.chute").reg("chute"); - - endBatch(prependTags("factory:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION)); - - startBatch();// transport - // BC Transport Items - registerTag("item.waterproof").reg("waterproof").locale("pipeWaterproof").oldReg("pipeWaterproof").model("waterproof"); - registerTag("item.plug.blocker").reg("plug_blocker").locale("PipePlug").model("plug_blocker"); - registerTag("item.plug.gate").reg("plug_gate").locale("gate").model("pluggable/gate").tab("buildcraft.gates"); - registerTag("item.plug.pulsar").reg("plug_pulsar").locale("pulsar").model("plug_pulsar"); - registerTag("item.plug.daylight_sensor").reg("plug_daylight_sensor").locale("daylight_sensor").model("plug_daylight_sensor"); - registerTag("item.wire").reg("wire").locale("pipeWire").model("wire/"); - // BC Transport Pipes - startBatch();// Pipes - registerTag("item.pipe.buildcrafttransport.structure").reg("pipe_structure").locale("PipeStructureCobblestone"); - registerTag("item.pipe.buildcrafttransport.wood_item").reg("pipe_wood_item").locale("PipeItemsWood"); - registerTag("item.pipe.buildcrafttransport.wood_fluid").reg("pipe_wood_fluid").locale("PipeFluidsWood"); - registerTag("item.pipe.buildcrafttransport.wood_power").reg("pipe_wood_power").locale("PipePowerWood"); - registerTag("item.pipe.buildcrafttransport.stone_item").reg("pipe_stone_item").locale("PipeItemsStone"); - registerTag("item.pipe.buildcrafttransport.stone_fluid").reg("pipe_stone_fluid").locale("PipeFluidsStone"); - registerTag("item.pipe.buildcrafttransport.stone_power").reg("pipe_stone_power").locale("PipePowerStone"); - registerTag("item.pipe.buildcrafttransport.cobblestone_item").reg("pipe_cobble_item").locale("PipeItemsCobblestone"); - registerTag("item.pipe.buildcrafttransport.cobblestone_fluid").reg("pipe_cobble_fluid").locale("PipeFluidsCobblestone"); - registerTag("item.pipe.buildcrafttransport.cobblestone_power").reg("pipe_cobble_power").locale("PipePowerCobblestone"); - registerTag("item.pipe.buildcrafttransport.quartz_item").reg("pipe_quartz_item").locale("PipeItemsQuartz"); - registerTag("item.pipe.buildcrafttransport.quartz_fluid").reg("pipe_quartz_fluid").locale("PipeFluidsQuartz"); - registerTag("item.pipe.buildcrafttransport.quartz_power").reg("pipe_quartz_power").locale("PipePowerQuartz"); - registerTag("item.pipe.buildcrafttransport.gold_item").reg("pipe_gold_item").locale("PipeItemsGold"); - registerTag("item.pipe.buildcrafttransport.gold_fluid").reg("pipe_gold_fluid").locale("PipeFluidsGold"); - registerTag("item.pipe.buildcrafttransport.gold_power").reg("pipe_gold_power").locale("PipePowerGold"); - registerTag("item.pipe.buildcrafttransport.sandstone_item").reg("pipe_sandstone_item").locale("PipeItemsSandstone"); - registerTag("item.pipe.buildcrafttransport.sandstone_fluid").reg("pipe_sandstone_fluid").locale("PipeFluidsSandstone"); - registerTag("item.pipe.buildcrafttransport.sandstone_power").reg("pipe_sandstone_power").locale("PipePowerSandstone"); - registerTag("item.pipe.buildcrafttransport.iron_item").reg("pipe_iron_item").locale("PipeItemsIron"); - registerTag("item.pipe.buildcrafttransport.iron_fluid").reg("pipe_iron_fluid").locale("PipeFluidsIron"); - registerTag("item.pipe.buildcrafttransport.iron_power").reg("pipe_iron_power").locale("PipePowerIron"); - registerTag("item.pipe.buildcrafttransport.diamond_item").reg("pipe_diamond_item").locale("PipeItemsDiamond"); - registerTag("item.pipe.buildcrafttransport.diamond_fluid").reg("pipe_diamond_fluid").locale("PipeFluidsDiamond"); - registerTag("item.pipe.buildcrafttransport.diamond_power").reg("pipe_diamond_power").locale("PipePowerDiamond"); - registerTag("item.pipe.buildcrafttransport.diamond_wood_item").reg("pipe_diamond_wood_item").locale("PipeItemsEmerald"); - registerTag("item.pipe.buildcrafttransport.diamond_wood_fluid").reg("pipe_diamond_wood_fluid").locale("PipeFluidsEmerald"); - registerTag("item.pipe.buildcrafttransport.diamond_wood_power").reg("pipe_diamond_wood_power").locale("PipePowerEmerald"); - registerTag("item.pipe.buildcrafttransport.clay_item").reg("pipe_clay_item").locale("PipeItemsClay"); - registerTag("item.pipe.buildcrafttransport.clay_fluid").reg("pipe_clay_fluid").locale("PipeFluidsClay"); - registerTag("item.pipe.buildcrafttransport.void_item").reg("pipe_void_item").locale("PipeItemsVoid"); - registerTag("item.pipe.buildcrafttransport.void_fluid").reg("pipe_void_fluid").locale("PipeFluidsVoid"); - registerTag("item.pipe.buildcrafttransport.obsidian_item").reg("pipe_obsidian_item").locale("PipeItemsObsidian"); - registerTag("item.pipe.buildcrafttransport.obsidian_fluid").reg("pipe_obsidian_fluid").locale("PipeFluidsObsidian"); - registerTag("item.pipe.buildcrafttransport.lapis_item").reg("pipe_lapis_fluid").locale("PipeItemsLapis"); - registerTag("item.pipe.buildcrafttransport.daizuli_item").reg("pipe_daizuli_fluid").locale("PipeItemsDaizuli"); - endBatch(setTab("buildcraft.pipes")); - // BC Transport Item Blocks - registerTag("item.block.filtered_buffer").reg("filtered_buffer").locale("filteredBufferBlock").model("filtered_buffer"); - // BC Transport Blocks - registerTag("block.filtered_buffer").reg("filtered_buffer").oldReg("filteredBufferBlock").locale("filteredBufferBlock").model("filtered_buffer"); - registerTag("block.pipe_holder").reg("pipe_holder").locale("pipeHolder"); - // BC Transport Tiles - registerTag("tile.filtered_buffer").reg("filtered_buffer"); - registerTag("tile.pipe_holder").reg("pipe_holder"); - - endBatch(prependTags("transport:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION)); - - startBatch();// robotics - // BC Robotics Items - // BC Robotics Item Blocks - registerTag("item.block.zone_planner").reg("zone_planner").locale("zonePlannerBlock").model("zone_planner"); - // BC Robotics Blocks - registerTag("block.zone_planner").reg("zone_planner").oldReg("zonePlannerBlock").locale("zonePlannerBlock").model("zone_planner"); - // BC Robotics Tiles - registerTag("tile.zone_planner").reg("zone_planner"); - - endBatch(prependTags("robotics:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION)); - - startBatch();// silicon - // BC Silicon Items - registerTag("item.redstone_chipset").reg("redstone_chipset").locale("redstone_chipset").model("redstone_chipset/"); - // BC Silicon Item Blocks - registerTag("item.block.laser").reg("laser").locale("laserBlock").model("laser"); - registerTag("item.block.assembly_table").reg("assembly_table").locale("assemblyTableBlock").model("assembly_table"); - registerTag("item.block.advanced_crafting_table").reg("advanced_crafting_table").locale("assemblyWorkbenchBlock").model("advanced_crafting_table"); - registerTag("item.block.integration_table").reg("integration_table").locale("integrationTableBlock").model("integration_table"); - registerTag("item.block.charging_table").reg("charging_table").locale("chargingTableBlock").model("charging_table"); - registerTag("item.block.programming_table").reg("programming_table").locale("programmingTableBlock").model("programming_table"); - // BC Silicon Blocks - registerTag("block.laser").reg("laser").oldReg("laserBlock").locale("laserBlock").model("laser"); - registerTag("block.assembly_table").reg("assembly_table").oldReg("assemblyTableBlock").locale("assemblyTableBlock").model("assembly_table"); - registerTag("block.advanced_crafting_table").reg("advanced_crafting_table").oldReg("advancedCraftingTableBlock").locale("advancedCraftingTableBlock").model("advanced_crafting_table"); - registerTag("block.integration_table").reg("integration_table").oldReg("integrationTableBlock").locale("integrationTableBlock").model("integration_table"); - registerTag("block.charging_table").reg("charging_table").oldReg("chargingTableBlock").locale("chargingTableBlock").model("charging_table"); - registerTag("block.programming_table").reg("programming_table").oldReg("programmingTableBlock").locale("programmingTableBlock").model("programming_table"); - // BC Silicon Tiles - registerTag("tile.laser").reg("laser"); - registerTag("tile.assembly_table").reg("assembly_table"); - registerTag("tile.advanced_crafting_table").reg("advanced_crafting_table"); - registerTag("tile.integration_table").reg("integration_table"); - registerTag("tile.charging_table").reg("charging_table"); - registerTag("tile.programming_table").reg("programming_table"); - - endBatch(prependTags("silicon:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION)); - - endBatch(prependTags("buildcraft", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION).andThen(setTab("buildcraft.main"))); - } } diff --git a/common/buildcraft/robotics/BCRobotics.java b/common/buildcraft/robotics/BCRobotics.java index 7236a01667..edbb008128 100644 --- a/common/buildcraft/robotics/BCRobotics.java +++ b/common/buildcraft/robotics/BCRobotics.java @@ -1,5 +1,7 @@ package buildcraft.robotics; +import java.util.function.Consumer; + import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; @@ -11,6 +13,9 @@ import buildcraft.lib.BCLib; import buildcraft.lib.BCMessageHandler; import buildcraft.lib.registry.RegistryHelper; +import buildcraft.lib.registry.TagManager; +import buildcraft.lib.registry.TagManager.EnumTagType; +import buildcraft.lib.registry.TagManager.TagEntry; import buildcraft.robotics.zone.MessageZoneMapRequest; import buildcraft.robotics.zone.MessageZoneMapResponse; @@ -49,4 +54,33 @@ public static void init(FMLInitializationEvent evt) { public static void postInit(FMLPostInitializationEvent evt) { } + + static { + startBatch(); + + // Items + + // Item Blocks + registerTag("item.block.zone_planner").reg("zone_planner").locale("zonePlannerBlock").model("zone_planner"); + + // Blocks + registerTag("block.zone_planner").reg("zone_planner").oldReg("zonePlannerBlock").locale("zonePlannerBlock").model("zone_planner"); + + // Tiles + registerTag("tile.zone_planner").reg("zone_planner"); + + endBatch(TagManager.prependTags("buildcraftrobotics:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION).andThen(TagManager.setTab("buildcraft.main"))); + } + + private static TagEntry registerTag(String id) { + return TagManager.registerTag(id); + } + + private static void startBatch() { + TagManager.startBatch(); + } + + private static void endBatch(Consumer consumer) { + TagManager.endBatch(consumer); + } } diff --git a/common/buildcraft/silicon/BCSilicon.java b/common/buildcraft/silicon/BCSilicon.java index 275104b7df..4037f19c7b 100644 --- a/common/buildcraft/silicon/BCSilicon.java +++ b/common/buildcraft/silicon/BCSilicon.java @@ -1,5 +1,7 @@ package buildcraft.silicon; +import java.util.function.Consumer; + import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; @@ -9,6 +11,9 @@ import buildcraft.core.BCCore; import buildcraft.lib.BCLib; import buildcraft.lib.registry.RegistryHelper; +import buildcraft.lib.registry.TagManager; +import buildcraft.lib.registry.TagManager.EnumTagType; +import buildcraft.lib.registry.TagManager.TagEntry; //@formatter:off @Mod(modid = BCSilicon.MODID, @@ -44,4 +49,45 @@ public void init(FMLInitializationEvent evt) { public void postInit(FMLPostInitializationEvent evt) { } + + static { + startBatch(); + // Items + registerTag("item.redstone_chipset").reg("redstone_chipset").locale("redstone_chipset").model("redstone_chipset/"); + // Item Blocks + registerTag("item.block.laser").reg("laser").locale("laserBlock").model("laser"); + registerTag("item.block.assembly_table").reg("assembly_table").locale("assemblyTableBlock").model("assembly_table"); + registerTag("item.block.advanced_crafting_table").reg("advanced_crafting_table").locale("assemblyWorkbenchBlock").model("advanced_crafting_table"); + registerTag("item.block.integration_table").reg("integration_table").locale("integrationTableBlock").model("integration_table"); + registerTag("item.block.charging_table").reg("charging_table").locale("chargingTableBlock").model("charging_table"); + registerTag("item.block.programming_table").reg("programming_table").locale("programmingTableBlock").model("programming_table"); + // Blocks + registerTag("block.laser").reg("laser").oldReg("laserBlock").locale("laserBlock").model("laser"); + registerTag("block.assembly_table").reg("assembly_table").oldReg("assemblyTableBlock").locale("assemblyTableBlock").model("assembly_table"); + registerTag("block.advanced_crafting_table").reg("advanced_crafting_table").oldReg("advancedCraftingTableBlock").locale("advancedCraftingTableBlock").model("advanced_crafting_table"); + registerTag("block.integration_table").reg("integration_table").oldReg("integrationTableBlock").locale("integrationTableBlock").model("integration_table"); + registerTag("block.charging_table").reg("charging_table").oldReg("chargingTableBlock").locale("chargingTableBlock").model("charging_table"); + registerTag("block.programming_table").reg("programming_table").oldReg("programmingTableBlock").locale("programmingTableBlock").model("programming_table"); + // Tiles + registerTag("tile.laser").reg("laser"); + registerTag("tile.assembly_table").reg("assembly_table"); + registerTag("tile.advanced_crafting_table").reg("advanced_crafting_table"); + registerTag("tile.integration_table").reg("integration_table"); + registerTag("tile.charging_table").reg("charging_table"); + registerTag("tile.programming_table").reg("programming_table"); + + endBatch(TagManager.prependTags("buildcraftsilicon:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION).andThen(TagManager.setTab("buildcraft.main"))); + } + + private static TagEntry registerTag(String id) { + return TagManager.registerTag(id); + } + + private static void startBatch() { + TagManager.startBatch(); + } + + private static void endBatch(Consumer consumer) { + TagManager.endBatch(consumer); + } } diff --git a/common/buildcraft/transport/BCTransport.java b/common/buildcraft/transport/BCTransport.java index cfa8c92cd3..59767da806 100644 --- a/common/buildcraft/transport/BCTransport.java +++ b/common/buildcraft/transport/BCTransport.java @@ -1,5 +1,7 @@ package buildcraft.transport; +import java.util.function.Consumer; + import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; @@ -23,6 +25,9 @@ import buildcraft.lib.registry.CreativeTabManager; import buildcraft.lib.registry.CreativeTabManager.CreativeTabBC; import buildcraft.lib.registry.RegistryHelper; +import buildcraft.lib.registry.TagManager; +import buildcraft.lib.registry.TagManager.EnumTagType; +import buildcraft.lib.registry.TagManager.TagEntry; import buildcraft.transport.pipe.PipeRegistry; import buildcraft.transport.pipe.flow.PipeFlowFluids; import buildcraft.transport.pipe.flow.PipeFlowItems; @@ -57,7 +62,7 @@ public static void preInit(FMLPreInitializationEvent evt) { PipeAPI.flowStructure = new PipeFlowType(PipeFlowStructure::new, PipeFlowStructure::new); CreativeTabBC tabPipes = CreativeTabManager.createTab("buildcraft.pipes"); - CreativeTabBC tabGates = CreativeTabManager.createTab("buildcraft.gates"); + CreativeTabBC tabPlugs = CreativeTabManager.createTab("buildcraft.plugs"); BCTransportConfig.preInit(); BCTransportBlocks.preInit(); @@ -75,7 +80,7 @@ public static void preInit(FMLPreInitializationEvent evt) { BCTransportConfig.reloadConfig(EnumRestartRequirement.GAME); tabPipes.setItem(BCTransportItems.pipeItemDiamond); - tabGates.setItem(BCTransportItems.plugGate); + tabPlugs.setItem(BCTransportItems.plugGate); NetworkRegistry.INSTANCE.registerGuiHandler(INSTANCE, BCTransportProxy.getProxy()); @@ -96,4 +101,76 @@ public static void init(FMLInitializationEvent evt) { public static void postInit(FMLPostInitializationEvent evt) { BCTransportProxy.getProxy().fmlPostInit(); } + + static { + startBatch(); + // Items + registerTag("item.waterproof").reg("waterproof").locale("pipeWaterproof").oldReg("pipeWaterproof").model("waterproof"); + registerTag("item.plug.blocker").reg("plug_blocker").locale("PipePlug").model("plug_blocker").tab("buildcraft.plugs"); + registerTag("item.plug.gate").reg("plug_gate").locale("gate").model("pluggable/gate").tab("buildcraft.plugs"); + registerTag("item.plug.pulsar").reg("plug_pulsar").locale("pulsar").model("plug_pulsar").tab("buildcraft.plugs"); + registerTag("item.plug.daylight_sensor").reg("plug_daylight_sensor").locale("daylight_sensor").model("plug_daylight_sensor").tab("buildcraft.plugs"); + registerTag("item.wire").reg("wire").locale("pipeWire").model("wire/").tab("buildcraft.plugs"); + // Pipes + startBatch();// Pipes + registerTag("item.pipe.buildcrafttransport.structure").reg("pipe_structure").locale("PipeStructureCobblestone"); + registerTag("item.pipe.buildcrafttransport.wood_item").reg("pipe_wood_item").locale("PipeItemsWood"); + registerTag("item.pipe.buildcrafttransport.wood_fluid").reg("pipe_wood_fluid").locale("PipeFluidsWood"); + registerTag("item.pipe.buildcrafttransport.wood_power").reg("pipe_wood_power").locale("PipePowerWood"); + registerTag("item.pipe.buildcrafttransport.stone_item").reg("pipe_stone_item").locale("PipeItemsStone"); + registerTag("item.pipe.buildcrafttransport.stone_fluid").reg("pipe_stone_fluid").locale("PipeFluidsStone"); + registerTag("item.pipe.buildcrafttransport.stone_power").reg("pipe_stone_power").locale("PipePowerStone"); + registerTag("item.pipe.buildcrafttransport.cobblestone_item").reg("pipe_cobble_item").locale("PipeItemsCobblestone"); + registerTag("item.pipe.buildcrafttransport.cobblestone_fluid").reg("pipe_cobble_fluid").locale("PipeFluidsCobblestone"); + registerTag("item.pipe.buildcrafttransport.cobblestone_power").reg("pipe_cobble_power").locale("PipePowerCobblestone"); + registerTag("item.pipe.buildcrafttransport.quartz_item").reg("pipe_quartz_item").locale("PipeItemsQuartz"); + registerTag("item.pipe.buildcrafttransport.quartz_fluid").reg("pipe_quartz_fluid").locale("PipeFluidsQuartz"); + registerTag("item.pipe.buildcrafttransport.quartz_power").reg("pipe_quartz_power").locale("PipePowerQuartz"); + registerTag("item.pipe.buildcrafttransport.gold_item").reg("pipe_gold_item").locale("PipeItemsGold"); + registerTag("item.pipe.buildcrafttransport.gold_fluid").reg("pipe_gold_fluid").locale("PipeFluidsGold"); + registerTag("item.pipe.buildcrafttransport.gold_power").reg("pipe_gold_power").locale("PipePowerGold"); + registerTag("item.pipe.buildcrafttransport.sandstone_item").reg("pipe_sandstone_item").locale("PipeItemsSandstone"); + registerTag("item.pipe.buildcrafttransport.sandstone_fluid").reg("pipe_sandstone_fluid").locale("PipeFluidsSandstone"); + registerTag("item.pipe.buildcrafttransport.sandstone_power").reg("pipe_sandstone_power").locale("PipePowerSandstone"); + registerTag("item.pipe.buildcrafttransport.iron_item").reg("pipe_iron_item").locale("PipeItemsIron"); + registerTag("item.pipe.buildcrafttransport.iron_fluid").reg("pipe_iron_fluid").locale("PipeFluidsIron"); + registerTag("item.pipe.buildcrafttransport.iron_power").reg("pipe_iron_power").locale("PipePowerIron"); + registerTag("item.pipe.buildcrafttransport.diamond_item").reg("pipe_diamond_item").locale("PipeItemsDiamond"); + registerTag("item.pipe.buildcrafttransport.diamond_fluid").reg("pipe_diamond_fluid").locale("PipeFluidsDiamond"); + registerTag("item.pipe.buildcrafttransport.diamond_power").reg("pipe_diamond_power").locale("PipePowerDiamond"); + registerTag("item.pipe.buildcrafttransport.diamond_wood_item").reg("pipe_diamond_wood_item").locale("PipeItemsEmerald"); + registerTag("item.pipe.buildcrafttransport.diamond_wood_fluid").reg("pipe_diamond_wood_fluid").locale("PipeFluidsEmerald"); + registerTag("item.pipe.buildcrafttransport.diamond_wood_power").reg("pipe_diamond_wood_power").locale("PipePowerEmerald"); + registerTag("item.pipe.buildcrafttransport.clay_item").reg("pipe_clay_item").locale("PipeItemsClay"); + registerTag("item.pipe.buildcrafttransport.clay_fluid").reg("pipe_clay_fluid").locale("PipeFluidsClay"); + registerTag("item.pipe.buildcrafttransport.void_item").reg("pipe_void_item").locale("PipeItemsVoid"); + registerTag("item.pipe.buildcrafttransport.void_fluid").reg("pipe_void_fluid").locale("PipeFluidsVoid"); + registerTag("item.pipe.buildcrafttransport.obsidian_item").reg("pipe_obsidian_item").locale("PipeItemsObsidian"); + registerTag("item.pipe.buildcrafttransport.obsidian_fluid").reg("pipe_obsidian_fluid").locale("PipeFluidsObsidian"); + registerTag("item.pipe.buildcrafttransport.lapis_item").reg("pipe_lapis_fluid").locale("PipeItemsLapis"); + registerTag("item.pipe.buildcrafttransport.daizuli_item").reg("pipe_daizuli_fluid").locale("PipeItemsDaizuli"); + endBatch(TagManager.setTab("buildcraft.pipes")); + // Item Blocks + registerTag("item.block.filtered_buffer").reg("filtered_buffer").locale("filteredBufferBlock").model("filtered_buffer"); + // Blocks + registerTag("block.filtered_buffer").reg("filtered_buffer").oldReg("filteredBufferBlock").locale("filteredBufferBlock").model("filtered_buffer"); + registerTag("block.pipe_holder").reg("pipe_holder").locale("pipeHolder"); + // Tiles + registerTag("tile.filtered_buffer").reg("filtered_buffer"); + registerTag("tile.pipe_holder").reg("pipe_holder"); + + endBatch(TagManager.prependTags("buildcrafttransport:", EnumTagType.REGISTRY_NAME, EnumTagType.MODEL_LOCATION).andThen(TagManager.setTab("buildcraft.main"))); + } + + private static TagEntry registerTag(String id) { + return TagManager.registerTag(id); + } + + private static void startBatch() { + TagManager.startBatch(); + } + + private static void endBatch(Consumer consumer) { + TagManager.endBatch(consumer); + } } diff --git a/common/buildcraft/transport/client/model/PipeBaseModelGenStandard.java b/common/buildcraft/transport/client/model/PipeBaseModelGenStandard.java index b0e3b9f364..0f42154308 100644 --- a/common/buildcraft/transport/client/model/PipeBaseModelGenStandard.java +++ b/common/buildcraft/transport/client/model/PipeBaseModelGenStandard.java @@ -77,7 +77,7 @@ public TextureAtlasSprite getItemSprite(PipeDefinition def, int index) { uvs.uMax = uvs.vMax = 12; for (EnumFacing face : EnumFacing.VALUES) { MutableQuad quad = ModelUtil.createFace(face, center, radius, uvs); - quad.setDiffuse(quad.getVertex(0).normal()); + quad.setDiffuse(quad.normalvf()); QUADS[0][face.ordinal()][0] = quad; dupDarker(QUADS[0][face.ordinal()]); @@ -128,7 +128,7 @@ public TextureAtlasSprite getItemSprite(PipeDefinition def, int index) { MutableQuad col = new MutableQuad(quad); - quad.setDiffuse(quad.getVertex(0).normal()); + quad.setDiffuse(quad.normalvf()); QUADS[1][side.ordinal()][i] = quad; col.translatevd(faceOffset[face.ordinal()]); @@ -146,8 +146,7 @@ private static void dupDarker(MutableQuad[] quads) { int n = i + halfLength; MutableQuad from = quads[i]; if (from != null) { - MutableQuad to = new MutableQuad(from); - to.invertNormal(); + MutableQuad to = from.copyAndInvertNormal(); to.setCalculatedDiffuse(); to.multColourd(mult); quads[n] = to; @@ -161,9 +160,7 @@ private static void dupInverted(MutableQuad[] quads) { int n = i + halfLength; MutableQuad from = quads[i]; if (from != null) { - MutableQuad to = new MutableQuad(from); - to.invertNormal(); - quads[n] = to; + quads[n] = from.copyAndInvertNormal(); } } } @@ -187,7 +184,7 @@ public List generateCutout(PipeBaseCutoutKey key) { for (MutableQuad q : quads) { bakedQuads.add(q.toBakedBlock()); } - return bakedQuads; + return ImmutableList.of();//bakedQuads; } private static TextureAtlasSprite getSprite(TextureAtlasSprite[] array, int index) { diff --git a/common/buildcraft/transport/client/model/PipeModelCacheAll.java b/common/buildcraft/transport/client/model/PipeModelCacheAll.java index ed2f491e10..2c7622117d 100644 --- a/common/buildcraft/transport/client/model/PipeModelCacheAll.java +++ b/common/buildcraft/transport/client/model/PipeModelCacheAll.java @@ -36,8 +36,7 @@ public static List getCutoutModel(TilePipeHolder tile) { } public static List getTranslucentModel(TilePipeHolder tile) { - PipeAllTranslucentKey key = new PipeAllTranslucentKey(tile); - return cacheTranslucent.bake(key); + return cacheTranslucent.bake(new PipeAllTranslucentKey(tile)); } public static void clearModels() { diff --git a/common/buildcraft/transport/client/model/plug/PlugBakerBlocker.java b/common/buildcraft/transport/client/model/plug/PlugBakerBlocker.java index 511f9963a0..106849ba22 100644 --- a/common/buildcraft/transport/client/model/plug/PlugBakerBlocker.java +++ b/common/buildcraft/transport/client/model/plug/PlugBakerBlocker.java @@ -28,17 +28,14 @@ public List bake(KeyPlugBlocker key) { MutableQuad[] quads = BCTransportModels.BLOCKER.getCutoutQuads(); if (quads != lastSeen) { cached.clear(); - MutableQuad copy = new MutableQuad(0, null); + MutableQuad copy = new MutableQuad(); for (EnumFacing to : EnumFacing.VALUES) { List list = new ArrayList<>(); Matrix4f transform = MatrixUtil.rotateTowardsFace(to); for (MutableQuad q : quads) { copy.copyFrom(q); copy.transform(transform); - copy.lightf(1, 1); - if (copy.isShade()) { - copy.setCalculatedDiffuse(); - } + copy.multShade(); list.add(copy.toBakedBlock()); } cached.put(to, list); diff --git a/common/buildcraft/transport/client/model/plug/PlugBakerDaylightSensor.java b/common/buildcraft/transport/client/model/plug/PlugBakerDaylightSensor.java index d45082b9d4..4ddfc446ed 100644 --- a/common/buildcraft/transport/client/model/plug/PlugBakerDaylightSensor.java +++ b/common/buildcraft/transport/client/model/plug/PlugBakerDaylightSensor.java @@ -28,16 +28,14 @@ public List bake(KeyPlugDaylightSensor key) { MutableQuad[] quads = BCTransportModels.DAYLIGHT_SENSOR.getCutoutQuads(); if (quads != lastSeen) { cached.clear(); - MutableQuad copy = new MutableQuad(0, null); + MutableQuad copy = new MutableQuad(); for (EnumFacing to : EnumFacing.VALUES) { List list = new ArrayList<>(); Matrix4f transform = MatrixUtil.rotateTowardsFace(to); for (MutableQuad q : quads) { copy.copyFrom(q); copy.transform(transform); - if (copy.isShade()) { - copy.setCalculatedDiffuse(); - } + copy.multShade(); list.add(copy.toBakedBlock()); } cached.put(to, list); diff --git a/common/buildcraft/transport/client/model/plug/PlugGateBaker.java b/common/buildcraft/transport/client/model/plug/PlugGateBaker.java index af224ab63d..e28a1d9685 100644 --- a/common/buildcraft/transport/client/model/plug/PlugGateBaker.java +++ b/common/buildcraft/transport/client/model/plug/PlugGateBaker.java @@ -34,7 +34,7 @@ public List bake(KeyPlugGate key) { for (MutableQuad q : quads) { MutableQuad c = new MutableQuad(q); c.transform(transform); - c.setCalculatedDiffuse(); + c.multShade(); list.add(c.toBakedBlock()); } cached.put(key, list); diff --git a/common/buildcraft/transport/client/render/PipeFlowRendererItems.java b/common/buildcraft/transport/client/render/PipeFlowRendererItems.java index 544e86f80e..af5e0bf47c 100644 --- a/common/buildcraft/transport/client/render/PipeFlowRendererItems.java +++ b/common/buildcraft/transport/client/render/PipeFlowRendererItems.java @@ -78,7 +78,7 @@ public void render(PipeFlowItems flow, double x, double y, double z, float parti for (MutableQuad q : COLOURED_QUADS) { MutableQuad q2 = new MutableQuad(q); q2.lighti(lightc); - q2.multColourd(r / 255.0, g / 255.0, b / 255.0, 1); + q2.multColouri(r, g, b, 255); q2.render(vb); } vb.setTranslation(0, 0, 0); diff --git a/common/buildcraft/transport/client/render/PipeFlowRendererPower.java b/common/buildcraft/transport/client/render/PipeFlowRendererPower.java index c4e15a4579..95015fd2e4 100644 --- a/common/buildcraft/transport/client/render/PipeFlowRendererPower.java +++ b/common/buildcraft/transport/client/render/PipeFlowRendererPower.java @@ -1,16 +1,49 @@ package buildcraft.transport.client.render; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.VertexBuffer; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.Vec3d; import buildcraft.api.transport.neptune.IPipeFlowRenderer; +import buildcraft.core.client.BuildCraftLaserManager; +import buildcraft.lib.client.render.laser.LaserData_BC8; +import buildcraft.lib.client.render.laser.LaserRenderer_BC8; +import buildcraft.lib.misc.SpriteUtil; +import buildcraft.lib.misc.VecUtil; import buildcraft.transport.pipe.flow.PipeFlowPower; +import buildcraft.transport.pipe.flow.PipeFlowPower.PowerConnection; public enum PipeFlowRendererPower implements IPipeFlowRenderer { INSTANCE; @Override public void render(PipeFlowPower flow, double x, double y, double z, float partialTicks, VertexBuffer vb) { + GlStateManager.pushMatrix(); + GlStateManager.translate(x, y, z); + RenderHelper.disableStandardItemLighting(); + SpriteUtil.bindBlockTextureMap(); + Vec3d center = VecUtil.VEC_HALF; + for (EnumFacing face : EnumFacing.VALUES) { + PowerConnection type = flow.getConnectionType(face); + Vec3d start = VecUtil.offset(center, face, 0.5); + Vec3d end = center;//VecUtil.offset(center, face, 0); + + if (type == PowerConnection.REQUEST) { + Vec3d t = start; + start = end; + end = t; + } else if (type == PowerConnection.SENDER) { + // Everything is already correct + } else { + continue; + } + LaserData_BC8 data = new LaserData_BC8(BuildCraftLaserManager.POWER_LOW, start, end, 1 / 16.0, false, false, 15); + LaserRenderer_BC8.renderLaserStatic(data); + } + GlStateManager.popMatrix(); } } diff --git a/common/buildcraft/transport/client/render/PipeWireRenderer.java b/common/buildcraft/transport/client/render/PipeWireRenderer.java index fcb0119bfa..33bd4c4e6b 100644 --- a/common/buildcraft/transport/client/render/PipeWireRenderer.java +++ b/common/buildcraft/transport/client/render/PipeWireRenderer.java @@ -63,9 +63,9 @@ private static MutableQuad[] getQuads(EnumWirePart part) { MutableQuad[] quads = new MutableQuad[6]; Tuple3f center = new Point3f(// - 0.5f + (part.x.getOffset() * 4.51f / 16f),// - 0.5f + (part.y.getOffset() * 4.51f / 16f),// - 0.5f + (part.z.getOffset() * 4.51f / 16f) // + 0.5f + (part.x.getOffset() * 4.51f / 16f),// + 0.5f + (part.y.getOffset() * 4.51f / 16f),// + 0.5f + (part.z.getOffset() * 4.51f / 16f) // ); Tuple3f radius = new Point3f(1 / 32f, 1 / 32f, 1 / 32f); UvFaceData uvs = new UvFaceData(); @@ -101,29 +101,29 @@ private static MutableQuad[] getQuads(EnumWireBetween between) { double cL = 0.5f - 4.51f / 16f; double cU = 0.5f + 4.51f / 16f; center = new Vec3d(// - ax ? 0.5f : (between.xy ? cU : cL),// - ay ? 0.5f : ((ax ? between.xy : between.yz) ? cU : cL),// - az ? 0.5f : (between.yz ? cU : cL) // + ax ? 0.5f : (between.xy ? cU : cL),// + ay ? 0.5f : ((ax ? between.xy : between.yz) ? cU : cL),// + az ? 0.5f : (between.yz ? cU : cL) // ); double rC = 4.01f / 16f; double rN = 1f / 16f / 2; radius = new Vec3d(// - ax ? rC : rN,// - ay ? rC : rN,// - az ? rC : rN // + ax ? rC : rN,// + ay ? rC : rN,// + az ? rC : rN // ); } else {// we are a connection double cL = (8 - 4.51) / 16; double cU = (8 + 4.51) / 16; radius = new Vec3d(// - ax ? 2.99 / 32 : 1 / 32.0,// - ay ? 2.99 / 32 : 1 / 32.0,// - az ? 2.99 / 32 : 1 / 32.0 // + ax ? 2.99 / 32 : 1 / 32.0,// + ay ? 2.99 / 32 : 1 / 32.0,// + az ? 2.99 / 32 : 1 / 32.0 // ); center = new Vec3d(// - ax ? (0.5 + 6.505 / 16 * between.to.getFrontOffsetX()) : (between.xy ? cU : cL),// - ay ? (0.5 + 6.505 / 16 * between.to.getFrontOffsetY()) : ((ax ? between.xy : between.yz) ? cU : cL),// - az ? (0.5 + 6.505 / 16 * between.to.getFrontOffsetZ()) : (between.yz ? cU : cL) // + ax ? (0.5 + 6.505 / 16 * between.to.getFrontOffsetX()) : (between.xy ? cU : cL),// + ay ? (0.5 + 6.505 / 16 * between.to.getFrontOffsetY()) : ((ax ? between.xy : between.yz) ? cU : cL),// + az ? (0.5 + 6.505 / 16 * between.to.getFrontOffsetZ()) : (between.yz ? cU : cL) // ); } @@ -187,19 +187,24 @@ private static void renderQuads(MutableQuad[] quads, ISprite sprite, int level) VertexBuffer vb = tessellator.getBuffer(); vb.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX); - float texOffset = (level & 0xF) / 16f; + float vOffset = (level & 0xF) / 16f; for (MutableQuad q : quads) { - for (int i = 0; i < 4; i++) { - MutableVertex v = q.getVertex(i); - v.renderPosition(vb); - vb.tex(sprite.getInterpU(v.tex_u), sprite.getInterpV(v.tex_v + texOffset)); - vb.endVertex(); - } + renderVertex(vb, q.vertex_0, sprite, vOffset); + renderVertex(vb, q.vertex_1, sprite, vOffset); + renderVertex(vb, q.vertex_2, sprite, vOffset); + renderVertex(vb, q.vertex_3, sprite, vOffset); } - tessellator.draw(); } + private static void renderVertex(VertexBuffer vb, MutableVertex vertex, ISprite sprite, float vOffset) { + vertex.renderPosition(vb); + double u = sprite.getInterpU(vertex.tex_u); + double v = sprite.getInterpV(vertex.tex_v + vOffset); + vb.tex(u, v); + vb.endVertex(); + } + private static int compileQuads(MutableQuad[] quads, EnumDyeColor colour, boolean isOn) { int index = GlStateManager.glGenLists(1); GlStateManager.glNewList(index, GL11.GL_COMPILE); diff --git a/common/buildcraft/transport/client/render/RenderPipeHolder.java b/common/buildcraft/transport/client/render/RenderPipeHolder.java index 16bcd2e1a6..0e6daec14d 100644 --- a/common/buildcraft/transport/client/render/RenderPipeHolder.java +++ b/common/buildcraft/transport/client/render/RenderPipeHolder.java @@ -13,6 +13,7 @@ import buildcraft.transport.pipe.Pipe; import buildcraft.transport.pipe.flow.PipeFlowFluids; import buildcraft.transport.pipe.flow.PipeFlowItems; +import buildcraft.transport.pipe.flow.PipeFlowPower; import buildcraft.transport.tile.TilePipeHolder; public class RenderPipeHolder extends FastTESR { @@ -58,6 +59,8 @@ private void renderContents(TilePipeHolder pipe, double x, double y, double z, f PipeFlowRendererItems.INSTANCE.render((PipeFlowItems) p.flow, x, y, z, partialTicks, vb); } else if (p.flow instanceof PipeFlowFluids) { PipeFlowRendererFluids.INSTANCE.render((PipeFlowFluids) p.flow, x, y, z, partialTicks, vb); + } else if (p.flow instanceof PipeFlowPower) { + PipeFlowRendererPower.INSTANCE.render((PipeFlowPower) p.flow, x, y, z, partialTicks, vb); } } } diff --git a/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java b/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java index dbd0644289..94d69e65a5 100644 --- a/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java +++ b/common/buildcraft/transport/pipe/flow/PipeFlowFluids.java @@ -129,14 +129,6 @@ public boolean canConnect(EnumFacing face, TileEntity oTile) { return oTile.hasCapability(CapUtil.CAP_FLUIDS, face.getOpposite()); } - @Override - public boolean hasCapability(Capability capability, EnumFacing facing) { - if (capability == CapUtil.CAP_FLUIDS) { - return true; - } - return super.hasCapability(capability, facing); - } - @Override public T getCapability(Capability capability, EnumFacing facing) { if (capability == CapUtil.CAP_FLUIDS) { diff --git a/common/buildcraft/transport/pipe/flow/PipeFlowPower.java b/common/buildcraft/transport/pipe/flow/PipeFlowPower.java index 1d91efaf48..5a931ac907 100644 --- a/common/buildcraft/transport/pipe/flow/PipeFlowPower.java +++ b/common/buildcraft/transport/pipe/flow/PipeFlowPower.java @@ -1,14 +1,50 @@ package buildcraft.transport.pipe.flow; +import java.io.IOException; +import java.util.EnumMap; +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.PacketBuffer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.RayTraceResult; + +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import buildcraft.api.core.EnumPipePart; +import buildcraft.api.mj.IMjConnector; +import buildcraft.api.mj.IMjPassiveProvider; +import buildcraft.api.mj.IMjReceiver; import buildcraft.api.mj.MjAPI; +import buildcraft.api.tiles.IDebuggable; +import buildcraft.api.transport.PipeEventPower; +import buildcraft.api.transport.neptune.IFlowPower; import buildcraft.api.transport.neptune.IPipe; +import buildcraft.api.transport.neptune.IPipe.ConnectedType; import buildcraft.api.transport.neptune.PipeFlow; -public class PipeFlowPower extends PipeFlow { +import buildcraft.lib.engine.TileEngineBase_BC8; +import buildcraft.lib.misc.MathUtil; + +public class PipeFlowPower extends PipeFlow implements IFlowPower, IDebuggable { + public static final long ABSOLUTE_MAX_POWER = MjAPI.MJ * 100;// TEMP! + + long maxPower = ABSOLUTE_MAX_POWER; + boolean isReceiver = false; + final EnumMap sections = createSections(); + + private EnumMap createSections() { + EnumMap map = new EnumMap<>(EnumFacing.class); + for (EnumFacing face : EnumFacing.VALUES) { + map.put(face, new Section(face)); + } + return map; + } + public PipeFlowPower(IPipe pipe) { super(pipe); } @@ -17,6 +53,23 @@ public PipeFlowPower(IPipe pipe, NBTTagCompound nbt) { super(pipe, nbt); } + @Override + public NBTTagCompound writeToNbt() { + NBTTagCompound nbt = super.writeToNbt(); + + return nbt; + } + + @Override + public void readPayload(int id, PacketBuffer buffer, Side side) throws IOException { + super.readPayload(id, buffer, side); + } + + @Override + public void writePayload(int id, PacketBuffer buffer, Side side) { + super.writePayload(id, buffer, side); + } + @Override public boolean canConnect(EnumFacing face, PipeFlow other) { return other instanceof PipeFlowPower; @@ -24,6 +77,192 @@ public boolean canConnect(EnumFacing face, PipeFlow other) { @Override public boolean canConnect(EnumFacing face, TileEntity oTile) { - return oTile.hasCapability(MjAPI.CAP_RECEIVER, face.getOpposite()); + if (isReceiver) { + IMjPassiveProvider provider = oTile.getCapability(MjAPI.CAP_PASSIVE_PROVIDER, face.getOpposite()); + if (provider != null) return true; + } + IMjConnector reciever = oTile.getCapability(MjAPI.CAP_CONNECTOR, face.getOpposite()); + if (reciever == null) return false; + return reciever.canConnect(sections.get(face)); + } + + @Override + public void reconfigure() { + PipeEventPower.Configure configure = new PipeEventPower.Configure(pipe.getHolder(), this); + configure.setMaxPower(maxPower); + configure.setReceiver(isReceiver); + pipe.getHolder().fireEvent(configure); + maxPower = MathUtil.clamp(configure.getMaxPower(), MjAPI.MJ, ABSOLUTE_MAX_POWER); + isReceiver = configure.isReceiver(); + } + + @Override + public long tryExtractPower(long maxExtracted, EnumFacing from) { + if (!isReceiver) return 0; + TileEntity tile = pipe.getConnectedTile(from); + if (tile == null) return 0; + IMjPassiveProvider reciever = tile.getCapability(MjAPI.CAP_PASSIVE_PROVIDER, from.getOpposite()); + if (reciever == null) return 0; + + // TODO! + return 0; + } + + @Override + public void onTick() { + for (EnumFacing side : EnumFacing.VALUES) { + Section s = sections.get(side); + if (!pipe.isConnected(side)) { + s.connection = PowerConnection.DEAD_END; + continue; + } + ConnectedType type = pipe.getConnectedType(side); + if (type == ConnectedType.PIPE) { + IPipe oPipe = pipe.getConnectedPipe(side); + if (oPipe != null && oPipe.getFlow() instanceof PipeFlowPower) { + PipeFlowPower oPower = (PipeFlowPower) oPipe.getFlow(); + s.connection = oPower.getConnectionTypeExcluding(side.getOpposite(), getConnectionTypeExcluding(side, null)); + } else { + s.connection = PowerConnection.DEAD_END; + } + } else if (type == ConnectedType.TILE) { + TileEntity tile = pipe.getConnectedTile(side); + if (tile != null) { + s.connection = (tile instanceof TileEngineBase_BC8) ? PowerConnection.SENDER : PowerConnection.REQUEST;// TEMP! + } else { + s.connection = PowerConnection.DEAD_END; + } + } else { + s.connection = PowerConnection.DEAD_END; + } + } + } + + private PowerConnection getConnectionTypeExcluding(EnumFacing ignore, PowerConnection from) { + PowerConnection current = PowerConnection.DEAD_END; + for (EnumFacing face : EnumFacing.VALUES) { + PowerConnection c = sections.get(face).connection; + if (face == ignore) continue; + switch (c) { + case UNKNOWN: + return PowerConnection.UNKNOWN; + case SENDER: + case REQUEST: { + PowerConnection other = c == PowerConnection.SENDER ? PowerConnection.REQUEST : PowerConnection.SENDER; + if (current == other) { + if (from == PowerConnection.REQUEST) { + return PowerConnection.SENDER; + } else if (from == PowerConnection.SENDER) { + return PowerConnection.REQUEST; + } else { + return PowerConnection.UNKNOWN; + } + } else { + current = c; + break; + } + } + case DEAD_END: + break; + default: + throw new IllegalArgumentException("Unknown PowerConnection " + c); + } + } + return current; + } + + @Override + public boolean onFlowActivate(EntityPlayer player, RayTraceResult trace, float hitX, float hitY, float hitZ, EnumPipePart part) { + return super.onFlowActivate(player, trace, hitX, hitY, hitZ, part); + } + + @Override + public T getCapability(Capability capability, EnumFacing facing) { + if (facing == null || capability != MjAPI.CAP_CONNECTOR || capability != MjAPI.CAP_RECEIVER) { + return null; + } + return (T) sections.get(facing); + } + + @Override + @SideOnly(Side.CLIENT) + public void getDebugInfo(List left, List right, EnumFacing side) { + left.add("Connections:"); + for (EnumFacing face : EnumFacing.VALUES) { + if (!pipe.isConnected(face)) continue; + Section section = sections.get(face); + left.add(" " + face + " = " + section.connection); + } + } + + @SideOnly(Side.CLIENT) + public PowerConnection getConnectionType(EnumFacing face) { + return sections.get(face).connection; + } + + public class Section implements IMjReceiver { + public final EnumFacing side; + + long actualMaxPower = 0; + long stored; + long maxThisTick = maxPower; + // long strength; + // long maxStrength; + PowerConnection connection = PowerConnection.UNKNOWN; + + public Section(EnumFacing side) { + this.side = side; + } + + void onTick() { + actualMaxPower = pipe.isConnected(side) ? maxPower : 0; + + // maxStrength /= 2; + // maxStrength = Math.max(maxStrength, strength); + // strength = 0; + + maxThisTick = actualMaxPower - stored; + } + + @Override + public boolean canConnect(IMjConnector other) { + return true; + } + + @Override + public long getPowerRequested() { + return maxThisTick; + } + + long receivePowerInternal(long sent) { + return sent; + } + + @Override + public long receivePower(long microJoules, boolean simulate) { + // if (!isReceiver) { + return microJoules; + // } + // long toAccept = Math.max(microJoules, maxThisTick); + // toAccept = Math.min(toAccept, actualMaxPower - stored); + // if (toAccept <= 0) { + // return microJoules; + // } + + // if (!simulate) { + // strength += toAccept; + // maxThisTick -= toAccept; + // stored += toAccept; + // } + + // return microJoules - toAccept; + } + } + + public enum PowerConnection { + UNKNOWN, + DEAD_END, + REQUEST, + SENDER; } } diff --git a/src/test/java/buildcraft/test/lib/nbt/NbtSquisherTester.java b/src/test/java/buildcraft/test/lib/nbt/NbtSquisherTester.java index efe04bedfe..b6eef6a360 100644 --- a/src/test/java/buildcraft/test/lib/nbt/NbtSquisherTester.java +++ b/src/test/java/buildcraft/test/lib/nbt/NbtSquisherTester.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; +import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -15,22 +16,20 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagFloat; import net.minecraft.nbt.NBTTagList; +import net.minecraft.profiler.Profiler; -import buildcraft.lib.nbt.NBTSquishDebugging; import buildcraft.lib.nbt.NbtSquisher; public class NbtSquisherTester { - private final NBTTagCompound nbt = genNbt(); + private final NBTTagCompound nbt = genNbt(64 * 64 * 64); + private final NBTTagCompound nbtSmall = genNbt(10); @Test public void testSimpleNBT() throws IOException { - NBTSquishDebugging.debug = true; - test(nbt); - NBTSquishDebugging.debug = false; - test(nbt); + test(true, nbt); } - private static NBTTagCompound genNbt() { + private static NBTTagCompound genNbt(int bptSize) { Random rand = new Random(0x517123); NBTTagCompound nbt = new NBTTagCompound(); @@ -63,60 +62,64 @@ private static NBTTagCompound genNbt() { nbt.setTag("complex|compound", compound); - NBTTagCompound air = new NBTTagCompound(); - air.setString("block", "minecraft:air"); + String[] names = { "minecraft:air", "minecraft:log", "minecraft:torch", "minecraft:stone", "minecraft:fence" }; + int[] metas = { 1, 16, 5, 7, 4 }; - NBTTagCompound diorite = new NBTTagCompound(); - diorite.setString("block", "minecraft:stone"); - diorite.setByte("meta", (byte) 4); + NBTTagCompound[] blocks = new NBTTagCompound[sum(metas)]; - NBTTagCompound andersite = new NBTTagCompound(); - andersite.setString("block", "minecraft:stone"); - andersite.setByte("meta", (byte) 3); - - NBTTagCompound cobblestone = new NBTTagCompound(); - cobblestone.setString("block", "minecraft:cobblestone"); - - NBTTagCompound torch = new NBTTagCompound(); - torch.setString("block", "minecraft:torch"); - torch.setByte("meta", (byte) 0); - - NBTTagCompound itemApple = new NBTTagCompound(); - itemApple.setString("id", "minecraft:apple"); - itemApple.setByte("Count", (byte) 12); - itemApple.setShort("Damage", (short) 0); - - NBTTagCompound chest = new NBTTagCompound(); - chest.setString("block", "minecraft:chest"); - chest.setByte("meta", (byte) 2); - NBTTagList chestItems = new NBTTagList(); - chestItems.appendTag(itemApple); + int block = 0; + for (int b = 0; b < names.length; b++) { + NBTTagCompound blockNbt = new NBTTagCompound(); + blockNbt.setString("id", names[b]); + blocks[block++] = blockNbt.copy(); + for (int m = 1; m < metas[b]; m++) { + blockNbt.setByte("meta", (byte) m); + blocks[block++] = blockNbt.copy(); + } + } - chest.setTag("items", chestItems); + NBTTagCompound air = blocks[0]; NBTTagList bpt = new NBTTagList(); - for (int i = 0; i < 64 * 64 * 64; i++) { + int chests = 0; + for (int i = 0; i < bptSize; i++) { double r = rand.nextDouble(); final NBTTagCompound toUse; - if (r < 0.8) toUse = air; - else if (r < 0.875) toUse = andersite; - else if (r < 0.93) toUse = cobblestone; - else if (r < 0.9995) toUse = torch; - else if (r < 0.9999) toUse = chest; - else toUse = genRandomChest(rand); + if (r < 0.4) { + toUse = air; + } else if (r < 0.9999) { + toUse = blocks[rand.nextInt(blocks.length)]; + } else { + toUse = genRandomChest(rand); + chests++; + } bpt.appendTag(toUse); } + System.out.println(chests + " random chests in a " + Math.cbrt(bptSize) + " bpt"); nbt.setTag("bpt", bpt); return nbt; } - public static byte[] test(NBTTagCompound nbt) throws IOException { + private static int sum(int[] values) { + int total = 0; + for (int i : values) { + total += i; + } + return total; + } + + public static long[] test(boolean print, NBTTagCompound nbt) throws IOException { + long[] times = new long[4]; + Stopwatch watch = Stopwatch.createStarted(); byte[] bytes = NbtSquisher.squishVanillaUncompressed(nbt); watch.stop(); - printBytesData("vanilla [un] took " + padMilliseconds(watch.elapsed(TimeUnit.MILLISECONDS), 8), bytes); + if (print) { + times[0] = watch.elapsed(TimeUnit.MILLISECONDS); + printBytesData("vanilla [un] took " + padMilliseconds(times[0], 8), bytes); + } watch.reset(); NBTTagCompound to = NbtSquisher.expand(bytes.clone()); @@ -125,26 +128,41 @@ public static byte[] test(NBTTagCompound nbt) throws IOException { watch.start(); bytes = NbtSquisher.squishVanilla(nbt); watch.stop(); - printBytesData("vanilla [cp] took " + padMilliseconds(watch.elapsed(TimeUnit.MILLISECONDS), 8), bytes); + if (print) { + times[1] = watch.elapsed(TimeUnit.MILLISECONDS); + printBytesData("vanilla [cp] took " + padMilliseconds(times[1], 8), bytes); + } watch.reset(); to = NbtSquisher.expand(bytes.clone()); checkEquality(nbt, to); - return bytes; - } - - private static void testBcOnly(NBTTagCompound nbt) { - Stopwatch watch = Stopwatch.createStarted(); - byte[] bytes = NbtSquisher.squishBuildCraftV1Uncompressed(nbt); + watch.start(); + bytes = NbtSquisher.squishBuildCraftV1Uncompressed(nbt); watch.stop(); - printBytesData("buildcraft[un] took " + padMilliseconds(watch.elapsed(TimeUnit.MILLISECONDS), 8), bytes); + if (print) { + times[2] = watch.elapsed(TimeUnit.MILLISECONDS); + printBytesData("buildcraft[un] took " + padMilliseconds(times[2], 8), bytes); + } watch.reset(); + NbtSquisher.debug = false; + + to = NbtSquisher.expand(bytes.clone()); + checkEquality(nbt, to); + watch.start(); bytes = NbtSquisher.squishBuildCraftV1(nbt); watch.stop(); - printBytesData("buildcraft[cp] took " + padMilliseconds(watch.elapsed(TimeUnit.MILLISECONDS), 8), bytes); + if (print) { + times[3] = watch.elapsed(TimeUnit.MILLISECONDS); + printBytesData("buildcraft[cp] took " + padMilliseconds(times[3], 8), bytes); + } + + to = NbtSquisher.expand(bytes.clone()); + checkEquality(nbt, to); + + return times; } public static void checkEquality(NBTTagCompound from, NBTTagCompound to) { @@ -216,11 +234,9 @@ private static NBTTagCompound genRandomChest(Random rand) { NBTTagList chestItems = new NBTTagList(); NBTTagCompound itemB = genRandomItem(rand); - int num = rand.nextInt(3) + rand.nextInt(3) - 3; - num += 5; - num *= 6; + int num = rand.nextInt(3) + 2; for (int i = 0; i < num; i++) { - if (rand.nextInt(6) == 0) { + if (rand.nextInt(6) > 0) { chestItems.appendTag(itemB); } else { chestItems.appendTag(genRandomItem(rand)); @@ -275,12 +291,80 @@ private static void printByte(byte[] bytes, int i) { } public static void main(String[] args) throws IOException { + System.in.read(); NbtSquisherTester tester = new NbtSquisherTester(); + Stopwatch watch = Stopwatch.createStarted(); + for (int i = 1; i <= 100_000; i++) { + test(false, tester.nbtSmall); + if (i % 10_000 == 0) { + watch.stop(); + System.out.println("Finished test " + i + " in " + watch.elapsed(TimeUnit.MILLISECONDS) + "ms"); + watch.reset().start(); + } + } + watch.reset(); + + NbtSquisher.profiler.profilingEnabled = true; + NbtSquisher.profiler.startSection("root"); + + final int times = 100; + long[][] all = new long[times][]; + + System.in.read(); + NbtSquisher.debug = true; for (int i = 0; i < 100; i++) { - System.in.read(); System.out.println("Starting test " + (i + 1)); - testBcOnly(tester.nbt); + all[i] = test(true, tester.nbt); System.out.println("Finished test " + (i + 1)); + NbtSquisher.debug = false; + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + return; + } + } + String[] types = { "vanilla [un]", "vanilla [cp]", "buildcraft[un]", "buildcraft[cp]" }; + for (int i = 0; i < 4; i++) { + long total = 0; + for (int j = 20; j < times; j++) + total += all[j][i]; + long average = total * 100 / (times - 20); + System.out.println(types[i] + " took (on average) " + (average / 100) + "." + (average % 100) + "ms"); + } + + NbtSquisher.profiler.endSection(); + writeProfilerResults(0, "root.write", NbtSquisher.profiler); + } + + private static void writeProfilerResults(int indent, String sectionName, Profiler profiler) { + List list = profiler.getProfilingData(sectionName); + + if (list != null && list.size() >= 3) { + for (int i = 1; i < list.size(); ++i) { + Profiler.Result profiler$result = list.get(i); + StringBuilder builder = new StringBuilder(); + builder.append(String.format("[%02d] ", indent)); + + for (int j = 0; j < indent; ++j) { + builder.append("| "); + } + + builder.append(profiler$result.profilerName); + builder.append(" - "); + builder.append(String.format("%.2f", profiler$result.usePercentage)); + builder.append("%/"); + builder.append(String.format("%.2f", profiler$result.totalUsePercentage)); + System.out.println(builder.toString()); + + if (!"unspecified".equals(profiler$result.profilerName)) { + try { + writeProfilerResults(indent + 1, sectionName + "." + profiler$result.profilerName, profiler); + } catch (Exception exception) { + System.out.println("[[ EXCEPTION " + exception + " ]]"); + } + } + } } } } diff --git a/src_old_license/buildcraft/core/lib/client/render/RenderResizableCuboid.java b/src_old_license/buildcraft/core/lib/client/render/RenderResizableCuboid.java index e7fa6e92c7..3e7ee6308f 100644 --- a/src_old_license/buildcraft/core/lib/client/render/RenderResizableCuboid.java +++ b/src_old_license/buildcraft/core/lib/client/render/RenderResizableCuboid.java @@ -411,18 +411,18 @@ private static void bakeCuboidFace(List quads, EntityResizableCuboi if (flip ? out : in) { MutableQuad mutable = new MutableQuad(-1, face); - bakePoint(mutable.getVertex(0), face, u, v, otherMoved, ri, true, false); - bakePoint(mutable.getVertex(1), face, u, v, otherMoved, ri, true, true); - bakePoint(mutable.getVertex(2), face, u, v, otherMoved, ri, false, true); - bakePoint(mutable.getVertex(3), face, u, v, otherMoved, ri, false, false); + bakePoint(mutable.vertex_0, face, u, v, otherMoved, ri, true, false); + bakePoint(mutable.vertex_1, face, u, v, otherMoved, ri, true, true); + bakePoint(mutable.vertex_2, face, u, v, otherMoved, ri, false, true); + bakePoint(mutable.vertex_3, face, u, v, otherMoved, ri, false, false); quads.add(mutable); } if (flip ? in : out) { MutableQuad mutable = new MutableQuad(-1, face); - bakePoint(mutable.getVertex(0), opposite, u, v, otherMoved, ri, false, false); - bakePoint(mutable.getVertex(1), opposite, u, v, otherMoved, ri, false, true); - bakePoint(mutable.getVertex(2), opposite, u, v, otherMoved, ri, true, true); - bakePoint(mutable.getVertex(3), opposite, u, v, otherMoved, ri, true, false); + bakePoint(mutable.vertex_0, opposite, u, v, otherMoved, ri, false, false); + bakePoint(mutable.vertex_1, opposite, u, v, otherMoved, ri, false, true); + bakePoint(mutable.vertex_2, opposite, u, v, otherMoved, ri, true, true); + bakePoint(mutable.vertex_3, opposite, u, v, otherMoved, ri, true, false); quads.add(mutable); } }