a lot of stuff idk

This commit is contained in:
DrMangoTea
2025-02-26 19:28:51 +01:00
parent 088f145afe
commit 212ec033b1
786 changed files with 28991 additions and 29133 deletions

View File

@@ -4,6 +4,7 @@ import com.drmangotea.tfmg.base.TFMGContraptions;
import com.drmangotea.tfmg.base.TFMGCreativeTabs;
import com.drmangotea.tfmg.base.TFMGRegistrate;
import com.drmangotea.tfmg.content.electricity.base.ElectricNetworkManager;
import com.drmangotea.tfmg.content.engines.fuels.BaseFuelTypes;
import com.drmangotea.tfmg.content.items.weapons.explosives.thermite_grenades.fire.TFMGColoredFires;
import com.drmangotea.tfmg.content.machinery.oil_processing.pumpjack.pumpjack.base.DepositManager;
import com.drmangotea.tfmg.datagen.TFMGDatagen;
@@ -92,7 +93,7 @@ public class TFMG {
TFMGFluidInteractions.registerFluidInteractions();
event.enqueueWork(() -> {
BaseFuelTypes.register();
registerHeater(TFMGBlocks.FIREBOX.get(), (level, pos, state) -> {
BlazeBurnerBlock.HeatLevel value = state.getValue(BlazeBurnerBlock.HEAT_LEVEL);
if (value == BlazeBurnerBlock.HeatLevel.NONE) {

View File

@@ -8,18 +8,24 @@ import com.drmangotea.tfmg.content.decoration.doors.TFMGSlidingDoorBlock;
import com.drmangotea.tfmg.content.decoration.encased.TFMGEncasedCogwheelBlock;
import com.drmangotea.tfmg.content.decoration.encased.TFMGEncasedShaftBlock;
import com.drmangotea.tfmg.content.decoration.flywheels.TFMGFlywheelBlock;
import com.drmangotea.tfmg.content.electricity.connection.copycat_cable.CopycatCableBlock;
import com.drmangotea.tfmg.content.electricity.lights.neon_tube.NeonTubeBlock;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.simibubi.create.AllBlocks;
import com.simibubi.create.AllTags;
import com.simibubi.create.content.contraptions.behaviour.DoorMovingInteraction;
import com.simibubi.create.content.decoration.encasing.EncasedCTBehaviour;
import com.simibubi.create.content.decoration.girder.GirderBlock;
import com.simibubi.create.content.decoration.slidingDoor.SlidingDoorMovementBehaviour;
import com.simibubi.create.content.kinetics.BlockStressDefaults;
import com.simibubi.create.content.kinetics.base.RotatedPillarKineticBlock;
import com.simibubi.create.content.kinetics.simpleRelays.encased.EncasedCogCTBehaviour;
import com.simibubi.create.foundation.block.connected.CTSpriteShiftEntry;
import com.simibubi.create.foundation.data.*;
import com.simibubi.create.foundation.utility.Iterate;
import com.tterrag.registrate.builders.BlockBuilder;
import com.tterrag.registrate.providers.DataGenContext;
import com.tterrag.registrate.providers.RegistrateBlockstateProvider;
import com.tterrag.registrate.util.DataIngredient;
import com.tterrag.registrate.util.entry.BlockEntry;
import com.tterrag.registrate.util.nullness.NonNullUnaryOperator;
@@ -32,7 +38,9 @@ import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraftforge.client.model.generators.ModelFile;
import net.minecraftforge.client.model.generators.MultiPartBlockStateBuilder;
import java.nio.channels.Pipe;
import java.util.function.Supplier;
import static com.drmangotea.tfmg.TFMG.REGISTRATE;
@@ -70,15 +78,44 @@ public class TFMGBuilderTransformers {
.build();
}
public static <B extends Block, P> NonNullUnaryOperator<BlockBuilder<B, P>> surfaceScanner() {
return b -> b.initialProperties(SharedProperties::softMetal)
.blockstate((c, p) -> p.horizontalBlock(c.get(), p.models()
.getExistingFile(p.modLoc("block/surface_scanner/block"))))
.addLayer(() -> RenderType::cutoutMipped)
.item()
.transform(ModelGen.customItemModel("surface_scanner", "item"));
public static void generateNeonTubeBlockState(DataGenContext<Block, NeonTubeBlock> c, RegistrateBlockstateProvider p) {
MultiPartBlockStateBuilder builder = p.getMultipartBuilder(c.get());
builder.part()
.modelFile(AssetLookup.partialBaseModel(c, p, "center"))
.addModel()
.end();
builder.part().modelFile(AssetLookup.partialBaseModel(c, p, "north"))
.addModel()
.condition(PipeBlock.NORTH, true)
.end();
builder.part().modelFile(AssetLookup.partialBaseModel(c, p, "south"))
.addModel()
.condition(PipeBlock.SOUTH, true)
.end();
builder.part().modelFile(AssetLookup.partialBaseModel(c, p, "west"))
.addModel()
.condition(PipeBlock.WEST, true)
.end();
builder.part().modelFile(AssetLookup.partialBaseModel(c, p, "east"))
.addModel()
.condition(PipeBlock.EAST, true)
.end();
builder.part().modelFile(AssetLookup.partialBaseModel(c, p, "top"))
.addModel()
.condition(PipeBlock.UP, true)
.end();
builder.part().modelFile(AssetLookup.partialBaseModel(c, p, "bottom"))
.addModel()
.condition(PipeBlock.DOWN, true)
.end();
}
public static <B extends TFMGEncasedShaftBlock, P> NonNullUnaryOperator<BlockBuilder<B, P>> encasedShaft(String casing,
Supplier<CTSpriteShiftEntry> casingShift) {
return builder -> encasedBase(builder, AllBlocks.SHAFT::get)
@@ -147,19 +184,19 @@ public class TFMGBuilderTransformers {
.transform(BlockStressDefaults.setNoImpact())
.loot((p, lb) -> p.dropOther(lb, drop.get()));
}
//public static <B extends CopycatCableBlock, P> NonNullUnaryOperator<BlockBuilder<B, P>> copycatCable() {
// return b -> b.initialProperties(SharedProperties::softMetal)
// .blockstate((c, p) -> p.simpleBlock(c.get(), p.models()
// .getExistingFile(p.mcLoc("air"))))
// .initialProperties(SharedProperties::softMetal)
// .properties(BlockBehaviour.Properties::noOcclusion)
// .addLayer(() -> RenderType::solid)
// .addLayer(() -> RenderType::cutout)
// .addLayer(() -> RenderType::cutoutMipped)
// // .addLayer(() -> RenderType::translucent)
// .color(() -> CopycatCableBlock::wrappedColor)
// .transform(TagGen.axeOrPickaxe());
//}
public static <B extends CopycatCableBlock, P> NonNullUnaryOperator<BlockBuilder<B, P>> copycatCable() {
return b -> b.initialProperties(SharedProperties::softMetal)
.blockstate((c, p) -> p.simpleBlock(c.get(), p.models()
.getExistingFile(p.mcLoc("air"))))
.initialProperties(SharedProperties::softMetal)
.properties(BlockBehaviour.Properties::noOcclusion)
.addLayer(() -> RenderType::solid)
.addLayer(() -> RenderType::cutout)
.addLayer(() -> RenderType::cutoutMipped)
// .addLayer(() -> RenderType::translucent)
.color(() -> CopycatCableBlock::wrappedColor)
.transform(TagGen.axeOrPickaxe());
}
///////////////
public static BlockEntry<TFMGFlywheelBlock> flywheel(String name) {

View File

@@ -8,6 +8,7 @@ import com.simibubi.create.content.processing.sequenced.SequencedAssemblyItem;
import com.simibubi.create.foundation.data.CreateRegistrate;
import com.tterrag.registrate.util.entry.RegistryEntry;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
@@ -40,6 +41,7 @@ public class TFMGCreativeTabs {
.build());
public static void addCreative(BuildCreativeModeTabContentsEvent event) {
if (event.getTab() == TFMG_MAIN.get()){
event.acceptAll(customAdditions());
for(RegistryEntry<Item> item : REGISTRATE.getAll(Registries.ITEM)){
if(!CreateRegistrate.isInCreativeTab(item,TFMG_MAIN))
@@ -49,7 +51,6 @@ public class TFMGCreativeTabs {
if(item.get() instanceof SequencedAssemblyItem)
continue;
if(item.get() instanceof SpoolItem&&!item.is(TFMGItems.EMPTY_SPOOL.get())){
ItemStack spool = item.get().getDefaultInstance();
spool.getOrCreateTag().putInt("Amount", 1000);
event.accept(spool);
@@ -71,6 +72,7 @@ public class TFMGCreativeTabs {
event.accept(item);
}
}
}
public static void register(IEventBus modEventBus){
@@ -81,6 +83,41 @@ public class TFMGCreativeTabs {
List<RegistryEntry<Item>> list = new ArrayList<>();
return list;
}
public static List<ItemStack> customAdditions(){
List<ItemStack> list = new ArrayList<>();
CompoundTag gasolineTag = new CompoundTag();
gasolineTag.putString("gasoline", "forge:gasoline");
CompoundTag gasolineTagName = new CompoundTag();
gasolineTagName.putString("gasoline", "Gasoline");
//
CompoundTag dieselTag = new CompoundTag();
dieselTag.putString("diesel", "forge:diesel");
CompoundTag dieselTagName = new CompoundTag();
dieselTagName.putString("diesel", "Diesel");
//
CompoundTag lpgTag = new CompoundTag();
lpgTag.putString("lpg", "forge:lpg");
CompoundTag lpgTagName = new CompoundTag();
lpgTagName.putString("lpg", "LPG");
//
ItemStack gasoline = TFMGItems.ENGINE_CYLINDER.asStack();
gasoline.getOrCreateTag().put("Fuels", gasolineTag);
gasoline.getOrCreateTag().put("FuelNames", gasolineTagName);
list.add(gasoline);
ItemStack diesel = TFMGItems.ENGINE_CYLINDER.asStack();
diesel.getOrCreateTag().put("Fuels", dieselTag);
diesel.getOrCreateTag().put("FuelNames", dieselTagName);
list.add(diesel);
ItemStack lpg = TFMGItems.ENGINE_CYLINDER.asStack();
lpg.getOrCreateTag().put("Fuels", lpgTag);
lpg.getOrCreateTag().put("FuelNames", lpgTagName);
list.add(lpg);
return list;
}
}

View File

@@ -0,0 +1,96 @@
package com.drmangotea.tfmg.base;
import com.drmangotea.tfmg.TFMG;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.simibubi.create.foundation.gui.AllIcons;
import com.simibubi.create.foundation.gui.element.DelegatedStencilElement;
import com.simibubi.create.foundation.utility.Color;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.joml.Matrix4f;
public class TFMGIcons extends AllIcons {
public static final ResourceLocation ICON_ATLAS = TFMG.asResource("textures/gui/icons.png");
public static final int ICON_ATLAS_SIZE = 256;
private static int x = 0, y = -1;
private int iconX;
private int iconY;
public static final TFMGIcons
DISTILLATION_OUTPUT_ICON_DO_NOT_VOID = newRow(),
DISTILLATION_OUTPUT_ICON_VOID = next();
public TFMGIcons(int x, int y) {
super(x, y);
iconX = x * 16;
iconY = y * 16;
}
private static TFMGIcons next() {
return new TFMGIcons(++x, y);
}
private static TFMGIcons newRow() {
return new TFMGIcons(x = 0, ++y);
}
@OnlyIn(Dist.CLIENT)
public void bind() {
RenderSystem.setShaderTexture(0, ICON_ATLAS);
}
@OnlyIn(Dist.CLIENT)
@Override
public void render(GuiGraphics graphics, int x, int y) {
graphics.blit(ICON_ATLAS, x, y, 0, iconX, iconY, 16, 16, 256, 256);
}
@OnlyIn(Dist.CLIENT)
public void render(PoseStack ms, MultiBufferSource buffer, int color) {
VertexConsumer builder = buffer.getBuffer(RenderType.text(ICON_ATLAS));
Matrix4f matrix = ms.last().pose();
Color rgb = new Color(color);
int light = LightTexture.FULL_BRIGHT;
Vec3 vec1 = new Vec3(0, 0, 0);
Vec3 vec2 = new Vec3(0, 1, 0);
Vec3 vec3 = new Vec3(1, 1, 0);
Vec3 vec4 = new Vec3(1, 0, 0);
float u1 = iconX * 1f / ICON_ATLAS_SIZE;
float u2 = (iconX + 16) * 1f / ICON_ATLAS_SIZE;
float v1 = iconY * 1f / ICON_ATLAS_SIZE;
float v2 = (iconY + 16) * 1f / ICON_ATLAS_SIZE;
vertex(builder, matrix, vec1, rgb, u1, v1, light);
vertex(builder, matrix, vec2, rgb, u1, v2, light);
vertex(builder, matrix, vec3, rgb, u2, v2, light);
vertex(builder, matrix, vec4, rgb, u2, v1, light);
}
@OnlyIn(Dist.CLIENT)
private void vertex(VertexConsumer builder, Matrix4f matrix, Vec3 vec, Color rgb, float u, float v, int light) {
builder.vertex(matrix, (float) vec.x, (float) vec.y, (float) vec.z)
.color(rgb.getRed(), rgb.getGreen(), rgb.getBlue(), 255)
.uv(u, v)
.uv2(light)
.endVertex();
}
@OnlyIn(Dist.CLIENT)
public DelegatedStencilElement asStencil() {
return new DelegatedStencilElement().withStencilRenderer((ms, w, h, alpha) -> this.render(ms, 0, 0)).withBounds(16, 16);
}
}

View File

@@ -16,33 +16,33 @@ import static net.minecraft.core.Direction.*;
public class TFMGShapes {
public static final VoxelShaper
ENGINE = shape(0, 0, 0, 16, 7, 16).add(3, 7, 0, 13, 12, 16)
.forDirectional(SOUTH),
.forDirectional(SOUTH),
ENGINE_FRONT = shape(0, 0, 1, 16, 7, 16).add(3, 7, 1, 13, 12, 16)
.forDirectional(SOUTH),
PUMPJACK_HAMMER_PART = shape(0, 2, 0, 16, 14, 16)
.forDirectional(),
.forDirectional(),
RADIAL_ENGINE = shape(1, 4, 1, 15, 12, 15)
.forDirectional(),
.forDirectional(),
LARGE_RADIAL_ENGINE = shape(-3, 4, -3, 19, 12, 19)
.forDirectional(),
PUMPJACK_HEAD = shape(1, 0, -4, 15, 14, 24)
.forDirectional(),
.forDirectional(),
COMPACT_ENGINE_VERTICAL = shape(3, 0, 3, 13, 14, 14)
.forDirectional(),
.forDirectional(),
COMPACT_ENGINE = shape(3, 0, 3, 13, 14, 14)
.forDirectional(),
.forDirectional(),
CABLE_CONNECTOR = shape(6, 0, 6, 10, 9, 10)
.forDirectional(),
.forDirectional(),
CABLE_CONNECTOR_MIDDLE = shape(6, 0, 6, 10, 16, 10)
.forDirectional(),
.forDirectional(),
GALVANIC_CELL = shape(5, 10, 5, 11, 16, 16).add(1, 4, 6, 15, 10, 16)
.forDirectional(),
.forDirectional(),
RESISTOR = shape(6, 0, 3, 10, 4, 13)
.forDirectional(),
GENERATOR = shape(3, 0, 3, 13, 14, 13).add(0, 4, 0, 16, 10, 16)
.forDirectional(),
.forDirectional(),
LIGHT_BULB = shape(5, 0, 5, 11, 9, 11)
.forDirectional(),
.forDirectional(),
MODERN_LIGHT = shape(0, 0, 0, 16, 3, 16)
.forDirectional(),
CIRCULAR_LIGHT = shape(3, 0, 3, 13, 10, 13)
@@ -50,7 +50,7 @@ public class TFMGShapes {
ALUMINUM_LAMP = shape(3, 0, 3, 13, 2, 13).add(4, 2, 4, 12, 3, 12)
.forDirectional(),
POTENTIOMETER = shape(3, 0, 3, 13, 16, 13).add(1, 1, 13, 15, 15, 16)
.forDirectional(),
.forDirectional(),
WINDING_MACHINE = shape(0, 0, 0, 16, 8, 16).add(0, 8, 4, 10, 12, 12)
.forHorizontal(NORTH),
RESISTOR_VERTICAL = shape(3, 0, 3, 13, 16, 13)
@@ -58,16 +58,21 @@ public class TFMGShapes {
BLAST_FURNACE_REINFORCEMENT_WALL = shape(0, 0, 0, 16, 6, 16)
.forDirectional(),
ROTOR = shape(4, 5, 4, 12, 11, 12).add(5, 0, 5, 11, 16, 11)
ROTOR = shape(4, 5, 4, 12, 11, 12).add(5, 0, 5, 11, 16, 11)
.forDirectional(),
STATOR = shape(5, 1, 0, 16, 15.2, 5).add(5, 1, 5, 10, 15.2, 10).add(0, 1, 0, 5, 15.2, 16)
.forDirectional(),
.forDirectional(),
STATOR_ROTATED = shape(5, 1, 11, 16, 15, 16).add(5, 1, 6, 10, 15, 11).add(0, 1, 0, 5, 15, 16)
.forDirectional(),
STATOR_VERTICAL = shape(5, 0, 1, 16, 5, 15).add(5, 5, 1, 10, 10, 15).add(0, 0, 1, 5, 16, 15)
.forDirectional(),
VOLTMETER = shape(0, 0, 2, 16, 3, 14)
.forDirectional(),
.forDirectional(),
ELECTRIC_PUMP = shape(2, 6, 2, 14, 10, 14)
.add(4, 3, 4, 12, 11, 12)
.add(3, 11, 3, 13, 16, 13)
.add(3, 0, 3, 13, 5, 13)
.forDirectional(),
DIAGONAL_CABLE_BLOCK_DOWN = shape(3, 3, 11, 13, 13, 16)
.add(3, 11, 3, 13, 16, 13)
.add(4, 4, 5, 12, 11, 12)
@@ -79,38 +84,41 @@ public class TFMGShapes {
CASTING_BASIN = shape(0, 0, 0, 16, 8, 16)
.add(4, 8, 14, 12, 13, 16)
.forHorizontal(NORTH),
TRANSFORMER = shape(0, 0, 0, 16, 6, 16)
.add(1, 6, 5, 15, 15, 11)
.forHorizontal(NORTH),
CABLE_TUBE = shape(6, 0, 6, 10, 16, 10)
.forDirectional(),
REBAR_PILLAR = shape(3, 0, 3, 13, 16, 13)
.forDirectional(),
ELECTRICAL_SWITCH = shape(5, 0, 3, 11, 3, 13)
.forHorizontalAxis(),
.forHorizontalAxis(),
ELECTRICAL_SWITCH_CEILING = shape(5, 13, 3, 11, 16, 13)
.forHorizontalAxis(),
ELECTRICAL_SWITCH_WALL = shape(5, 3, 0, 11, 13, 3)
.forHorizontal(SOUTH),
POLARIZER = shape(4, 8, 0, 12, 12, 2)
.add(5, 8, 14, 11, 11, 16)
.add(11, 8, 4, 15, 12, 11)
.add(1, 8, 4, 5, 12, 11)
.add(0, 0, 0, 16, 8, 16)
.forHorizontal(NORTH)
;
.forHorizontal(NORTH);
public static final VoxelShape
EMPTY = shape(0, 0, 0, 0, 0, 0).build(),
PUMPJACK_CRANK = shape(0, 0, 0, 16, 8, 16).build(),
INDUSTRIAL_PIPE = shape(4, 0, 4, 12, 16, 12).build(),
FLARESTACK = shape(3, 0, 3, 13, 14, 14).build(),
PUMPJACK_BASE = shape(3, 0, 3, 13, 16, 13).build(),
TRAFFIC_LIGHT = shape(3, 0, 3, 13, 16, 13).build(),
REBAR_FLOOR = shape(0, 4, 0, 16, 12, 16)
.build(),
SURFACE_SCANNER = shape(2, 0, 2, 14, 14, 14).build(),
FULL = shape(0, 0, 0, 16, 16, 16).build(),
ELECTRIC_POST = shape(4, 0, 4, 12, 16, 12).build(),
SLAB = shape(0, 0, 0, 16, 8, 16).build();
;
EMPTY = shape(0, 0, 0, 0, 0, 0).build(),
PUMPJACK_CRANK = shape(0, 0, 0, 16, 8, 16).build(),
INDUSTRIAL_PIPE = shape(4, 0, 4, 12, 16, 12).build(),
FLARESTACK = shape(3, 0, 3, 13, 14, 14).build(),
PUMPJACK_BASE = shape(3, 0, 3, 13, 16, 13).build(),
TRAFFIC_LIGHT = shape(3, 0, 3, 13, 16, 13).build(),
REBAR_FLOOR = shape(0, 4, 0, 16, 12, 16)
.build(),
SURFACE_SCANNER = shape(2, 0, 2, 14, 14, 14).build(),
FULL = shape(0, 0, 0, 16, 16, 16).build(),
ELECTRIC_POST = shape(4, 0, 4, 12, 16, 12).build(),
SLAB = shape(0, 0, 0, 16, 8, 16).build();
;
private static Builder shape(VoxelShape shape) {
return new Builder(shape);
@@ -156,6 +164,7 @@ public class TFMGShapes {
public VoxelShaper build(BiFunction<VoxelShape, Axis, VoxelShaper> factory, Axis axis) {
return factory.apply(shape, axis);
}
public VoxelShaper forDirectional(Direction direction) {
return build(VoxelShaper::forDirectional, direction);
}

View File

@@ -8,6 +8,7 @@ import com.drmangotea.tfmg.content.electricity.connection.cables.CablePos;
import com.drmangotea.tfmg.registry.TFMGEntityTypes;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.simibubi.create.AllSoundEvents;
import com.simibubi.create.Create;
import com.simibubi.create.content.fluids.tank.FluidTankBlockEntity;
import com.simibubi.create.foundation.fluid.SmartFluidTank;
@@ -20,9 +21,12 @@ import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.Mth;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.Level;
@@ -69,6 +73,18 @@ public class TFMGUtils {
}
level.explode(null, pos.getX(), pos.getY(), pos.getZ(), radius, Level.ExplosionInteraction.BLOCK);
}
public static void playSound(Level level, BlockPos pos, SoundEvent sound, SoundSource source){
playSound(level,pos,sound,source,1,1,null);
}
public static void playSound(Level level, BlockPos pos, SoundEvent sound, SoundSource source, Player player){
playSound(level,pos,sound,source,1,1,player);
}
public static void playSound(Level level, BlockPos pos, SoundEvent sound, SoundSource source, float volume, float pitch){
playSound(level,pos,sound,source,volume,pitch,null);
}
public static void playSound(Level level, BlockPos pos, SoundEvent sound, SoundSource source, float volume, float pitch, Player player){
level.playSound(player,pos,sound,source,volume,pitch);
}
public static void blowUpTank(FluidTankBlockEntity tank, int power) {
@@ -264,6 +280,10 @@ public class TFMGUtils {
return super.drain(resource, action);
}
public FluidStack forceDrain(FluidStack resource, FluidAction action){
return super.drain(resource,action);
}
@Override
public FluidStack drain(int maxDrain, FluidAction action) {
if (!extractionAllowed) return FluidStack.EMPTY;

View File

@@ -2,11 +2,19 @@ package com.drmangotea.tfmg.base.events;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.engines.fuels.EngineFuelTypeManager;
import com.drmangotea.tfmg.registry.TFMGItems;
import com.simibubi.create.Create;
import com.simibubi.create.api.event.BlockEntityBehaviourEvent;
import com.simibubi.create.content.equipment.toolbox.ToolboxHandler;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.LevelAccessor;
import net.minecraftforge.event.AddReloadListenerEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.level.BlockEvent;
import net.minecraftforge.event.level.LevelEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
@@ -20,9 +28,31 @@ public class TFMGCommonEvents {
Player player = event.getEntity();
TFMG.DEPOSITS.playerLogin(player);
}
@SubscribeEvent
public static void onLoadWorld(LevelEvent.Load event) {
LevelAccessor world = event.getLevel();
TFMG.DEPOSITS.levelLoaded(world);
}
@SubscribeEvent
public static void onBlockPlaced(BlockEvent.EntityPlaceEvent event) {
if (event.getEntity() instanceof Player player) {
if (player.getItemInHand(InteractionHand.OFF_HAND).is(TFMGItems.ELECTRICIANS_WRENCH.get()) && event.getLevel().getBlockEntity(event.getPos()) instanceof IElectric be && be.canBeInGroups()) {
be.getData().group.id = player.getItemInHand(InteractionHand.OFF_HAND).getOrCreateTag().getInt("Number");
be.updateNextTick();
be.sendStuff();
}
}
}
@SubscribeEvent
public static void addReloadListeners(AddReloadListenerEvent event) {
event.addListener(EngineFuelTypeManager.ReloadListener.INSTANCE);
}
}

View File

@@ -9,9 +9,9 @@ public class MachineConfig extends ConfigBase {
public final ConfigInt blastFurnaceMaxHeight = i(10, 3, "blastFurnaceMaxHeight", Comments.blastFurnaceHeight);
public final ConfigFloat blastFurnaceHeightSpeedModifier = f(1f, 0.1f, "blastFurnaceHeightSpeedModifier", Comments.blastFurnaceHeightSpeedModifier);
public final ConfigInt blastFurnaceFuelConsumption = i(600, 1, "blastFurnaceFuelConsumption", Comments.blastFurnaceFuelConsumption);
public final ConfigInt electricMotorMinimumPower = i(3000, 1, "electricMotorMinimumPower", Comments.electricMotorMinimumPower);
public final ConfigInt electricMotorMinimumPower = i(250, 1, "electricMotorMinimumPower", Comments.electricMotorMinimumPower);
public final ConfigInt electricMotorMinimumVoltage = i(150, 1, "electricMotorMinimumVoltage", Comments.electricMotorMinimumVoltage);
public final ConfigFloat electricMotorPowerUsageModifier = f(1, 0, "electricMotorPowerUsageModifier", Comments.electricMotorPowerUsageModifier);
public final ConfigFloat electricMotorInternalResistance = f(100, 0, "electricMotorInternalResistance", Comments.electricMotorInternalResistance);
public final ConfigInt cokeOvenMaxSize = i(5, 1, "cokeOvenMaxSize", Comments.cokeOvenMaxSize);
public final ConfigInt accumulatorStorage = i(100000, 1, "accumulatorStorage", Comments.accumulatorStorage);
public final ConfigInt accumulatorVoltage = i(12, 1, "accumulatorVoltage", Comments.accumulatorVoltage);
@@ -41,7 +41,7 @@ public class MachineConfig extends ConfigBase {
static String blastFurnaceFuelConsumption = "Determines how many ticks does it take to consume one fuel.";
static String electricMotorMinimumPower = "Determines the minimum power an electric motor can run on.";
static String electricMotorMinimumVoltage = "Determines the minimum voltage an electric motor can run on.";
static String electricMotorPowerUsageModifier = "Changes the power usage of electric motors.";
static String electricMotorInternalResistance = "Sets the internal resistance of the electric motor.";
static String cokeOvenMaxSize = "Determines the maximum size of coke ovens.";
static String accumulatorStorage = "Determines the storage space of accumulators.";
static String accumulatorVoltage = "Determines the voltage accumulators output.";

View File

@@ -1,7 +1,6 @@
package com.drmangotea.tfmg.content.electricity.base;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.content.electricity.lights.LightBulbBlockEntity;
import com.drmangotea.tfmg.registry.TFMGPackets;
import com.simibubi.create.content.equipment.goggles.IHaveHoveringInformation;
import com.simibubi.create.foundation.blockEntity.SmartBlockEntity;
@@ -10,7 +9,6 @@ import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
@@ -23,22 +21,26 @@ public class ElectricBlockEntity extends SmartBlockEntity implements IElectric,
public ElectricBlockValues data = new ElectricBlockValues(getPos());
int powerPercentage = 100;
public ElectricBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
data.connectNextTick = true;
if(!canBeInGroups()){
if (!canBeInGroups()) {
data.group = new ElectricalGroup(-1);
}
}
@Override
public boolean addToTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
return makeElectricityTooltip(tooltip, isPlayerSneaking);
}
@Override
public void addBehaviours(List<BlockEntityBehaviour> behaviours) {}
@Override
public LevelAccessor getLevelAccessor(){
public void addBehaviours(List<BlockEntityBehaviour> behaviours) {
}
@Override
public LevelAccessor getLevelAccessor() {
return level;
}
@@ -49,7 +51,7 @@ public class ElectricBlockEntity extends SmartBlockEntity implements IElectric,
@Override
public ElectricalNetwork getOrCreateElectricNetwork() {
if(level.getBlockEntity(BlockPos.of(data.electricalNetworkId)) instanceof IElectric) {
if (level.getBlockEntity(BlockPos.of(data.electricalNetworkId)) instanceof IElectric) {
return TFMG.NETWORK_MANAGER.getOrCreateNetworkFor((IElectric) level.getBlockEntity(BlockPos.of(data.electricalNetworkId)));
} else {
ElectricNetworkManager.networks.get(getLevel())
@@ -61,6 +63,14 @@ public class ElectricBlockEntity extends SmartBlockEntity implements IElectric,
@Override
public void lazyTick() {
super.lazyTick();
if(data.failTimer >=4){
this.blockFail();
data.failTimer = 0;
sendStuff();
} else if((data.voltage>getMaxVoltage()&&getMaxVoltage()>0)||(getCurrent()>getMaxCurrent()&&getMaxCurrent()>0)){
blockFail();
data.failTimer++;
}
}
@Override
@@ -69,7 +79,6 @@ public class ElectricBlockEntity extends SmartBlockEntity implements IElectric,
}
@Override
public int getPowerPercentage() {
return powerPercentage;
@@ -79,25 +88,26 @@ public class ElectricBlockEntity extends SmartBlockEntity implements IElectric,
public float resistance() {
return 0;
}
@Override
public int voltageGeneration() {
int voltageGeneration = 0;
for(Direction direction : Direction.values()){
if(hasElectricitySlot(direction)){
for (Direction direction : Direction.values()) {
if (hasElectricitySlot(direction)) {
if(level.getBlockEntity(getBlockPos().relative(direction)) instanceof VoltageAlteringBlockEntity be)
if(be.getData().getId() !=getData().getId())
if(be.getData().getVoltage()!=0)
if(be.hasElectricitySlot(direction)){
voltageGeneration = Math.max(voltageGeneration,be.getOutputVoltage());
if (level.getBlockEntity(getBlockPos().relative(direction)) instanceof VoltageAlteringBlockEntity be)
if (be.getData().getId() != getData().getId())
if (be.getData().getVoltage() != 0)
if (be.hasElectricitySlot(direction)) {
voltageGeneration = Math.max(voltageGeneration, be.getOutputVoltage());
data.getsOutsidePower = true;
}
}
}
if(voltageGeneration == 0)
if (voltageGeneration == 0)
data.getsOutsidePower = false;
return voltageGeneration;
@@ -108,15 +118,16 @@ public class ElectricBlockEntity extends SmartBlockEntity implements IElectric,
int powerGeneration = 0;
for(Direction direction : Direction.values()){
if(hasElectricitySlot(direction)){
for (Direction direction : Direction.values()) {
if (hasElectricitySlot(direction)) {
if(level.getBlockEntity(getBlockPos().relative(direction)) instanceof VoltageAlteringBlockEntity be)
if(be.getData().getId() !=getData().getId())
if(be.getData().getVoltage()!=0)
if(be.hasElectricitySlot(direction)){
powerGeneration = Math.max(powerGeneration,be.getOutputPower());
if (level.getBlockEntity(getBlockPos().relative(direction)) instanceof VoltageAlteringBlockEntity be) {
if (be.getData().getId() != getData().getId())
if (be.getData().getVoltage() != 0)
if (be.hasElectricitySlot(direction)) {
powerGeneration = Math.max(powerGeneration, be.getPowerUsage()) + 1;
}
}
}
}
@@ -136,7 +147,7 @@ public class ElectricBlockEntity extends SmartBlockEntity implements IElectric,
@Override
public void updateNetwork() {
getOrCreateElectricNetwork().updateNetwork();
if(!level.isClientSide)
if (!level.isClientSide)
TFMGPackets.getChannel().send(PacketDistributor.ALL.noArg(), new NetworkUpdatePacket(BlockPos.of(getPos())));
sendData();
}
@@ -153,8 +164,8 @@ public class ElectricBlockEntity extends SmartBlockEntity implements IElectric,
// TFMG.LOGGER.debug("Rezistancja Grup "+data.group.resistance);
//}
if(canBeInGroups()){
data.voltage = (int) (((float)resistance()/data.group.resistance)*(float)data.voltageSupply);
if (canBeInGroups()) {
data.voltage = (int) (((float) resistance() / data.group.resistance) * (float) data.voltageSupply);
return;
}
data.voltage = newVoltage;
@@ -187,13 +198,13 @@ public class ElectricBlockEntity extends SmartBlockEntity implements IElectric,
@Override
public void setNetwork(long network) {
this.data.electricalNetworkId = network;
if(network!=getPos())
if (network != getPos())
ElectricNetworkManager.networks.get(getLevel())
.remove(getPos());
}
public boolean networkUndersupplied(){
return getNetworkPowerUsage()>data.networkPowerGeneration;
public boolean networkUndersupplied() {
return getNetworkPowerUsage() > data.networkPowerGeneration;
}
@@ -206,21 +217,20 @@ public class ElectricBlockEntity extends SmartBlockEntity implements IElectric,
public void remove() {
super.remove();
this.data.destroyed = true;
for(Direction d : Direction.values()) {
if(hasElectricitySlot(d))
if(getLevelAccessor().getBlockEntity(BlockPos.of(getPos()).relative(d)) instanceof IElectric be&&be.hasElectricitySlot(d.getOpposite())) {
for (Direction d : Direction.values()) {
if (hasElectricitySlot(d))
if (getLevelAccessor().getBlockEntity(BlockPos.of(getPos()).relative(d)) instanceof IElectric be && be.hasElectricitySlot(d.getOpposite())) {
ElectricNetworkManager.networks.get(getLevel())
.remove(be.getPos());
be.setNetwork(be.getPos());
be.onPlaced();
be.updateNextTick();
}
}
if(data.electricalNetworkId != getPos())
if (data.electricalNetworkId != getPos())
getOrCreateElectricNetwork().getMembers().remove(this);
if(data.electricalNetworkId == getPos())
if (data.electricalNetworkId == getPos())
ElectricNetworkManager.networks.get(getLevel())
.remove(getData().getId());
}
@@ -228,15 +238,16 @@ public class ElectricBlockEntity extends SmartBlockEntity implements IElectric,
@Override
public void tick() {
super.tick();
if(data.connectNextTick) {
onPlaced();
data.connectNextTick = false;
}
if(data.updateNextTick) {
updateNetwork();
data.updateNextTick = false;
}
if(data.setVoltageNextTick) {
if (data.connectNextTick) {
TFMG.LOGGER.debug("SIGMA A");
onPlaced();
data.connectNextTick = false;
}
if (data.updateNextTick) {
updateNetwork();
data.updateNextTick = false;
}
if (data.setVoltageNextTick) {
setVoltage(data.voltageSupply);
data.setVoltageNextTick = false;
}
@@ -256,7 +267,7 @@ public class ElectricBlockEntity extends SmartBlockEntity implements IElectric,
super.read(compound, clientPacket);
data.group = new ElectricalGroup(compound.getInt("GroupId"));
data.group.resistance = compound.getFloat("GroupResistance");
if(!clientPacket)
if (!clientPacket)
data.connectNextTick = true;
}
}

View File

@@ -17,6 +17,8 @@ public class ElectricBlockValues {
public boolean setVoltageNextTick = false;
public int failTimer = 0;
public ElectricalGroup group = new ElectricalGroup(0);
public ElectricBlockValues(long pos){

View File

@@ -1,9 +1,6 @@
package com.drmangotea.tfmg.content.electricity.base;
import com.drmangotea.tfmg.content.electricity.connection.cables.IHaveCables;
import com.drmangotea.tfmg.content.electricity.connection.cables.WireNetwork;
import net.minecraft.world.level.LevelAccessor;
import org.apache.http.impl.conn.Wire;
import java.util.HashMap;
import java.util.Map;

View File

@@ -1,8 +1,13 @@
package com.drmangotea.tfmg.content.electricity.base;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.base.TFMGUtils;
import com.drmangotea.tfmg.content.electricity.connection.cables.CableConnectorBlockEntity;
import com.drmangotea.tfmg.content.electricity.lights.LightBulbBlockEntity;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import java.util.ArrayList;
import java.util.HashMap;
@@ -27,11 +32,9 @@ public class ElectricalNetwork {
List<Long> posList = new ArrayList<>();
members.forEach(member -> posList.add(member.getData().getId()));
if (posList.contains(be.getData().getId()))
return;
members.add(be);
}
public void updateNetwork() {
@@ -42,10 +45,10 @@ public class ElectricalNetwork {
int powerGeneration = 0;
Map<Integer, Float> groups = new HashMap<>();
for (IElectric member : members) {
int groupId = member.getData().group.id;
maxVoltage = Math.max(member.voltageGeneration(), maxVoltage);

View File

@@ -29,18 +29,28 @@ public interface IElectric {
}
default void onPlaced() {
if (!getLevelAccessor().isClientSide())
TFMGPackets.getChannel().send(PacketDistributor.ALL.noArg(), new ConnectNeightborsPacket(BlockPos.of(getPos())));
TFMG.NETWORK_MANAGER.getOrCreateNetworkFor(this);
setNetwork(getPos());
getData().electricalNetworkId = getPos();
updateNetwork();
onConnected();
sendStuff();
updateNextTick();
}
default void onConnected() {
default int getMaxVoltage() {
return 0;
}
default int getMaxCurrent() {
return 0;
}
default void onConnected() {
BlockPos pos = BlockPos.of(getPos());
for (Direction d : Direction.values()) {
@@ -51,6 +61,7 @@ public interface IElectric {
getOrCreateElectricNetwork().add(be);
if (be.getData().getId() != getData().getId()) {
be.setNetwork(getData().getId());
TFMG.LOGGER.debug("KONNEQT ");
be.onConnected();
if (!getLevelAccessor().isClientSide())
sendStuff();
@@ -62,12 +73,16 @@ public interface IElectric {
}
}
sendStuff();
}
default boolean makeElectricityTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
Lang.number(getOrCreateElectricNetwork().members.size()).forGoggles(tooltip, 1);
if (getData().failTimer > 0)
Lang.text("Skill issue: " + getData().failTimer).forGoggles(tooltip, 1);
Lang.text("X " + BlockPos.of(getData().electricalNetworkId).getX() + " Y " + BlockPos.of(getData().electricalNetworkId).getY() + " Z " + BlockPos.of(getData().electricalNetworkId).getZ()).forGoggles(tooltip, 1);
Lang.translate("multimeter.header")
.style(ChatFormatting.WHITE)
.forGoggles(tooltip, 1);
@@ -136,13 +151,27 @@ public interface IElectric {
ElectricBlockValues getData();
default void blockFail() {
getLevelAccessor().destroyBlock(BlockPos.of(getPos()), false);
}
default int getPowerUsage() {
return (int) (getData().getVoltage() * getCurrent());
}
default int getNetworkPowerUsage(IElectric blocked) {
int power = 0;
for (IElectric member : getOrCreateElectricNetwork().members)
if (member.getPos() != blocked.getPos()) {
power += member.getPowerUsage();
} else blocked.updateNextTick();
return power;
}
default int getNetworkPowerUsage() {
int power = 0;
for (IElectric member : getOrCreateElectricNetwork().members)
power += member.getPowerUsage();
return power;
}
@@ -181,18 +210,20 @@ public interface IElectric {
default float getCurrent() {
return getData().getVoltage() == 0 || resistance() == 0 ? 0 : ((float) getData().getVoltage() / (float) resistance());
}
default float getCableCurrent(){
float current =0;
default float getCableCurrent() {
float current = 0;
List<Integer> groups = new ArrayList<>();
for(IElectric member : getOrCreateElectricNetwork().members){
if(member.canBeInGroups())
if(!groups.contains(member.getData().group.id)){
current+=member.getCurrent();
for (IElectric member : getOrCreateElectricNetwork().members) {
if (member.canBeInGroups())
if (!groups.contains(member.getData().group.id)) {
current += member.getCurrent();
groups.add(member.getData().group.id);
}
}
return current;
}
void updateNextTick();
void updateNetwork();

View File

@@ -112,7 +112,7 @@ public class KineticElectricBlockEntity extends GeneratingKineticBlockEntity imp
if(be.getData().getId() !=getData().getId())
if(be.getData().getVoltage()!=0)
if(be.hasElectricitySlot(direction)){
powerGeneration = Math.max(powerGeneration,be.getOutputPower());
powerGeneration = Math.max(powerGeneration,be.getOutputPower())+10;
}
}
}
@@ -126,9 +126,6 @@ public class KineticElectricBlockEntity extends GeneratingKineticBlockEntity imp
}
@Override
public void updateNextTick() {
data.updateNextTick = true;
@@ -149,6 +146,7 @@ public class KineticElectricBlockEntity extends GeneratingKineticBlockEntity imp
@Override
public void setVoltage(int newVoltage) {
if(canBeInGroups()){
data.voltage = (int) (((float)resistance()/data.group.resistance)*(float)data.voltageSupply);
return;
@@ -202,20 +200,20 @@ public class KineticElectricBlockEntity extends GeneratingKineticBlockEntity imp
public void remove() {
super.remove();
this.data.destroyed = true;
for(Direction d : Direction.values()) {
if(hasElectricitySlot(d))
if(getLevelAccessor().getBlockEntity(BlockPos.of(getPos()).relative(d)) instanceof IElectric be&&be.hasElectricitySlot(d.getOpposite())) {
for (Direction d : Direction.values()) {
if (hasElectricitySlot(d))
if (getLevelAccessor().getBlockEntity(BlockPos.of(getPos()).relative(d)) instanceof IElectric be && be.hasElectricitySlot(d.getOpposite())) {
ElectricNetworkManager.networks.get(getLevel())
.remove(be.getPos());
be.setNetwork(be.getPos());
be.onPlaced();
be.getData().connectNextTick = true;
be.updateNextTick();
}
}
if(data.electricalNetworkId != getPos())
if (data.electricalNetworkId != getPos())
getOrCreateElectricNetwork().getMembers().remove(this);
if(data.electricalNetworkId == getPos())
if (data.electricalNetworkId == getPos())
ElectricNetworkManager.networks.get(getLevel())
.remove(getData().getId());
}
@@ -243,6 +241,20 @@ public class KineticElectricBlockEntity extends GeneratingKineticBlockEntity imp
}
@Override
public void lazyTick() {
super.lazyTick();
if(data.failTimer >=4){
this.blockFail();
data.failTimer = 0;
sendStuff();
} else if((data.voltage>getMaxVoltage()&&getMaxVoltage()>0)||(getCurrent()>getMaxCurrent()&&getMaxCurrent()>0)){
blockFail();
data.failTimer++;
}
}
@Override
protected void write(CompoundTag tag, boolean clientPacket) {
super.write(tag, clientPacket);

View File

@@ -11,18 +11,16 @@ import org.checkerframework.checker.units.qual.C;
public class CableConnection {
final CablePos pos1;
final CablePos pos2;
final BlockPos blockPos1;
final BlockPos blockPos2;
final boolean visible;
final CableType type;
public final CablePos pos1;
public final CablePos pos2;
public final BlockPos blockPos1;
public final boolean visible;
public final CableType type;
public CableConnection(CablePos pos1, CablePos pos2,BlockPos blockPos1,BlockPos blockPos2,CableType type, boolean visible){
public CableConnection(CablePos pos1, CablePos pos2,BlockPos blockPos1,CableType type, boolean visible){
this.pos1 = pos1;
this.pos2 = pos2;
this.blockPos1 = blockPos1;
this.blockPos2 = blockPos2;
this.visible = visible;
this.type = type;
}
@@ -41,13 +39,9 @@ public class CableConnection {
//compoundTag.putLong("BlockPos1", blockPos1.asLong());
//compoundTag.putLong("BlockPos2", blockPos2.asLong());
compoundTag.putInt("XX1", blockPos1.getX());
compoundTag.putInt("YY1", blockPos1.getY());
compoundTag.putInt("ZZ1", blockPos1.getZ());
compoundTag.putLong("Pos", blockPos1.asLong());
compoundTag.putInt("XX2", blockPos2.getX());
compoundTag.putInt("YY2", blockPos2.getY());
compoundTag.putInt("ZZ2", blockPos2.getZ());
compoundTag.putBoolean("Visible", visible);
@@ -66,13 +60,11 @@ public class CableConnection {
//BlockPos blockPos1 = BlockPos.of(compoundTag.getLong("BlockPos1"));
//BlockPos blockPos2 = BlockPos.of(compoundTag.getLong("BlockPos2"));
BlockPos blockPos1 = new BlockPos(compoundTag.getInt("XX1"),compoundTag.getInt("YY1"),compoundTag.getInt("ZZ1"));
BlockPos blockPos2 = new BlockPos(compoundTag.getInt("XX2"),compoundTag.getInt("YY2"),compoundTag.getInt("ZZ2"));
BlockPos blockPos1 = BlockPos.of(compoundTag.getLong("Pos"));
boolean visible = compoundTag.getBoolean("Visible");
CableType type = CableType.valueOf(compoundTag.getString("CableType"));
return new CableConnection(pos1,pos2,blockPos1,blockPos2,type,visible);
return new CableConnection(pos1,pos2,blockPos1,type,visible);
}
public float getLength(){
return TFMGUtils.getDistance(new BlockPos((int) pos1.x(), (int) pos1.y(), (int) pos1.z()),new BlockPos((int) pos2.x(), (int) pos2.y(), (int) pos2.z()), false);
@@ -82,9 +74,10 @@ public class CableConnection {
public enum CableType{
NONE(TFMGItems.COPPER_WIRE, 0,0xffffff),
COPPER(TFMGItems.COPPER_WIRE, 0.0188f,0xD8735A),
ALUMINUM(TFMGItems.ALUMINUM_WIRE, 0.0188f,0xEDEFEF),
STEEL_REINFORCED_ALUMINUM(TFMGItems.COPPER_WIRE, 0.0188f,0x595E5F)
COPPER(TFMGItems.COPPER_WIRE, 0.00188f,0xD8735A),
ALUMINUM(TFMGItems.ALUMINUM_WIRE, 0.0027f,0xEDEFEF),
CONSTANTAN(TFMGItems.CONSTANTAN_WIRE, 1f,0xEDEFEF),
STEEL_REINFORCED_ALUMINUM(TFMGItems.COPPER_WIRE, 0.0027f,0xB8A08D)
;
public final ItemEntry<?> wire;
public final float resistivity;

View File

@@ -2,6 +2,7 @@ package com.drmangotea.tfmg.content.electricity.connection.cables;
import com.drmangotea.tfmg.base.TFMGShapes;
import com.drmangotea.tfmg.base.WallMountBlock;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
import com.simibubi.create.foundation.block.IBE;
import net.minecraft.core.BlockPos;
@@ -29,7 +30,7 @@ public class CableConnectorBlock extends WallMountBlock implements IBE<CableConn
@Override
public void onPlace(BlockState state, Level level, BlockPos pos, BlockState blockState1, boolean b) {
updateExtension(level,state,pos);
withBlockEntityDo(level,pos, IElectric::onPlaced);
BlockPos below = pos.relative(state.getValue(FACING).getOpposite());
BlockState stateBelow = level.getBlockState(below);
if(stateBelow.getBlock() instanceof IHaveCables)
@@ -38,6 +39,13 @@ public class CableConnectorBlock extends WallMountBlock implements IBE<CableConn
super.onPlace(state, level, pos, blockState1, b);
}
@Override
public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
IBE.onRemove(state, level, pos, newState);
}
//@Override
//public InteractionResult use(BlockState state, Level level, BlockPos pos, Player p_60506_, InteractionHand p_60507_, BlockHitResult p_60508_) {
// if(level.isClientSide)
@@ -90,7 +98,7 @@ public class CableConnectorBlock extends WallMountBlock implements IBE<CableConn
BlockPos above = pos.relative(state.getValue(FACING));
BlockState stateAbove = level.getBlockState(above);
if(stateAbove.getBlock() instanceof IHaveCables) {
if(stateAbove.getBlock() instanceof IHaveCables&&stateAbove.getValue(FACING)==state.getValue(FACING)) {
level.setBlockAndUpdate(pos, state.setValue(EXTENSION, true));
} else {
level.setBlockAndUpdate(pos, state.setValue(EXTENSION, false));

View File

@@ -1,30 +1,30 @@
package com.drmangotea.tfmg.content.electricity.connection.cables;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.content.electricity.base.ElectricNetworkManager;
import com.drmangotea.tfmg.registry.TFMGPackets;
import com.drmangotea.tfmg.base.TFMGUtils;
import com.drmangotea.tfmg.content.electricity.base.ElectricBlockEntity;
import com.simibubi.create.content.equipment.goggles.IHaveHoveringInformation;
import com.simibubi.create.foundation.blockEntity.SmartBlockEntity;
import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour;
import com.simibubi.create.foundation.utility.Lang;
import com.simibubi.create.foundation.utility.animation.LerpedFloat;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
import net.minecraftforge.network.PacketDistributor;
import java.util.ArrayList;
import java.util.List;
public class CableConnectorBlockEntity extends SmartBlockEntity implements IHaveHoveringInformation {
import static com.drmangotea.tfmg.base.WallMountBlock.FACING;
import static com.drmangotea.tfmg.content.electricity.connection.cables.CableConnectorBlock.EXTENSION;
public class CableConnectorBlockEntity extends ElectricBlockEntity implements IHaveHoveringInformation {
//player held cable rendering
public Player player;
@@ -36,6 +36,7 @@ public class CableConnectorBlockEntity extends SmartBlockEntity implements IHave
public List<CableConnection> connections = new ArrayList<>();
public long id;
public boolean removeWiresNextTick = false;
public CableConnectorBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
@@ -46,17 +47,34 @@ public class CableConnectorBlockEntity extends SmartBlockEntity implements IHave
}
@Override
public void addBehaviours(List<BlockEntityBehaviour> behaviours) {}
public void addBehaviours(List<BlockEntityBehaviour> behaviours) {
}
@Override
public void remove() {
super.remove();
removeConnections(false);
notifyRemoval();
}
public void removeConnections(boolean client) {
if (!level.isClientSide()) {
TFMGPackets.getChannel().send(PacketDistributor.ALL.noArg(), new CablePacket(this.getBlockPos()));
} else if(!client)
@Override
public boolean hasElectricitySlot(Direction direction) {
if(getBlockState().getValue(EXTENSION))
return direction.getAxis() == getBlockState().getValue(FACING).getAxis();
return direction == getBlockState().getValue(FACING).getOpposite();
}
@Override
public boolean makeElectricityTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
return super.makeElectricityTooltip(tooltip, isPlayerSneaking);
}
public void notifyRemoval() {
if(level.isClientSide)
return;
for (CableConnection connection : connections) {
@@ -64,25 +82,119 @@ public class CableConnectorBlockEntity extends SmartBlockEntity implements IHave
if (itemToDrop.getItem().getCount() > 0) {
level.addFreshEntity(itemToDrop);
}
BlockPos pos = connection.blockPos1 == getBlockPos() ? connection.blockPos2 : connection.blockPos1;
if (level.getBlockEntity(pos) instanceof CableConnectorBlockEntity be) {
BlockPos pos = connection.blockPos1;
if(be.getBlockPos() == getBlockPos())
// level.setBlock(connection.blockPos1.above(), Blocks.GOLD_BLOCK.defaultBlockState(),3);
if (level.getBlockEntity(pos) instanceof CableConnectorBlockEntity be) {
if (be.getBlockPos() == getBlockPos())
continue;
be.connections.removeIf(c->c.blockPos1==getBlockPos()||c.blockPos2==getBlockPos());
be.setChanged();
be.sendData();
setChanged();
sendData();
be.onPlaced();
be.removeWiresNextTick = true;
}
}
}
//@Override
//public float resistance() {
// float resistance = 0;
// for(CableConnection connection : connections){
// if(connection.visible){
// resistance+=connection.type.resistivity*connection.getLength();
// }
// }
// return resistance;
//}
public void removeConnection(){
connections.removeIf(c->{
BlockPos pos = c.blockPos1;
return !(level.getBlockEntity(pos) instanceof CableConnectorBlockEntity);
});
sendStuff();
}
@Override
public void onConnected() {
super.onConnected();
for(CableConnectorBlockEntity be : getConnectedWires()){
if (be.getData().getId() != getData().getId()) {
be.setNetwork(getData().getId());
be.onConnected();
}
be.sendStuff();
}
sendStuff();
}
public List<CableConnectorBlockEntity> getConnectedWires(){
return getConnectedWires(new ArrayList<>());
}
public List<CableConnectorBlockEntity> getConnectedWires(List<CableConnectorBlockEntity> foundList){
if(!foundList.contains(this)) {
foundList.add(this);
}
for(CableConnection connection : connections){
BlockPos pos = connection.blockPos1;
//level.setBlockAndUpdate(pos.above(), Blocks.GOLD_BLOCK.defaultBlockState());
//level.setBlockAndUpdate(pos2.above(2), Blocks.DIAMOND_BLOCK.defaultBlockState());
if(connection.blockPos1 == getBlockPos())
TFMGUtils.debugMessage(level, "PRIMARY IS SUS");
if(pos ==getBlockPos()){
TFMG.LOGGER.debug("WHAT THE SIGMA");
continue;
}
// TFMGUtils.debugMessage(level, "Eﴤ "+connections.size());
if(level.getBlockEntity(pos) instanceof CableConnectorBlockEntity bee&&bee.getBlockPos() == getBlockPos())
TFMGUtils.debugMessage(level, "SUSSY BEHAVIOUR");
if(level.getBlockEntity(pos) instanceof CableConnectorBlockEntity be&&!foundList.contains(be)){
// TFMGUtils.debugMessage(level, "Bﴤ "+connections.size());
be.getConnectedWires(foundList);
sendStuff();
be.sendStuff();
}
}
sendStuff();
return foundList;
}
@Override
public void tick() {
super.tick();
if(removeWiresNextTick) {
removeConnection();
removeWiresNextTick = false;
}
if (player != null)
managePlayerWire();
}
@Override
@@ -91,6 +203,8 @@ public class CableConnectorBlockEntity extends SmartBlockEntity implements IHave
compound.putInt("ConnectionCount", connections.size());
for (int i = 0; i < connections.size(); i++) {
CableConnection connection = connections.get(i);
compound.put("Connection" + i, connection.saveConnection());
@@ -108,6 +222,7 @@ public class CableConnectorBlockEntity extends SmartBlockEntity implements IHave
@Override
protected void read(CompoundTag compound, boolean clientPacket) {
super.read(compound, clientPacket);
connections = new ArrayList<>();
for (int i = 0; i < compound.getInt("ConnectionCount"); i++) {

View File

@@ -31,7 +31,7 @@ public class CableConnectorRenderer extends SafeBlockEntityRenderer<CableConnect
for (CableConnection connection : be.connections) {
if (connection.visible)
TFMGUtils.renderWire(be.getLevel(), ms, bufferSource, connection.pos1, connection.pos2, connection.getLength() / 4500, new Color(connection.type.color).getRed(), new Color(connection.type.color).getGreen(), new Color(connection.type.color).getBlue());
TFMGUtils.renderWire(be.getLevel(), ms, bufferSource, connection.pos2, connection.pos1, connection.getLength() / 4500, new Color(connection.type.color).getRed(), new Color(connection.type.color).getGreen(), new Color(connection.type.color).getBlue());
}
//for (BlockPos connection : be.connections) {

View File

@@ -1,24 +1,24 @@
package com.drmangotea.tfmg.content.electricity.connection.cables;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.simibubi.create.foundation.blockEntity.SmartBlockEntity;
import com.simibubi.create.foundation.networking.BlockEntityDataPacket;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
public class CablePacket extends BlockEntityDataPacket<SmartBlockEntity> {
public class CablePlacePacket extends BlockEntityDataPacket<SmartBlockEntity> {
public CablePacket(BlockPos pos) {
public CablePlacePacket(BlockPos pos) {
super(pos);
}
public CablePacket(FriendlyByteBuf buffer) {
public CablePlacePacket(FriendlyByteBuf buffer) {
super(buffer);
@@ -32,7 +32,7 @@ public class CablePacket extends BlockEntityDataPacket<SmartBlockEntity> {
protected void handlePacket(SmartBlockEntity blockEntity) {
if(blockEntity instanceof CableConnectorBlockEntity be) {
be.removeConnections(true);
be.onConnected();
}
}

View File

@@ -0,0 +1,41 @@
package com.drmangotea.tfmg.content.electricity.connection.cables;
import com.simibubi.create.foundation.blockEntity.SmartBlockEntity;
import com.simibubi.create.foundation.networking.BlockEntityDataPacket;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
public class CableRemovalPacket extends BlockEntityDataPacket<SmartBlockEntity> {
public CableRemovalPacket(BlockPos pos) {
super(pos);
}
public CableRemovalPacket(FriendlyByteBuf buffer) {
super(buffer);
}
@Override
protected void writeData(FriendlyByteBuf buffer) {}
@Override
protected void handlePacket(SmartBlockEntity blockEntity) {
if(blockEntity instanceof CableConnectorBlockEntity be) {
// be.removeConnections(true);
}
}
}

View File

@@ -1,44 +0,0 @@
package com.drmangotea.tfmg.content.electricity.connection.cables;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import org.apache.http.impl.conn.Wire;
import java.util.ArrayList;
import java.util.List;
public class WireNetwork{
public long id;
public List<IHaveCables> connectors = new ArrayList<>();
public int voltage;
public float resistance;
public WireNetwork(long id){
this.id = id;
}
public void add(IHaveCables be) {
List<Long> posList = new ArrayList<>();
connectors.forEach(member -> posList.add(member.getId()));
if (posList.contains(be.getId()))
return;
connectors.add(be);
}
public void updateCables(){
for(IHaveCables cable : connectors){
if(cable instanceof IElectric be){
}
}
}
}

View File

@@ -0,0 +1,362 @@
package com.drmangotea.tfmg.content.electricity.connection.copycat_cable;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.simibubi.create.AllTags;
import com.simibubi.create.content.equipment.wrench.IWrenchable;
import com.simibubi.create.foundation.block.IBE;
import net.minecraft.client.Minecraft;
import net.minecraft.client.color.block.BlockColor;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.SpawnPlacements;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.*;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.model.data.ModelDataManager;
import net.minecraftforge.network.PacketDistributor;
import javax.annotation.Nullable;
public class CopycatCableBlock extends Block implements IBE<CopycatCableBlockEntity>, IWrenchable {
public CopycatCableBlock(Properties pProperties) {
super(pProperties);
}
@Override
public InteractionResult onSneakWrenched(BlockState state, UseOnContext context) {
onWrenched(state, context);
return IWrenchable.super.onSneakWrenched(state, context);
}
@Override
public InteractionResult onWrenched(BlockState state, UseOnContext context) {
return onBlockEntityUse(context.getLevel(), context.getClickedPos(), ufte -> {
ItemStack consumedItem = ufte.getConsumedItem();
if (!ufte.hasCustomMaterial())
return InteractionResult.PASS;
Player player = context.getPlayer();
if (!player.isCreative())
player.getInventory()
.placeItemBackInInventory(consumedItem);
context.getLevel()
.levelEvent(2001, context.getClickedPos(), Block.getId(ufte.getBlockState()));
ufte.setMaterial(TFMGBlocks.COPYCAT_CABLE_BASE.getDefaultState());
ufte.setConsumedItem(ItemStack.EMPTY);
return InteractionResult.SUCCESS;
});
}
@Override
public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand, BlockHitResult pHit) {
if (pPlayer == null)
return InteractionResult.PASS;
Direction face = pHit.getDirection();
ItemStack itemInHand = pPlayer.getItemInHand(pHand);
BlockState materialIn = getAcceptedBlockState(pLevel, pPos, itemInHand, face);
if (materialIn != null)
materialIn = prepareMaterial(pLevel, pPos, pState, pPlayer, pHand, pHit, materialIn);
if (materialIn == null)
return InteractionResult.PASS;
BlockState material = materialIn;
return onBlockEntityUse(pLevel, pPos, ufte -> {
if (ufte.getMaterial()
.is(material.getBlock())) {
if (!ufte.cycleMaterial())
return InteractionResult.PASS;
ufte.getLevel()
.playSound(null, ufte.getBlockPos(), SoundEvents.ITEM_FRAME_ADD_ITEM, SoundSource.BLOCKS, .75f,
.95f);
return InteractionResult.SUCCESS;
}
if (ufte.hasCustomMaterial())
return InteractionResult.PASS;
if (pLevel.isClientSide())
return InteractionResult.SUCCESS;
ufte.setMaterial(material);
ufte.setConsumedItem(itemInHand);
ufte.getLevel()
.playSound(null, ufte.getBlockPos(), material.getSoundType()
.getPlaceSound(), SoundSource.BLOCKS, 1, .75f);
if (pPlayer.isCreative())
return InteractionResult.SUCCESS;
itemInHand.shrink(1);
if (itemInHand.isEmpty())
pPlayer.setItemInHand(pHand, ItemStack.EMPTY);
return InteractionResult.SUCCESS;
});
}
@Override
public void setPlacedBy(Level pLevel, BlockPos pPos, BlockState pState, LivingEntity pPlacer, ItemStack pStack) {
if (pPlacer == null)
return;
ItemStack offhandItem = pPlacer.getItemInHand(InteractionHand.OFF_HAND);
BlockState appliedState =
getAcceptedBlockState(pLevel, pPos, offhandItem, Direction.orderedByNearest(pPlacer)[0]);
if (appliedState == null)
return;
withBlockEntityDo(pLevel, pPos, ufte -> {
if (ufte.hasCustomMaterial())
return;
ufte.setMaterial(appliedState);
ufte.setConsumedItem(offhandItem);
if (pPlacer instanceof Player player && player.isCreative())
return;
offhandItem.shrink(1);
if (offhandItem.isEmpty())
pPlacer.setItemInHand(InteractionHand.OFF_HAND, ItemStack.EMPTY);
});
}
@Nullable
public BlockState getAcceptedBlockState(Level pLevel, BlockPos pPos, ItemStack item, Direction face) {
if (!(item.getItem() instanceof BlockItem bi))
return null;
Block block = bi.getBlock();
if (block instanceof com.simibubi.create.content.decoration.copycat.CopycatBlock||block instanceof CopycatCableBlock)
return null;
BlockState appliedState = block.defaultBlockState();
boolean hardCodedAllow = isAcceptedRegardless(appliedState);
if (!AllTags.AllBlockTags.COPYCAT_ALLOW.matches(block) && !hardCodedAllow) {
if (AllTags.AllBlockTags.COPYCAT_DENY.matches(block))
return null;
if (block instanceof EntityBlock)
return null;
if (block instanceof StairBlock)
return null;
if (pLevel != null) {
VoxelShape shape = appliedState.getShape(pLevel, pPos);
if (shape.isEmpty() || !shape.bounds()
.equals(Shapes.block()
.bounds()))
return null;
VoxelShape collisionShape = appliedState.getCollisionShape(pLevel, pPos);
if (collisionShape.isEmpty())
return null;
}
}
if (face != null) {
Direction.Axis axis = face.getAxis();
if (appliedState.hasProperty(BlockStateProperties.FACING))
appliedState = appliedState.setValue(BlockStateProperties.FACING, face);
if (appliedState.hasProperty(BlockStateProperties.HORIZONTAL_FACING) && axis != Direction.Axis.Y)
appliedState = appliedState.setValue(BlockStateProperties.HORIZONTAL_FACING, face);
if (appliedState.hasProperty(BlockStateProperties.AXIS))
appliedState = appliedState.setValue(BlockStateProperties.AXIS, axis);
if (appliedState.hasProperty(BlockStateProperties.HORIZONTAL_AXIS) && axis != Direction.Axis.Y)
appliedState = appliedState.setValue(BlockStateProperties.HORIZONTAL_AXIS, axis);
}
return appliedState;
}
public boolean isAcceptedRegardless(BlockState material) {
return false;
}
public BlockState prepareMaterial(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer, InteractionHand pHand, BlockHitResult pHit, BlockState material) {
return material;
}
@Override
public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean pIsMoving) {
IBE.onRemove(state, level, pos, newState);
if (!state.hasBlockEntity() || state.getBlock() == newState.getBlock())
return;
if (!pIsMoving)
withBlockEntityDo(level, pos, ufte -> Block.popResource(level, pos, ufte.getConsumedItem()));
level.removeBlockEntity(pos);
}
@Override
public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) {
super.playerWillDestroy(pLevel, pPos, pState, pPlayer);
if (pPlayer.isCreative())
withBlockEntityDo(pLevel, pPos, ufte -> ufte.setConsumedItem(ItemStack.EMPTY));
}
@Override
public void onPlace(BlockState pState, Level level, BlockPos pos, BlockState pOldState, boolean pIsMoving) {
withBlockEntityDo(level,pos, IElectric::onPlaced);
}
@Override
public Class<CopycatCableBlockEntity> getBlockEntityClass() {
return CopycatCableBlockEntity.class;
}
@Override
public BlockEntityType<? extends CopycatCableBlockEntity> getBlockEntityType() {
return TFMGBlockEntities.COPYCAT_CABLE.get();
}
// Connected Textures
@Override
@OnlyIn(Dist.CLIENT)
public BlockState getAppearance(BlockState state, BlockAndTintGetter level, BlockPos pos, Direction side,
BlockState queryState, BlockPos queryPos) {
if (isIgnoredConnectivitySide(level, state, side, pos, queryPos))
return state;
ModelDataManager modelDataManager = level.getModelDataManager();
if (modelDataManager == null)
return getMaterial(level, pos);
return CopycatCableBlockModel.getMaterial(modelDataManager.getAt(pos));
}
public boolean isIgnoredConnectivitySide(BlockAndTintGetter reader, BlockState state, Direction face,
BlockPos fromPos, BlockPos toPos) {
return false;
}
public static BlockState getMaterial(BlockGetter reader, BlockPos targetPos) {
if (reader.getBlockEntity(targetPos) instanceof CopycatCableBlockEntity cbe)
return cbe.getMaterial();
return Blocks.AIR.defaultBlockState();
}
// Wrapped properties
@Override
public SoundType getSoundType(BlockState state, LevelReader level, BlockPos pos, Entity entity) {
return getMaterial(level, pos).getSoundType();
}
@Override
public float getFriction(BlockState state, LevelReader level, BlockPos pos, Entity entity) {
return getMaterial(level, pos).getFriction(level, pos, entity);
}
@Override
public int getLightEmission(BlockState state, BlockGetter level, BlockPos pos) {
return getMaterial(level, pos).getLightEmission(level, pos);
}
@Override
public boolean canHarvestBlock(BlockState state, BlockGetter level, BlockPos pos, Player player) {
return getMaterial(level, pos).canHarvestBlock(level, pos, player);
}
@Override
public float getExplosionResistance(BlockState state, BlockGetter level, BlockPos pos, Explosion explosion) {
return getMaterial(level, pos).getExplosionResistance(level, pos, explosion);
}
@Override
public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter level, BlockPos pos,
Player player) {
BlockState material = getMaterial(level, pos);
if (TFMGBlocks.COPYCAT_CABLE_BASE.has(material) || player != null && player.isShiftKeyDown())
return new ItemStack(this);
return material.getCloneItemStack(target, level, pos, player);
}
@Override
public boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2,
LivingEntity entity, int numberOfParticles) {
return getMaterial(level, pos).addLandingEffects(level, pos, state2, entity, numberOfParticles);
}
@Override
public boolean addRunningEffects(BlockState state, Level level, BlockPos pos, Entity entity) {
return getMaterial(level, pos).addRunningEffects(level, pos, entity);
}
@Override
public float getEnchantPowerBonus(BlockState state, LevelReader level, BlockPos pos) {
return getMaterial(level, pos).getEnchantPowerBonus(level, pos);
}
@Override
public boolean canEntityDestroy(BlockState state, BlockGetter level, BlockPos pos, Entity entity) {
return getMaterial(level, pos).canEntityDestroy(level, pos, entity);
}
@Override
public boolean isValidSpawn(BlockState state, BlockGetter level, BlockPos pos, SpawnPlacements.Type type,
EntityType<?> entityType) {
return false;
}
@Override
public void fallOn(Level pLevel, BlockState pState, BlockPos pPos, Entity pEntity, float pFallDistance) {
BlockState material = getMaterial(pLevel, pPos);
material.getBlock()
.fallOn(pLevel, material, pPos, pEntity, pFallDistance);
}
@Override
public float getDestroyProgress(BlockState pState, Player pPlayer, BlockGetter pLevel, BlockPos pPos) {
return getMaterial(pLevel, pPos).getDestroyProgress(pPlayer, pLevel, pPos);
}
//
@OnlyIn(Dist.CLIENT)
public static BlockColor wrappedColor() {
return new WrappedBlockColor();
}
@OnlyIn(Dist.CLIENT)
public static class WrappedBlockColor implements BlockColor {
@Override
public int getColor(BlockState pState, @Nullable BlockAndTintGetter pLevel, @Nullable BlockPos pPos,
int pTintIndex) {
if (pLevel == null || pPos == null)
return GrassColor.get(0.5D, 1.0D);
return Minecraft.getInstance()
.getBlockColors()
.getColor(getMaterial(pLevel, pPos), pLevel, pPos, pTintIndex);
}
}
}

View File

@@ -0,0 +1,292 @@
package com.drmangotea.tfmg.content.electricity.connection.copycat_cable;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.content.electricity.base.*;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.drmangotea.tfmg.registry.TFMGPackets;
import com.simibubi.create.AllBlocks;
import com.simibubi.create.content.decoration.copycat.CopycatBlock;
import com.simibubi.create.content.decoration.copycat.CopycatBlockEntity;
import com.simibubi.create.content.equipment.goggles.IHaveGoggleInformation;
import com.simibubi.create.content.equipment.goggles.IHaveHoveringInformation;
import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.network.PacketDistributor;
import java.util.List;
public class CopycatCableBlockEntity extends CopycatBlockEntity implements IElectric, IHaveHoveringInformation {
public ElectricBlockValues data = new ElectricBlockValues(getPos());
int powerPercentage = 100;
boolean setNextTick = true;
public CopycatCableBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
data.connectNextTick = true;
if (!canBeInGroups()) {
data.group = new ElectricalGroup(-1);
}
}
public boolean addToTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
return makeElectricityTooltip(tooltip, isPlayerSneaking);
}
@Override
public boolean hasCustomMaterial() {
return !TFMGBlocks.COPYCAT_CABLE_BASE.has(getMaterial());
}
@Override
public void addBehaviours(List<BlockEntityBehaviour> behaviours) {
}
@Override
public LevelAccessor getLevelAccessor() {
return level;
}
@Override
public boolean destroyed() {
return data.destroyed;
}
@Override
public ElectricalNetwork getOrCreateElectricNetwork() {
if (level.getBlockEntity(BlockPos.of(data.electricalNetworkId)) instanceof IElectric) {
return TFMG.NETWORK_MANAGER.getOrCreateNetworkFor((IElectric) level.getBlockEntity(BlockPos.of(data.electricalNetworkId)));
} else {
ElectricNetworkManager.networks.get(getLevel())
.remove(data.electricalNetworkId);
return TFMG.NETWORK_MANAGER.getOrCreateNetworkFor(this);
}
}
@Override
public void lazyTick() {
super.lazyTick();
}
@Override
public ElectricBlockValues getData() {
return data;
}
@Override
public int getPowerPercentage() {
return powerPercentage;
}
@Override
public float resistance() {
return 0;
}
@Override
public int voltageGeneration() {
int voltageGeneration = 0;
for (Direction direction : Direction.values()) {
if (hasElectricitySlot(direction)) {
if (level.getBlockEntity(getBlockPos().relative(direction)) instanceof VoltageAlteringBlockEntity be)
if (be.getData().getId() != getData().getId())
if (be.getData().getVoltage() != 0)
if (be.hasElectricitySlot(direction)) {
voltageGeneration = Math.max(voltageGeneration, be.getOutputVoltage());
data.getsOutsidePower = true;
}
}
}
if (voltageGeneration == 0)
data.getsOutsidePower = false;
return voltageGeneration;
}
@Override
public int powerGeneration() {
int powerGeneration = 0;
for (Direction direction : Direction.values()) {
if (hasElectricitySlot(direction)) {
if (level.getBlockEntity(getBlockPos().relative(direction)) instanceof VoltageAlteringBlockEntity be) {
if (be.getData().getId() != getData().getId())
if (be.getData().getVoltage() != 0)
if (be.hasElectricitySlot(direction)) {
powerGeneration = Math.max(powerGeneration, be.getPowerUsage()) + 1;
}
}
}
}
return powerGeneration;
}
@Override
public int frequencyGeneration() {
return 0;
}
@Override
public void updateNextTick() {
data.updateNextTick = true;
}
@Override
public void updateNetwork() {
getOrCreateElectricNetwork().updateNetwork();
if (!level.isClientSide)
TFMGPackets.getChannel().send(PacketDistributor.ALL.noArg(), new NetworkUpdatePacket(BlockPos.of(getPos())));
sendData();
}
@Override
public void sendStuff() {
sendData();
}
@Override
public void setVoltage(int newVoltage) {
//if(this instanceof LightBulbBlockEntity be&&be.color == DyeColor.WHITE){
// TFMG.LOGGER.debug("Rezistancja Grup "+data.group.resistance);
//}
if (canBeInGroups()) {
data.voltage = (int) (((float) resistance() / data.group.resistance) * (float) data.voltageSupply);
return;
}
data.voltage = newVoltage;
}
@Override
public void setFrequency(int newFrequency) {
data.frequency = newFrequency;
}
@Override
public void setNetworkResistance(int newUsage) {
data.networkResistance = newUsage;
}
@Override
public int getNetworkResistance() {
return data.networkResistance;
}
@Override
public void setWattage(int newWattage) {
}
@Override
public void setPowerPercentage(int percentage) {
powerPercentage = percentage;
}
@Override
public void setNetwork(long network) {
this.data.electricalNetworkId = network;
if (network != getPos())
ElectricNetworkManager.networks.get(getLevel())
.remove(getPos());
}
public boolean networkUndersupplied() {
return getNetworkPowerUsage() > data.networkPowerGeneration;
}
@Override
public long getPos() {
return getBlockPos().asLong();
}
@Override
public void remove() {
super.remove();
this.data.destroyed = true;
for (Direction d : Direction.values()) {
if (hasElectricitySlot(d))
if (getLevelAccessor().getBlockEntity(BlockPos.of(getPos()).relative(d)) instanceof IElectric be && be.hasElectricitySlot(d.getOpposite())) {
ElectricNetworkManager.networks.get(getLevel())
.remove(be.getPos());
be.setNetwork(be.getPos());
be.onPlaced();
be.updateNextTick();
}
}
if (data.electricalNetworkId != getPos())
getOrCreateElectricNetwork().getMembers().remove(this);
if (data.electricalNetworkId == getPos())
ElectricNetworkManager.networks.get(getLevel())
.remove(getData().getId());
}
@Override
public void tick() {
super.tick();
if (data.connectNextTick) {
onPlaced();
data.connectNextTick = false;
}
if (data.updateNextTick) {
updateNetwork();
data.updateNextTick = false;
}
if (data.setVoltageNextTick) {
setVoltage(data.voltageSupply);
data.setVoltageNextTick = false;
}
if(setNextTick) {
setMaterial(TFMGBlocks.COPYCAT_CABLE_BASE.getDefaultState());
setNextTick = false;
}
}
@Override
protected void write(CompoundTag compound, boolean clientPacket) {
super.write(compound, clientPacket);
compound.putInt("GroupId", data.group.id);
compound.putFloat("GroupResistance", data.group.resistance);
}
@Override
protected void read(CompoundTag compound, boolean clientPacket) {
super.read(compound, clientPacket);
// Validate Material
if (getMaterial() != null && !clientPacket) {
BlockState blockState = getBlockState();
if (blockState == null)
return;
if (!(blockState.getBlock() instanceof CopycatBlock cb))
return;
BlockState acceptedBlockState = cb.getAcceptedBlockState(level, worldPosition, ItemStack.EMPTY, null);
if (acceptedBlockState != null && getMaterial().is(acceptedBlockState.getBlock()))
return;
setMaterial(TFMGBlocks.COPYCAT_CABLE_BASE.getDefaultState());
}
//
data.group = new ElectricalGroup(compound.getInt("GroupId"));
data.group.resistance = compound.getFloat("GroupResistance");
if (!clientPacket)
data.connectNextTick = true;
}
}

View File

@@ -0,0 +1,105 @@
package com.drmangotea.tfmg.content.electricity.connection.copycat_cable;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.simibubi.create.AllBlocks;
import com.simibubi.create.content.decoration.copycat.CopycatSpecialCases;
import com.simibubi.create.foundation.model.BakedModelHelper;
import com.simibubi.create.foundation.model.BakedQuadHelper;
import com.simibubi.create.foundation.utility.Iterate;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.BlockRenderDispatcher;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.DirectionalBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.client.model.data.ModelData;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class CopycatCableBlockModel extends com.simibubi.create.content.decoration.copycat.CopycatModel {
protected static final AABB CUBE_AABB = new AABB(BlockPos.ZERO);
public CopycatCableBlockModel(BakedModel originalModel) {
super(originalModel);
}
@Override
protected ModelData.Builder gatherModelData(ModelData.Builder builder, BlockAndTintGetter world, BlockPos pos, BlockState state, ModelData blockEntityData) {
BlockState material = getMaterial(blockEntityData);
if (material == null)
return builder;
return super.gatherModelData(builder, world, pos, state, blockEntityData);
}
@Nullable
public static BlockState getMaterial(ModelData data) {
BlockState material = data == null ? null : data.get(MATERIAL_PROPERTY);
return material == null ? TFMGBlocks.COPYCAT_CABLE_BASE.getDefaultState() : material;
}
@Override
protected List<BakedQuad> getCroppedQuads(BlockState state, Direction side, RandomSource rand, BlockState material,
ModelData wrappedData, RenderType renderType) {
Direction facing = Direction.UP;
BlockRenderDispatcher blockRenderer = Minecraft.getInstance()
.getBlockRenderer();
BlockState specialCopycatModelState = null;
//if (CopycatSpecialCases.isBarsMaterial(material))
// specialCopycatModelState = AllBlocks.COPYCAT_BARS.getDefaultState();
if (CopycatSpecialCases.isTrapdoorMaterial(material))
return blockRenderer.getBlockModel(material)
.getQuads(state, side, rand, wrappedData, renderType);
//if (specialCopycatModelState != null) {
// BakedModel blockModel = blockRenderer
// .getBlockModel(specialCopycatModelState.setValue(DirectionalBlock.FACING, facing));
// if (blockModel instanceof AbstractCopycatCableModel cm)
// return cm.getCroppedQuads(state, side, rand, material, wrappedData, renderType);
//}
BakedModel model = getModelOf(material);
List<BakedQuad> templateQuads = model.getQuads(material, side, rand, wrappedData, renderType);
int size = templateQuads.size();
List<BakedQuad> quads = new ArrayList<>();
Vec3 normal = Vec3.atLowerCornerOf(facing.getNormal());
Vec3 normalScaled16 = normal.scale(8 / 16f);
// 2 Pieces
for (boolean front : Iterate.trueAndFalse) {
Vec3 normalScaledN13 = normal.scale(front ? 0 : -0 / 16f);
float contract = 16 - (8);
AABB bb = CUBE_AABB.contract(normal.x * contract / 16, normal.y * contract / 16, normal.z * contract / 16);
if (!front)
bb = bb.move(normalScaled16);
for (BakedQuad quad : templateQuads) {
Direction direction = quad.getDirection();
if (front && direction == facing)
continue;
if (!front && direction == facing.getOpposite())
continue;
quads.add(BakedQuadHelper.cloneWithCustomGeometry(quad,
BakedModelHelper.cropAndMove(quad.getVertices(), quad.getSprite(), bb, normalScaledN13)));
}
}
return quads;
}
}

View File

@@ -3,29 +3,40 @@ package com.drmangotea.tfmg.content.electricity.debug;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.base.TFMGUtils;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.electricity.connection.cables.CableConnection;
import com.drmangotea.tfmg.content.electricity.connection.cables.CableConnectorBlockEntity;
import com.drmangotea.tfmg.content.electricity.generators.GeneratorBlockEntity;
import com.drmangotea.tfmg.content.electricity.storage.AccumulatorBlockEntity;
import com.drmangotea.tfmg.content.electricity.utilities.electric_motor.ElectricMotorBlockEntity;
import com.drmangotea.tfmg.content.engines.base.AbstractEngineBlockEntity;
import com.drmangotea.tfmg.content.engines.regular_engine.RegularEngineBlockEntity;
import com.drmangotea.tfmg.content.machinery.metallurgy.blast_stove.BlastStoveBlockEntity;
import com.drmangotea.tfmg.content.machinery.metallurgy.casting_basin.CastingBasinBlockEntity;
import com.drmangotea.tfmg.content.machinery.metallurgy.coke_oven.CokeOvenBlockEntity;
import com.drmangotea.tfmg.content.machinery.misc.concrete_hose.ConcreteHoseBlockEntity;
import com.drmangotea.tfmg.content.machinery.misc.vat_machines.base.VatBlockEntity;
import com.drmangotea.tfmg.content.machinery.oil_processing.pumpjack.pumpjack.base.PumpjackBaseBlockEntity;
import com.drmangotea.tfmg.content.machinery.oil_processing.surface_scanner.SurfaceScannerBlockEntity;
import com.drmangotea.tfmg.registry.TFMGItems;
import com.simibubi.create.content.fluids.FluidPropagator;
import com.simibubi.create.content.fluids.pipes.FluidPipeBlockEntity;
import com.simibubi.create.content.fluids.tank.FluidTankBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.network.protocol.game.DebugPackets;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.ticks.TickPriority;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.simibubi.create.content.fluids.pipes.FluidPipeBlock.isOpenAt;
public class DebugCinderBlockItem extends Item {
public DebugCinderBlockItem(Properties p_41383_) {
super(p_41383_);
@@ -41,15 +52,41 @@ public class DebugCinderBlockItem extends Item {
BlockPos pos = context.getClickedPos();
Level level = context.getLevel();
if(level.getBlockEntity(pos) instanceof RegularEngineBlockEntity be){
be.updateRotation();
return InteractionResult.SUCCESS;
}
if(level.getBlockEntity(pos) instanceof GeneratorBlockEntity be){
be.updateStress();
return InteractionResult.SUCCESS;
}
if(level.getBlockEntity(pos) instanceof ElectricMotorBlockEntity be){
be.onPlaced();
return InteractionResult.SUCCESS;
}
if(level.getBlockEntity(pos) instanceof ConcreteHoseBlockEntity be){
be.filler.reset();
return InteractionResult.SUCCESS;
}
if(level.getBlockEntity(pos) instanceof CableConnectorBlockEntity be){
//be.testSigma();
be.wiresUpdated();
if(context.getPlayer().isShiftKeyDown()) {
TFMG.LOGGER.debug("///////////////////////////////");
for(CableConnection connection : be.connections) {
TFMG.LOGGER.debug("Primary Pos "+connection.blockPos1.getX()+" "+connection.blockPos1.getY()+" "+connection.blockPos1.getZ());
}
TFMG.LOGGER.debug("///////////////////////////////");
return InteractionResult.SUCCESS;
}
TFMG.LOGGER.debug("///////////////////////////////");
TFMG.LOGGER.debug("Connector Count "+be.getConnectedWires().size());
TFMG.LOGGER.debug("Wire Count "+be.connections.size());
TFMG.LOGGER.debug("Member Count "+be.getOrCreateElectricNetwork().members.size());
TFMG.LOGGER.debug("Id "+"X "+BlockPos.of(be.getData().electricalNetworkId).getX()+" Y "+BlockPos.of(be.getData().electricalNetworkId).getY()+" Z "+BlockPos.of(be.getData().electricalNetworkId).getZ());
TFMG.LOGGER.debug("///////////////////////////////");
return InteractionResult.SUCCESS;
}
if(level.getBlockEntity(pos) instanceof IElectric be){
@@ -61,7 +98,12 @@ public class DebugCinderBlockItem extends Item {
TFMG.LOGGER.debug("Higherst Current "+be.getData().highestCurrent);
TFMG.LOGGER.debug("Group "+be.getData().group.id);
TFMG.LOGGER.debug("///////////////////////////////");
}else be.updateNextTick();
}else {
TFMGUtils.debugMessage(level, "Power "+be.getNetworkPowerUsage());
TFMGUtils.debugMessage(level, "Voltage "+be.getData().getVoltage());
};
}
if(level.getBlockEntity(pos) instanceof CokeOvenBlockEntity be){
be.controller = be.getBlockPos();

View File

@@ -0,0 +1,35 @@
package com.drmangotea.tfmg.content.electricity.electrians_wrench;
import com.drmangotea.tfmg.base.TFMGUtils;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import net.minecraft.core.BlockPos;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
public class ElectricBlockItem extends BlockItem {
public ElectricBlockItem(Block p_40565_, Properties p_40566_) {
super(p_40565_, p_40566_);
}
@Override
public InteractionResult place(BlockPlaceContext context) {
Level level = context.getLevel();
BlockPos pos = context.getClickedPos();
if(level.getBlockEntity(pos) instanceof IElectric be&&be.canBeInGroups()){
be.getData().group.id = context.getItemInHand().getOrCreateTag().getInt("Number");
be.updateNextTick();
be.sendStuff();
}
return super.place(context);
}
}

View File

@@ -1,12 +1,17 @@
package com.drmangotea.tfmg.content.electricity.electrians_wrench;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.base.TFMGUtils;
import com.drmangotea.tfmg.content.electricity.base.ConnectNeightborsPacket;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.engines.base.AbstractEngineBlockEntity;
import com.drmangotea.tfmg.registry.TFMGPackets;
import com.simibubi.create.content.equipment.symmetryWand.SymmetryWandScreen;
import com.simibubi.create.foundation.gui.ScreenOpener;
import net.minecraft.core.BlockPos;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.InteractionResultHolder;
@@ -48,15 +53,24 @@ public class ElectriciansWrenchItem extends Item {
Level level = context.getLevel();
BlockPos pos = context.getClickedPos();
if(!context.getPlayer().isShiftKeyDown())
if(level.getBlockEntity(pos) instanceof IElectric be){
if(!context.getPlayer().isShiftKeyDown()) {
if (level.getBlockEntity(pos) instanceof IElectric be && be.canBeInGroups()) {
be.getData().group.id = context.getItemInHand().getOrCreateTag().getInt("Number");
TFMGUtils.playSound(level, pos, SoundEvents.ITEM_PICKUP, SoundSource.BLOCKS, context.getPlayer());
be.updateNextTick();
be.sendStuff();
return InteractionResult.SUCCESS;
}
if (level.getBlockEntity(pos) instanceof AbstractEngineBlockEntity be ) {
be.changeDirection();
return InteractionResult.SUCCESS;
}
}
return super.useOn(context);

View File

@@ -2,18 +2,14 @@ package com.drmangotea.tfmg.content.electricity.lights;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.base.TFMGUtils;
import com.drmangotea.tfmg.content.electricity.base.ElectricBlockEntity;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.drmangotea.tfmg.registry.TFMGPackets;
import com.drmangotea.tfmg.registry.TFMGPartialModels;
import com.jozufozu.flywheel.core.PartialModel;
import com.simibubi.create.foundation.utility.NBTHelper;
import com.simibubi.create.foundation.utility.animation.LerpedFloat;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.item.DyeColor;
@@ -69,6 +65,22 @@ public class LightBulbBlockEntity extends ElectricBlockEntity {
notifyUpdate();
}
@Override
public void blockFail() {
super.blockFail();
TFMGUtils.playSound(level,getBlockPos(), SoundEvents.GLASS_BREAK, SoundSource.BLOCKS);
}
@Override
public int getMaxVoltage() {
return 500;
}
@Override
public int getMaxCurrent() {
return 4;
}
@Override
public void setVoltage(int newVoltage) {
super.setVoltage(newVoltage);

View File

@@ -0,0 +1,163 @@
package com.drmangotea.tfmg.content.electricity.lights.neon_tube;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.electricity.lights.LightBulbBlock;
import com.drmangotea.tfmg.content.electricity.lights.LightBulbBlockEntity;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.simibubi.create.content.contraptions.behaviour.dispenser.SimplePos;
import com.simibubi.create.content.equipment.wrench.IWrenchable;
import com.simibubi.create.foundation.block.IBE;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.PipeBlock;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.IntegerProperty;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.Vec3;
public class NeonTubeBlock extends PipeBlock implements IBE<NeonTubeBlockEntity>, IWrenchable {
public static final IntegerProperty LIGHT = LightBulbBlock.LIGHT;
public NeonTubeBlock(Properties p_55160_) {
super(0.3125F/2.5f, p_55160_);
this.registerDefaultState(this.stateDefinition.any().setValue(LIGHT, 0).setValue(NORTH, Boolean.valueOf(false)).setValue(EAST, Boolean.valueOf(false)).setValue(SOUTH, Boolean.valueOf(false)).setValue(WEST, Boolean.valueOf(false)).setValue(UP, Boolean.valueOf(true)).setValue(DOWN, Boolean.valueOf(true)));
}
public BlockState getStateForPlacement(BlockPlaceContext p_51709_) {
return this.getStateForPlacement(p_51709_.getLevel(), p_51709_.getClickedPos());
}
public BlockState getStateForPlacement(BlockGetter p_51711_, BlockPos p_51712_) {
BlockState blockstate = p_51711_.getBlockState(p_51712_.below());
BlockState blockstate1 = p_51711_.getBlockState(p_51712_.above());
BlockState blockstate2 = p_51711_.getBlockState(p_51712_.north());
BlockState blockstate3 = p_51711_.getBlockState(p_51712_.east());
BlockState blockstate4 = p_51711_.getBlockState(p_51712_.south());
BlockState blockstate5 = p_51711_.getBlockState(p_51712_.west());
return this.defaultBlockState().setValue(DOWN, Boolean.valueOf(blockstate.is(this) || blockstate.is(Blocks.CHORUS_FLOWER) || blockstate.is(Blocks.END_STONE))).setValue(UP, Boolean.valueOf(blockstate1.is(this) || blockstate1.is(Blocks.CHORUS_FLOWER))).setValue(NORTH, Boolean.valueOf(blockstate2.is(this) || blockstate2.is(Blocks.CHORUS_FLOWER))).setValue(EAST, Boolean.valueOf(blockstate3.is(this) || blockstate3.is(Blocks.CHORUS_FLOWER))).setValue(SOUTH, Boolean.valueOf(blockstate4.is(this) || blockstate4.is(Blocks.CHORUS_FLOWER))).setValue(WEST, Boolean.valueOf(blockstate5.is(this) || blockstate5.is(Blocks.CHORUS_FLOWER)));
}
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_51735_) {
p_51735_.add(NORTH, EAST, SOUTH, WEST, UP, DOWN,LIGHT);
}
@Override
public InteractionResult onWrenched(BlockState state, UseOnContext context) {
Level level = context.getLevel();
BlockPos pos = context.getClickedPos();
Direction facing = context.getClickedFace();
Vec3 position = context.getClickLocation();
TFMG.LOGGER.debug("X "+(position.x()-pos.getX())+" Y "+(position.y()-pos.getY())+" Z "+(position.z()-pos.getZ()));
SimplePos clickPosition = new SimplePos(position.x()-pos.getX(),position.y()-pos.getY(),position.z()-pos.getZ());
Direction dirToToggle = Direction.NORTH;
if(clickPosition.x()>=0.375&&clickPosition.x()<=0.625&&clickPosition.y()>=0.375&&clickPosition.y()<=0.625&&clickPosition.z()>=0.375&&clickPosition.z()<=0.625){
dirToToggle = facing;
}
if(clickPosition.x()>0.625)
dirToToggle = Direction.EAST;
if(clickPosition.x()<0.375)
dirToToggle = Direction.WEST;
if(clickPosition.y()>0.625)
dirToToggle = Direction.UP;
if(clickPosition.y()<0.375)
dirToToggle = Direction.DOWN;
if(clickPosition.z()>0.625)
dirToToggle = Direction.SOUTH;
if(clickPosition.z()<0.375)
dirToToggle = Direction.NORTH;
switch (dirToToggle){
case UP -> level.setBlockAndUpdate(pos, state.setValue(UP,!state.getValue(UP)));
case DOWN -> level.setBlockAndUpdate(pos, state.setValue(DOWN,!state.getValue(DOWN)));
case WEST -> level.setBlockAndUpdate(pos, state.setValue(WEST,!state.getValue(WEST)));
case EAST -> level.setBlockAndUpdate(pos, state.setValue(EAST,!state.getValue(EAST)));
case NORTH -> level.setBlockAndUpdate(pos, state.setValue(NORTH,!state.getValue(NORTH)));
case SOUTH -> level.setBlockAndUpdate(pos, state.setValue(SOUTH,!state.getValue(SOUTH)));
}
withBlockEntityDo(level,pos, IElectric::onPlaced);
for(Direction direction : Direction.values()){
if(level.getBlockEntity(pos.relative(direction)) instanceof IElectric be){
be.onPlaced();
}
}
return InteractionResult.SUCCESS;
}
@Override
public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player player, InteractionHand pHand,
BlockHitResult pHit) {
if (player.isShiftKeyDown())
return InteractionResult.PASS;
ItemStack heldItem = player.getItemInHand(pHand);
NeonTubeBlockEntity be = getBlockEntity(pLevel, pPos);
DyeColor dye = DyeColor.getColor(heldItem);
if (be != null) {
if (dye != null) {
pLevel.playSound(null, pPos, SoundEvents.DYE_USE, SoundSource.BLOCKS, 1.0F, 1.0F);
be.setColor(dye);
return InteractionResult.SUCCESS;
}
}
return InteractionResult.PASS;
}
@Override
public void onPlace(BlockState state, Level level, BlockPos pos, BlockState p_60569_, boolean p_60570_) {
if(!p_60569_.is(TFMGBlocks.NEON_TUBE.get()))
for(Direction facing : Direction.values()) {
BlockState neighbourState = level.getBlockState(pos.relative(facing));
TFMG.LOGGER.debug("A");
if (neighbourState.is(TFMGBlocks.NEON_TUBE.get())) {
level.setBlockAndUpdate(pos.relative(facing), neighbourState.setValue(PipeBlock.PROPERTY_BY_DIRECTION.get(facing.getOpposite()), true));
TFMG.LOGGER.debug("B");
}
}
withBlockEntityDo(level,pos, IElectric::onPlaced);
super.onPlace(state, level, pos, p_60569_, p_60570_);
}
@Override
public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
IBE.onRemove(state, level, pos, newState);
}
@Override
public Class<NeonTubeBlockEntity> getBlockEntityClass() {
return NeonTubeBlockEntity.class;
}
@Override
public BlockEntityType<? extends NeonTubeBlockEntity> getBlockEntityType() {
return TFMGBlockEntities.NEON_TUBE.get();
}
}

View File

@@ -0,0 +1,68 @@
package com.drmangotea.tfmg.content.electricity.lights.neon_tube;
import com.drmangotea.tfmg.content.electricity.base.ElectricBlockEntity;
import com.simibubi.create.foundation.utility.NBTHelper;
import com.simibubi.create.foundation.utility.animation.LerpedFloat;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.level.block.PipeBlock;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import static com.drmangotea.tfmg.content.electricity.lights.LightBulbBlock.LIGHT;
public class NeonTubeBlockEntity extends ElectricBlockEntity {
public DyeColor color= DyeColor.WHITE;
public LerpedFloat glow = LerpedFloat.linear();
public NeonTubeBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
}
@Override
public boolean canBeInGroups() {
return true;
}
@Override
public void tick() {
super.tick();
glow.chase(getPowerUsage()*1.5, 0.4, LerpedFloat.Chaser.EXP);
glow.tickChaser();
if (Math.min(getData().getVoltage() / 10, 15) != getBlockState().getValue(LIGHT))
level.setBlock(getBlockPos(), getBlockState().setValue(LIGHT, (int) Math.min(getData().getVoltage() / 10, 15)), 2);
}
@Override
protected void write(CompoundTag compound, boolean clientPacket) {
super.write(compound, clientPacket);
NBTHelper.writeEnum(compound,"color",color);
}
@Override
protected void read(CompoundTag compound, boolean clientPacket) {
super.read(compound, clientPacket);
color = NBTHelper.readEnum(compound,"color",DyeColor.class);
}
public void setColor(DyeColor color) {
if(color==DyeColor.BLACK||color == DyeColor.LIGHT_GRAY|| color == DyeColor.GRAY)
return;
this.color = color;
notifyUpdate();
}
@Override
public boolean hasElectricitySlot(Direction direction) {
return getBlockState().getValue(PipeBlock.PROPERTY_BY_DIRECTION.get(direction));
}
@Override
public float resistance() {
return 200;
}
}

View File

@@ -0,0 +1,83 @@
package com.drmangotea.tfmg.content.electricity.lights.neon_tube;
import com.drmangotea.tfmg.base.WallMountBlock;
import com.drmangotea.tfmg.content.electricity.lights.LightBulbBlockEntity;
import com.drmangotea.tfmg.registry.TFMGPartialModels;
import com.jozufozu.flywheel.core.PartialModel;
import com.mojang.blaze3d.vertex.PoseStack;
import com.simibubi.create.foundation.blockEntity.renderer.SafeBlockEntityRenderer;
import com.simibubi.create.foundation.render.CachedBufferer;
import com.simibubi.create.foundation.render.RenderTypes;
import com.simibubi.create.foundation.render.SuperByteBuffer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.minecraft.core.Direction;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.level.block.PipeBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
public class NeonTubeRenderer extends SafeBlockEntityRenderer<NeonTubeBlockEntity> {
public NeonTubeRenderer(BlockEntityRendererProvider.Context context) {
}
@Override
protected void renderSafe(NeonTubeBlockEntity be, float partialTicks, PoseStack ms, MultiBufferSource buffer, int light, int overlay) {
BlockState blockState = be.getBlockState();
ms.pushPose();
float glow = be.glow.getValue(partialTicks);
int color = Math.min(100, (int) (glow / 0.2f));
if (be.glow.getValue() != 0) {
SuperByteBuffer lightModel = CachedBufferer.partial(TFMGPartialModels.NEON_TUBE_LIGHT_CENTER, blockState)
.light((int) glow * 3 + 40)
.color(color, color, (int) (color * 0.8), 255)
.disableDiffuse();
PipeBlock.PROPERTY_BY_DIRECTION.forEach((d, p) -> {
if (blockState.getValue(p)) {
int xRotation = d.getAxis().isHorizontal() ? 90 : d == Direction.DOWN ? 180 : 0;
int yRotation = 0;
if(d==Direction.NORTH)
yRotation = 180;
if(d==Direction.WEST)
yRotation = 270;
if(d==Direction.EAST)
yRotation = 90;
SuperByteBuffer sideModel = CachedBufferer.partial(TFMGPartialModels.NEON_TUBE_LIGHT_SIDE, blockState)
.centre()
.rotateY(yRotation)
.rotateX(xRotation)
.unCentre()
.light((int) glow * 3 + 40)
.color(color, color, (int) (color * 0.8), 255)
.disableDiffuse();
if (be.color == DyeColor.WHITE) {
sideModel.color(color, color, (int) (color * 0.8), 255);
} else sideModel.color(be.color.getTextColor());
sideModel.renderInto(ms, buffer.getBuffer(RenderTypes.getAdditive()));
}
});
if (be.color == DyeColor.WHITE) {
lightModel.color(color, color, (int) (color * 0.8), 255);
} else lightModel.color(be.color.getTextColor());
lightModel.renderInto(ms, buffer.getBuffer(RenderTypes.getAdditive()));
}
ms.popPose();
}
}

View File

@@ -1,12 +1,15 @@
package com.drmangotea.tfmg.content.electricity.storage;
import com.drmangotea.tfmg.base.TFMGDirectionalBlock;
import com.drmangotea.tfmg.content.electricity.base.ConnectNeightborsPacket;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.electricity.connection.cables.IHaveCables;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.drmangotea.tfmg.registry.TFMGPackets;
import com.simibubi.create.foundation.block.IBE;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.LivingEntity;
@@ -15,11 +18,15 @@ import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.DirectionalBlock;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.block.state.properties.IntegerProperty;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.storage.loot.BuiltInLootTables;
import net.minecraft.world.level.storage.loot.LootParams;
@@ -31,17 +38,15 @@ import net.minecraftforge.network.PacketDistributor;
import java.util.Collections;
import java.util.List;
public class AccumulatorBlock extends DirectionalBlock implements IBE<AccumulatorBlockEntity> {
public class AccumulatorBlock extends TFMGDirectionalBlock implements IBE<AccumulatorBlockEntity> {
public AccumulatorBlock(Properties p_49795_) {
super(p_49795_);
}
public BlockState getStateForPlacement(BlockPlaceContext pContext) {
return this.defaultBlockState().setValue(FACING, pContext.getClickedFace());
}
@Override
public void setPlacedBy(Level level, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
@@ -69,20 +74,36 @@ public class AccumulatorBlock extends DirectionalBlock implements IBE<Accumulato
}
@Override
public void onPlace(BlockState pState, Level level, BlockPos pos, BlockState pOldState, boolean pIsMoving) {
withBlockEntityDo(level, pos, IElectric::onPlaced);
public void onNeighborChange(BlockState state, LevelReader level, BlockPos pos, BlockPos neighbor) {
withBlockEntityDo(level,pos,AccumulatorBlockEntity::refreshMultiblock);
super.onNeighborChange(state, level, pos, neighbor);
}
@Override
public void onPlace(BlockState state, Level level, BlockPos pos, BlockState blockState1, boolean a) {
withBlockEntityDo(level,pos, IElectric::onPlaced);
withBlockEntityDo(level,pos,b->b.refreshNextTick =true);
super.onPlace(state, level, pos, blockState1, a);
}
@Override
public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
for(Direction direction : Direction.values()){
BlockPos neighborPos = pos.relative(direction);
if(level.getBlockState(pos).is(TFMGBlocks.ACCUMULATOR.get()))
withBlockEntityDo(level,neighborPos,AccumulatorBlockEntity::refreshMultiblock);
//
}
IBE.onRemove(state, level, pos, newState);
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(FACING);
}
@Override
public Class<AccumulatorBlockEntity> getBlockEntityClass() {

View File

@@ -5,6 +5,9 @@ import com.drmangotea.tfmg.base.TFMGUtils;
import com.drmangotea.tfmg.config.TFMGConfigs;
import com.drmangotea.tfmg.content.electricity.base.ElectricBlockEntity;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.electricity.utilities.converter.ConverterBlockEntity;
import com.drmangotea.tfmg.content.engines.base.AbstractEngineBlockEntity;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.simibubi.create.foundation.utility.Lang;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
@@ -27,22 +30,50 @@ import static net.minecraft.world.level.block.DirectionalBlock.FACING;
public class AccumulatorBlockEntity extends ElectricBlockEntity {
public final TFMGForgeEnergyStorage energy = createEnergyStorage();
public TFMGForgeEnergyStorage energy = createEnergyStorage(1);
private LazyOptional<IEnergyStorage> energyCapability = LazyOptional.empty();
public int length = 1;
boolean refreshNextTick = true;
public BlockPos controller = getBlockPos();
int signal;
boolean signalChanged;
public AccumulatorBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
}
energyCapability = LazyOptional.of(() -> energy);
}
@Override
public void lazyTick() {
super.lazyTick();
neighbourChanged();
}
public void neighbourChanged() {
if (!hasLevel())
return;
if(isController()){
int power = level.getBestNeighborSignal(worldPosition);
if (power != signal)
signalChanged = true;
}
if(level.getBlockEntity(controller) instanceof AccumulatorBlockEntity be) {
int power = level.getBestNeighborSignal(worldPosition);
if (power != be.signal)
be.signalChanged = true;
}
}
@Override
public boolean makeElectricityTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
if (isController())
Lang.text("Controller").forGoggles(tooltip);
Lang.text("Energy").add(Lang.number(getCapability(ForgeCapabilities.ENERGY).orElseGet(null).getEnergyStored())).forGoggles(tooltip);
Lang.number(energy.getMaxEnergyStored()).forGoggles(tooltip);
super.makeElectricityTooltip(tooltip, isPlayerSneaking);
// Lang.translate("multimeter.energy_usage")
// .add(Component.literal(TFMGUtils.formatUnits((int) getChargingRate(), "FE")))
// .style(ChatFormatting.GOLD)
// .forGoggles(tooltip, 1);
Lang.number(length).forGoggles(tooltip);
Lang.translate("multimeter.energy_stored")
.add(Component.literal(TFMGUtils.formatUnits((int) energy.getEnergyStored(), "FE")))
.style(ChatFormatting.GOLD)
@@ -52,55 +83,159 @@ public class AccumulatorBlockEntity extends ElectricBlockEntity {
.add(Component.literal(TFMGUtils.formatUnits(getData().networkResistance, "W")))
.style(ChatFormatting.LIGHT_PURPLE)
.forGoggles(tooltip, 1);
int energyToExtract = data.networkPowerGeneration == 0 ? getNetworkPowerUsage() : (int) Math.max(0, Math.max(((float) powerGeneration() / (float) data.networkPowerGeneration) * (float) getNetworkPowerUsage(), 0));
energyToExtract /= TFMGConfigs.common().machines.FEtoWattTickConversionRate.get();
Lang.text(" Power Usage: ")
.add(Lang.number(getPowerUsage() == 0 ? 0 : Math.max(0, Math.max(((float) powerGeneration() / (float) getPowerUsage()) * (float) getData().networkResistance, 0))))
.add(Lang.number(energyToExtract))
.style(ChatFormatting.LIGHT_PURPLE)
.forGoggles(tooltip, 1);
return true;
}
@Override
public void remove() {
super.remove();
refreshController();
}
@Override
public void onPlaced() {
super.onPlaced();
refreshController();
}
public void refreshController() {
Direction facing = getBlockState().getValue(FACING);
for (int i = 0; i < 15; i++) {
BlockPos pos = getBlockPos().relative(getBlockState().getValue(FACING), i);
if (level.getBlockEntity(pos) instanceof AccumulatorBlockEntity be && be.getBlockState().getValue(FACING) == facing &&
!(level.getBlockEntity(pos.relative(facing)) instanceof AccumulatorBlockEntity otherBE && otherBE.getBlockState().getValue(FACING) == facing)) {
be.refreshMultiblock();
}
}
}
public void refreshMultiblock() {
Direction facing = getBlockState().getValue(FACING);
refreshCapability();
if (!(level.getBlockEntity(getBlockPos().relative(facing)) instanceof AccumulatorBlockEntity be && be.getBlockState().getValue(FACING) == facing)) {
int newLength = 1;
controller = getBlockPos();
for (int i = 1; i < 15; i++) {
BlockPos pos = getBlockPos().relative(getBlockState().getValue(FACING).getOpposite(), i);
if (level.getBlockEntity(pos) instanceof AccumulatorBlockEntity otherBe && otherBe.getBlockState().getValue(FACING) == getBlockState().getValue(FACING)) {
otherBe.controller = this.getBlockPos();
otherBe.refreshCapability();
otherBe.length = 0;
otherBe.energy.setEnergy(0);
newLength++;
} else break;
}
length = newLength;
int oldEnergy = energy.getEnergyStored();
energy = createEnergyStorage(length);
energy.setEnergy(Math.min(oldEnergy,energy.getMaxEnergyStored()*length));
refreshCapability();
updateNextTick();
for (int i = 1; i < length; i++) {
BlockPos pos = getBlockPos().relative(getBlockState().getValue(FACING).getOpposite(), i);
if(level.getBlockEntity(pos) instanceof AccumulatorBlockEntity be){
be.refreshCapability();
be.sendStuff();
}
}
sendStuff();
}
}
public void refreshCapability() {
LazyOptional<IEnergyStorage> oldCap = energyCapability;
if (level.getBlockEntity(controller) instanceof AccumulatorBlockEntity be) {
energyCapability = LazyOptional.of(() -> be.energy);
} else energyCapability = LazyOptional.of(() -> energy);
oldCap.invalidate();
}
@Override
public @NotNull <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) {
if (cap == ForgeCapabilities.ENERGY && side == null) {
return energyCapability.cast();
} else if (cap == ForgeCapabilities.ENERGY && hasElectricitySlot(side)) {
return energyCapability.cast();
}
return super.getCapability(cap, side);
}
public boolean isController() {
return controller == getBlockPos();
}
public TFMGForgeEnergyStorage createEnergyStorage() {
return new TFMGForgeEnergyStorage(getMaxCapacity(), 99999) {
public TFMGForgeEnergyStorage createEnergyStorage(int multiplier) {
return new TFMGForgeEnergyStorage(getMaxCapacity()*multiplier, 10000) {
@Override
public void onEnergyChanged(int amount) {
public void onEnergyChanged(int amount, int oldAmount) {
if((oldAmount==0&&amount>0)||(this.energy==0)) {
updateNextTick();
}
sendStuff();
}
};
}
public void setCapacity(ItemStack stack) {
energy.setEnergy(stack.getOrCreateTag().getInt("Storage"));
}
protected void analogSignalChanged() {
if(!isController()) {
signal = level.getBestNeighborSignal(controller);
return;
}
int newSignal = 0;
for(int i = 0;i<length;i++){
BlockPos pos = getBlockPos().relative(getBlockState().getValue(FACING).getOpposite(),i);
newSignal = Math.max(newSignal,level.getBestNeighborSignal(pos));
}
updateNextTick();
signal = newSignal;
}
@Override
public void tick() {
super.tick();
//if(level.isClientSide)
// TFMG.LOGGER.debug("CLIENT: "+energy.getEnergyStored());
//if(!level.isClientSide)
// TFMG.LOGGER.debug("SERVER: "+energy.getEnergyStored());
if (getData().getVoltage() > TFMGConfigs.common().machines.accumulatorVoltage.get())
energy.receiveEnergy(getChargingRate(), false);
//
if (signalChanged) {
signalChanged = false;
analogSignalChanged();
}
if (!isController())
return;
if (refreshNextTick) {
refreshMultiblock();
refreshNextTick = false;
}
if (getData().getVoltage() > TFMGConfigs.common().machines.accumulatorVoltage.get() * length) {
energy.receiveEnergy((int) (getChargingRate() / TFMGConfigs.common().machines.FEtoWattTickConversionRate.get()), false);
return;
}
if (canPower()) {
energy.extractEnergy(data.networkPowerGeneration == 0 ? getNetworkPowerUsage() : (int) Math.max(0, Math.max(((float) powerGeneration() / (float) data.networkPowerGeneration) * (float) getNetworkPowerUsage(), 0)), false);
TFMG.LOGGER.debug("A " + energy.extractEnergy(data.networkPowerGeneration == 0 ? getNetworkPowerUsage() : (int) Math.max(0, Math.max(((float) powerGeneration() / (float) data.networkPowerGeneration) * (float) getNetworkPowerUsage(), 0)), true));
int energyToExtract = data.networkPowerGeneration == 0 ? getNetworkPowerUsage() : (int) Math.max(0, Math.max(((float) powerGeneration() / (float) data.networkPowerGeneration) * (float) getNetworkPowerUsage(), 0));
energyToExtract /= TFMGConfigs.common().machines.FEtoWattTickConversionRate.get();
energy.extractEnergy(Math.max(energyToExtract, 1), false);
if (energy.getEnergyStored() == 0)
updateNextTick();
}
@@ -110,42 +245,48 @@ public class AccumulatorBlockEntity extends ElectricBlockEntity {
@Override
protected void write(CompoundTag compound, boolean clientPacket) {
super.write(compound, clientPacket);
compound.putInt("ForgeEnergy", energy.getEnergyStored());
compound.putInt("Length", length);
}
@Override
protected void read(CompoundTag compound, boolean clientPacket) {
super.read(compound, clientPacket);
length = compound.getInt("Length");
//energy = createEnergyStorage(length);
energy.setEnergy(compound.getInt("ForgeEnergy"));
}
@Override
public float resistance() {
if (voltageGeneration() > 0)
return 0;
if (!isController())
return 0;
int power = 0;
for (IElectric member : getOrCreateElectricNetwork().members)
if (!(member instanceof AccumulatorBlockEntity))
if (!(member instanceof ConverterBlockEntity)&&!(member instanceof AccumulatorBlockEntity))
power += member.getPowerUsage();
if (energy.getEnergyStored() == getMaxCapacity() || getData().getVoltage() <= getOutputVoltage() || canPower() || getPowerPercentage() < 100)
if (energy.getEnergyStored() == getMaxCapacity() || getData().getVoltage() <= getOutputVoltage() || canPower())
return 0;
return Math.min(Math.max((data.networkPowerGeneration - power), 0), getMaxChargingRate());
return (float) (data.voltage * data.voltage) /Math.min(Math.max((data.networkPowerGeneration - power), 0), getMaxChargingRate());
}
public boolean canPower() {
return getData().networkResistance > 0 && (getData().getVoltage() <= getOutputVoltage()) && energy.getEnergyStored() > 0;
return getData().networkResistance > 0 && (getData().getVoltage() <= getOutputVoltage()) && energy.getEnergyStored() > 0&&signal ==0;
}
@Override
public void onLoad() {
super.onLoad();
energyCapability = LazyOptional.of(() -> energy);
}
public int getChargingRate() {
int chargingRate = Math.max((data.networkPowerGeneration - getNetworkPowerUsage()), 0);
if (energy.getEnergyStored() == getMaxCapacity() || getData().getVoltage() < getOutputVoltage() || canPower() || getPowerPercentage() < 100)
if (energy.getEnergyStored() == getMaxCapacity() || getData().getVoltage() < getOutputVoltage() || canPower())
return 0;
return Math.min(chargingRate, getMaxChargingRate());
}
@@ -171,16 +312,16 @@ public class AccumulatorBlockEntity extends ElectricBlockEntity {
return TFMGConfigs.common().machines.accumulatorChargingRate.get();
}
public double conversionRate() {
return TFMGConfigs.common().machines.FEtoWattTickConversionRate.get();
}
public int getOutputVoltage() {
return TFMGConfigs.common().machines.accumulatorVoltage.get();
return TFMGConfigs.common().machines.accumulatorVoltage.get() * length;
}
@Override
public int voltageGeneration() {
return canPower() ? getOutputVoltage() : 0;
}

View File

@@ -11,18 +11,21 @@ public abstract class TFMGForgeEnergyStorage extends EnergyStorage {
@Override
public int extractEnergy(int maxExtract, boolean simulate) {
int oldAmount = this.energy;
int extractedEnergy = super.extractEnergy(maxExtract, simulate);
if(extractedEnergy != 0) {
onEnergyChanged(maxExtract*-1);
onEnergyChanged(maxExtract*-1,oldAmount);
}
return extractedEnergy;
}
@Override
public int receiveEnergy(int maxReceive, boolean simulate) {
int oldAmount = this.energy;
int receiveEnergy = super.receiveEnergy(maxReceive, simulate);
if(receiveEnergy != 0) {
onEnergyChanged(receiveEnergy);
onEnergyChanged(receiveEnergy,oldAmount);
}
return receiveEnergy;
}
@@ -31,10 +34,10 @@ public abstract class TFMGForgeEnergyStorage extends EnergyStorage {
this.energy = energy;
if(energy>0)
onEnergyChanged(energy);
onEnergyChanged(energy,this.energy);
return 0;
}
public abstract void onEnergyChanged(int amount);
public abstract void onEnergyChanged(int amount,int oldAmount);
}

View File

@@ -0,0 +1,67 @@
package com.drmangotea.tfmg.content.electricity.utilities.converter;
import com.drmangotea.tfmg.base.TFMGHorizontalDirectionalBlock;
import com.drmangotea.tfmg.base.TFMGShapes;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
import com.simibubi.create.content.equipment.wrench.IWrenchable;
import com.simibubi.create.foundation.block.IBE;
import net.minecraft.core.BlockPos;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
public class ConverterBlock extends TFMGHorizontalDirectionalBlock implements IBE<ConverterBlockEntity>, IWrenchable {
public static final BooleanProperty INPUT = BooleanProperty.create("input");
public ConverterBlock(Properties p_54120_) {
super(p_54120_);
}
@Override
public void onPlace(BlockState pState, Level level, BlockPos pos, BlockState pOldState, boolean pIsMoving) {
withBlockEntityDo(level,pos, IElectric::onPlaced);
}
@Override
public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
IBE.onRemove(state, level, pos, newState);
}
@Override
public InteractionResult onWrenched(BlockState state, UseOnContext context) {
context.getLevel().setBlockAndUpdate(context.getClickedPos(), state.setValue(INPUT, !state.getValue(INPUT)));
playRotateSound(context.getLevel(), context.getClickedPos());
return InteractionResult.SUCCESS;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(INPUT);
}
@Override
public VoxelShape getShape(BlockState p_60555_, BlockGetter p_60556_, BlockPos p_60557_, CollisionContext p_60558_) {
return TFMGShapes.TRANSFORMER.get(p_60555_.getValue(FACING));
}
@Override
public Class<ConverterBlockEntity> getBlockEntityClass() {
return ConverterBlockEntity.class;
}
@Override
public BlockEntityType<? extends ConverterBlockEntity> getBlockEntityType() {
return TFMGBlockEntities.CONVERTER.get();
}
}

View File

@@ -0,0 +1,227 @@
package com.drmangotea.tfmg.content.electricity.utilities.converter;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.base.TFMGUtils;
import com.drmangotea.tfmg.config.TFMGConfigs;
import com.drmangotea.tfmg.content.electricity.base.ElectricBlockEntity;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.electricity.storage.AccumulatorBlockEntity;
import com.drmangotea.tfmg.content.electricity.storage.TFMGForgeEnergyStorage;
import com.drmangotea.tfmg.content.machinery.misc.winding_machine.WindingMachineBlockEntity;
import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour;
import com.simibubi.create.foundation.blockEntity.behaviour.ValueBoxTransform;
import com.simibubi.create.foundation.blockEntity.behaviour.scrollValue.ScrollValueBehaviour;
import com.simibubi.create.foundation.utility.Lang;
import com.simibubi.create.foundation.utility.VecHelper;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.energy.IEnergyStorage;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import java.util.List;
import static com.drmangotea.tfmg.content.electricity.utilities.converter.ConverterBlock.INPUT;
import static com.simibubi.create.content.kinetics.base.HorizontalKineticBlock.HORIZONTAL_FACING;
import static net.minecraft.world.level.block.HorizontalDirectionalBlock.FACING;
public class ConverterBlockEntity extends ElectricBlockEntity {
public final TFMGForgeEnergyStorage energy = createEnergyStorage();
private LazyOptional<IEnergyStorage> energyCapability = LazyOptional.empty();
protected ScrollValueBehaviour voltageGenerated;
public ConverterBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
energyCapability = LazyOptional.of(() -> energy);
}
public TFMGForgeEnergyStorage createEnergyStorage() {
return new TFMGForgeEnergyStorage(500000, 10000) {
@Override
public void onEnergyChanged(int amount, int a) {
sendStuff();
}
};
}
@Override
public void addBehaviours(List<BlockEntityBehaviour> behaviours) {
super.addBehaviours(behaviours);
int max = 250;
voltageGenerated = new ScrollValueBehaviour(Lang.translateDirect("creative_generator.voltage_generation"),
this, new ConverterValueBox());
voltageGenerated.between(1, max);
voltageGenerated.value = 20;
voltageGenerated.withCallback(i -> this.updateNextTick());
behaviours.add(voltageGenerated);
}
@Override
protected void write(CompoundTag compound, boolean clientPacket) {
super.write(compound, clientPacket);
compound.putInt("ForgeEnergy", energy.getEnergyStored());
}
public boolean isInput() {
return getBlockState().getValue(INPUT);
}
@Override
public @NotNull <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) {
if (cap == ForgeCapabilities.ENERGY && side == null) {
return energyCapability.cast();
} else if (cap == ForgeCapabilities.ENERGY && hasElectricitySlot(side.getOpposite())) {
return energyCapability.cast();
}
return super.getCapability(cap, side);
}
@Override
public boolean makeElectricityTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
Lang.text("Energy").add(Lang.number(getCapability(ForgeCapabilities.ENERGY).orElseGet(null).getEnergyStored())).forGoggles(tooltip);
Lang.number(energy.getMaxEnergyStored()).forGoggles(tooltip);
super.makeElectricityTooltip(tooltip, isPlayerSneaking);
Lang.translate("multimeter.energy_stored")
.add(Component.literal(TFMGUtils.formatUnits((int) energy.getEnergyStored(), "FE")))
.style(ChatFormatting.GOLD)
.forGoggles(tooltip, 1);
/////
Lang.text(" Usage: ")
.add(Component.literal(TFMGUtils.formatUnits(getData().networkResistance, "W")))
.style(ChatFormatting.LIGHT_PURPLE)
.forGoggles(tooltip, 1);
int energyToExtract = data.networkPowerGeneration == 0 ? getNetworkPowerUsage() : (int) Math.max(0, Math.max(((float) powerGeneration() / (float) data.networkPowerGeneration) * (float) getNetworkPowerUsage(), 0));
energyToExtract /= TFMGConfigs.common().machines.FEtoWattTickConversionRate.get();
Lang.text(" Power Usage: ")
.add(Lang.number(energyToExtract))
.style(ChatFormatting.LIGHT_PURPLE)
.forGoggles(tooltip, 1);
return true;
}
@Override
public float resistance() {
if (voltageGeneration() > 0)
return 0;
int power = 0;
for (IElectric member : getOrCreateElectricNetwork().members)
if (!(member instanceof ConverterBlockEntity) && !(member instanceof AccumulatorBlockEntity))
power += member.getPowerUsage();
if (energy.getEnergyStored() == getMaxCapacity() || getData().getVoltage() <= voltageGenerated.getValue() || canPower())
return 0;
return (float) (data.voltage * data.voltage) /Math.min(Math.max((data.networkPowerGeneration - power), 0), getMaxChargingRate());
}
public boolean canPower() {
if (getBlockState().getValue(INPUT))
return false;
return getData().networkResistance > 0 && (getData().getVoltage() <= voltageGenerated.getValue()) && energy.getEnergyStored() > 0;
}
public int getChargingRate() {
int chargingRate = Math.max((data.networkPowerGeneration - getNetworkPowerUsage()), 0);
if (energy.getEnergyStored() == getMaxCapacity() || getData().getVoltage() < voltageGenerated.getValue() || canPower())
return 0;
return Math.min(chargingRate, getMaxChargingRate());
}
@Override
public int powerGeneration() {
if (canPower()) {
return getData().networkResistance > 0 ? voltageGenerated.getValue() : 0;
}
return 0;
}
@Override
public void tick() {
super.tick();
if (getBlockState().getValue(INPUT)) {
if (getData().getVoltage() > TFMGConfigs.common().machines.accumulatorVoltage.get()) {
energy.receiveEnergy((int) (getChargingRate() / TFMGConfigs.common().machines.FEtoWattTickConversionRate.get()), false);
}
} else if (canPower()) {
int energyToExtract = data.networkPowerGeneration == 0 ? getNetworkPowerUsage() : (int) Math.max(0, Math.max(((float) powerGeneration() / (float) data.networkPowerGeneration) * (float) getNetworkPowerUsage(), 0));
energyToExtract /= TFMGConfigs.common().machines.FEtoWattTickConversionRate.get();
energy.extractEnergy(Math.max(energyToExtract, 1), false);
if (energy.getEnergyStored() == 0)
updateNextTick();
}
}
public int getMaxCapacity() {
return TFMGConfigs.common().machines.accumulatorStorage.get();
}
//in FE per tick
public int getMaxChargingRate() {
return TFMGConfigs.common().machines.accumulatorChargingRate.get()*10;
}
@Override
public int voltageGeneration() {
return canPower() ? voltageGenerated.getValue() : 0;
}
@Override
protected void read(CompoundTag compound, boolean clientPacket) {
super.read(compound, clientPacket);
energy.setEnergy(compound.getInt("ForgeEnergy"));
}
@Override
public boolean hasElectricitySlot(Direction direction) {
return direction == getBlockState().getValue(FACING).getClockWise();
}
public static class ConverterValueBox extends ValueBoxTransform.Sided {
@Override
protected Vec3 getSouthLocation() {
return VecHelper.voxelSpace(8, 3, 16.05);
}
@Override
protected boolean isSideActive(BlockState state, Direction direction) {
return direction.getAxis() == state.getValue(HORIZONTAL_FACING).getAxis();
}
}
}

View File

@@ -0,0 +1,42 @@
package com.drmangotea.tfmg.content.electricity.utilities.converter;
import com.simibubi.create.foundation.data.SpecialBlockStateGen;
import com.tterrag.registrate.providers.DataGenContext;
import com.tterrag.registrate.providers.RegistrateBlockstateProvider;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.HorizontalDirectionalBlock;
import net.minecraft.world.level.block.StairBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.Half;
import net.minecraftforge.client.model.generators.ModelFile;
import static com.simibubi.create.foundation.data.AssetLookup.partialBaseModel;
public class ConverterGenerator extends SpecialBlockStateGen {
@Override
protected int getXRotation(BlockState state) {
return 0;
}
@Override
protected int getYRotation(BlockState state) {
return switch (state.getValue(HorizontalDirectionalBlock.FACING)) {
case NORTH -> 0;
case SOUTH -> 180;
case WEST -> 270;
case EAST -> 90;
case DOWN -> 90;
case UP -> 90;
};
}
@Override
public <T extends Block> ModelFile getModel(DataGenContext<Block, T> ctx, RegistrateBlockstateProvider prov,
BlockState state) {
return state.getValue(ConverterBlock.INPUT) ? partialBaseModel(ctx, prov, "rotated")
: partialBaseModel(ctx, prov);
}
}

View File

@@ -44,6 +44,19 @@ public class ElectricDiodeBlockEntity extends VoltageAlteringBlockEntity {
}
}
@Override
public int getPowerUsage() {
Direction facing = getDirection();
if (level.getBlockEntity(getBlockPos().relative(facing)) instanceof IElectric be && be.getData().getId() != data.getId()) {
if (be.hasElectricitySlot(facing.getOpposite()))
return Math.max(be.getNetworkPowerUsage(this), 0);
}
return 0;
}
@Override
public float resistance() {

View File

@@ -1,9 +1,10 @@
package com.drmangotea.tfmg.content.electricity.utilities.electric_motor;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.config.MachineConfig;
import com.drmangotea.tfmg.config.TFMGConfigs;
import com.drmangotea.tfmg.content.electricity.base.KineticElectricBlockEntity;
import com.electronwill.nightconfig.core.Config;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.jozufozu.flywheel.util.transform.TransformStack;
import com.mojang.blaze3d.vertex.PoseStack;
import com.simibubi.create.content.kinetics.motor.KineticScrollValueBehaviour;
@@ -43,38 +44,61 @@ public class ElectricMotorBlockEntity extends KineticElectricBlockEntity {
generatedSpeed.between(-max, max);
generatedSpeed.value = DEFAULT_SPEED;
generatedSpeed.withCallback(i -> this.updateGeneratedRotation());
generatedSpeed.withCallback(i ->this.updateNextTick());
behaviours.add(generatedSpeed);
}
@Override
public void updateNetwork() {
super.updateNetwork();
updateGeneratedRotation();
public boolean hasElectricitySlot(Direction direction) {
return direction == getBlockState().getValue(FACING).getOpposite()||(direction.getAxis().isHorizontal()&&direction == Direction.DOWN);
}
@Override
public void onNetworkChanged(int oldVoltage, int oldPower) {
updateGeneratedRotation();
if(oldPower!=getPowerUsage()||oldVoltage!=data.voltage) {
updateGeneratedRotation();
}
}
@Override
public float getGeneratedSpeed() {
MachineConfig machineConfig = TFMGConfigs.common().machines;
if(getPowerUsage() >= machineConfig.electricMotorMinimumPower.get()&&getData().getVoltage()>=machineConfig.electricMotorMinimumVoltage.get()&&getPowerPercentage()>0){
return Math.min(generatedSpeed.getValue(),getData().getVoltage())*((float) getPowerPercentage() /100);
//if(getPowerUsage() <machineConfig.electricMotorMinimumPower.get())
// return 0;
}
//if(getPowerUsage() >= machineConfig.electricMotorMinimumPower.get()){
return 0;
return Math.min(Math.abs(generatedSpeed.getValue()),data.getVoltage()/2);
//}
//return 0;
}
@Override
public boolean canBeInGroups() {
return true;
}
@Override
public float resistance() {
return (int) (13 * Math.min(generatedSpeed.getValue(),getData().getVoltage())*TFMGConfigs.common().machines.electricMotorPowerUsageModifier.get());
return TFMGConfigs.common().machines.electricMotorInternalResistance.getF();
}
@Override
public int getPowerUsage() {
if(Math.min(generatedSpeed.getValue(),data.getVoltage()/2) ==0)
return super.getPowerUsage();
float speedModifier = (Math.min(Math.abs(generatedSpeed.getValue()),data.getVoltage())/256f)*5;
return (int) ((float)super.getPowerUsage()* speedModifier);
}
class MotorValueBox extends ValueBoxTransform.Sided {

View File

@@ -1,6 +1,8 @@
package com.drmangotea.tfmg.content.electricity.utilities.electric_pump;
import com.drmangotea.tfmg.base.TFMGShapes;
import com.drmangotea.tfmg.content.electricity.base.ConnectNeightborsPacket;
import com.drmangotea.tfmg.content.electricity.base.ElectricBlockEntity;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
import com.drmangotea.tfmg.registry.TFMGPackets;
@@ -8,9 +10,12 @@ import com.simibubi.create.content.fluids.pump.PumpBlock;
import com.simibubi.create.content.fluids.pump.PumpBlockEntity;
import com.simibubi.create.foundation.block.IBE;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.network.PacketDistributor;
public class ElectricPumpBlock extends PumpBlock {
@@ -22,13 +27,21 @@ public class ElectricPumpBlock extends PumpBlock {
//@Override
//public void onPlace(BlockState pState, Level level, BlockPos pos, BlockState pOldState, boolean pIsMoving) {
// withBlockEntityDo(level,pos, IElectric::onPlaced);
//}
@Override
public void onPlace(BlockState pState, Level level, BlockPos pos, BlockState pOldState, boolean pIsMoving) {
super.onPlace(pState, level, pos, pOldState, pIsMoving);
withBlockEntityDo(level,pos, be->((ElectricPumpBlockEntity)be).onPlaced());
}
@Override
public VoxelShape getShape(BlockState state, BlockGetter p_220053_2_, BlockPos p_220053_3_, CollisionContext p_220053_4_) {
return TFMGShapes.ELECTRIC_PUMP.get(state.getValue(FACING));
}
@Override
public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
super.onRemove(state,level,pos,newState,isMoving);
IBE.onRemove(state, level, pos, newState);
}
@@ -39,7 +52,6 @@ public class ElectricPumpBlock extends PumpBlock {
@Override
public BlockEntityType<? extends PumpBlockEntity> getBlockEntityType() {
return TFMGBlockEntities.ELECTRIC_PUMP.get();

View File

@@ -41,10 +41,8 @@ public class ElectricPumpBlockEntity extends PumpBlockEntity implements IElectri
super(typeIn, pos, state);
setLazyTickRate(10);
data.connectNextTick = true;
}
@Override
public void addBehaviours(List<BlockEntityBehaviour> behaviours) {
@@ -139,7 +137,6 @@ public class ElectricPumpBlockEntity extends PumpBlockEntity implements IElectri
Map<Integer, Set<BlockFace>> validFaces = new HashMap<>();
searchForEndpointRecursively(pipeGraph, targets, validFaces,
new BlockFace(start.getPos(), start.getOppositeFace()), pull);
float pressure = getPowerUsage() == 0 ? 0 : Math.min(1500,data.getVoltage()*2);
for (Set<BlockFace> set : validFaces.values()) {
int parallelBranches = Math.max(1, set.size() - 1);
@@ -199,19 +196,17 @@ public class ElectricPumpBlockEntity extends PumpBlockEntity implements IElectri
boolean isFront = side == front;
return isFront;
}
//////////////////////
@Override
public boolean addToTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
return makeElectricityTooltip(tooltip, isPlayerSneaking);
}
@Override
public LevelAccessor getLevelAccessor(){
public LevelAccessor getLevelAccessor() {
return level;
}
@@ -222,15 +217,26 @@ public class ElectricPumpBlockEntity extends PumpBlockEntity implements IElectri
@Override
public ElectricalNetwork getOrCreateElectricNetwork() {
if(level.getBlockEntity(BlockPos.of(network)) instanceof IElectric) {
return TFMG.NETWORK_MANAGER.getOrCreateNetworkFor((IElectric) level.getBlockEntity(BlockPos.of(network)));
if (level.getBlockEntity(BlockPos.of(data.electricalNetworkId)) instanceof IElectric) {
return TFMG.NETWORK_MANAGER.getOrCreateNetworkFor((IElectric) level.getBlockEntity(BlockPos.of(data.electricalNetworkId)));
} else {
ElectricNetworkManager.networks.get(getLevel())
.remove(network);
.remove(data.electricalNetworkId);
return TFMG.NETWORK_MANAGER.getOrCreateNetworkFor(this);
}
}
@Override
public void lazyTick() {
super.lazyTick();
}
@Override
public ElectricBlockValues getData() {
return data;
}
@Override
public int getPowerPercentage() {
return powerPercentage;
@@ -238,28 +244,30 @@ public class ElectricPumpBlockEntity extends PumpBlockEntity implements IElectri
@Override
public float resistance() {
return 0;
return 50;
}
@Override
public int voltageGeneration() {
int voltageGeneration = 0;
for(Direction direction : Direction.values()){
if(hasElectricitySlot(direction)){
if(level.getBlockEntity(getBlockPos().relative(direction)) instanceof VoltageAlteringBlockEntity be)
if(be.data.getId() !=data.getId())
if(be.data.getVoltage()!=0)
if(be.hasElectricitySlot(direction)){
voltageGeneration = Math.max(voltageGeneration,be.getOutputVoltage());
for (Direction direction : Direction.values()) {
if (hasElectricitySlot(direction)) {
if (level.getBlockEntity(getBlockPos().relative(direction)) instanceof VoltageAlteringBlockEntity be)
if (be.getData().getId() != getData().getId())
if (be.getData().getVoltage() != 0)
if (be.hasElectricitySlot(direction)) {
voltageGeneration = Math.max(voltageGeneration, be.getOutputVoltage());
data.getsOutsidePower = true;
}
}
}
if(voltageGeneration == 0)
if (voltageGeneration == 0)
data.getsOutsidePower = false;
return voltageGeneration;
@@ -270,15 +278,16 @@ public class ElectricPumpBlockEntity extends PumpBlockEntity implements IElectri
int powerGeneration = 0;
for(Direction direction : Direction.values()){
if(hasElectricitySlot(direction)){
for (Direction direction : Direction.values()) {
if (hasElectricitySlot(direction)) {
if(level.getBlockEntity(getBlockPos().relative(direction)) instanceof VoltageAlteringBlockEntity be)
if(be.data.getId() !=data.getId())
if(be.data.getVoltage()!=0)
if(be.hasElectricitySlot(direction)){
powerGeneration = Math.max(powerGeneration,be.getOutputPower());
if (level.getBlockEntity(getBlockPos().relative(direction)) instanceof VoltageAlteringBlockEntity be) {
if (be.getData().getId() != getData().getId())
if (be.getData().getVoltage() != 0)
if (be.hasElectricitySlot(direction)) {
powerGeneration = Math.max(powerGeneration, be.getPowerUsage()) + 1;
}
}
}
}
@@ -290,7 +299,6 @@ public class ElectricPumpBlockEntity extends PumpBlockEntity implements IElectri
return 0;
}
@Override
public void updateNextTick() {
data.updateNextTick = true;
@@ -299,7 +307,7 @@ public class ElectricPumpBlockEntity extends PumpBlockEntity implements IElectri
@Override
public void updateNetwork() {
getOrCreateElectricNetwork().updateNetwork();
if(!level.isClientSide)
if (!level.isClientSide)
TFMGPackets.getChannel().send(PacketDistributor.ALL.noArg(), new NetworkUpdatePacket(BlockPos.of(getPos())));
sendData();
}
@@ -311,6 +319,12 @@ public class ElectricPumpBlockEntity extends PumpBlockEntity implements IElectri
@Override
public void setVoltage(int newVoltage) {
if (canBeInGroups()) {
data.voltage = (int) (((float) resistance() / data.group.resistance) * (float) data.voltageSupply);
return;
}
data.voltage = newVoltage;
}
@@ -340,17 +354,15 @@ public class ElectricPumpBlockEntity extends PumpBlockEntity implements IElectri
@Override
public void setNetwork(long network) {
this.network = network;
if(network!=getPos())
this.data.electricalNetworkId = network;
if (network != getPos())
ElectricNetworkManager.networks.get(getLevel())
.remove(getPos());
}
@Override
public long getPos() {
return getBlockPos().asLong();
@@ -359,69 +371,61 @@ public class ElectricPumpBlockEntity extends PumpBlockEntity implements IElectri
@Override
public void remove() {
super.remove();
this.data.destroyed = true;
for(Direction d : Direction.values()) {
if(hasElectricitySlot(d))
if(getLevelAccessor().getBlockEntity(BlockPos.of(getPos()).relative(d)) instanceof IElectric be&&be.hasElectricitySlot(d.getOpposite())) {
for (Direction d : Direction.values()) {
if (hasElectricitySlot(d))
if (getLevelAccessor().getBlockEntity(BlockPos.of(getPos()).relative(d)) instanceof IElectric be && be.hasElectricitySlot(d.getOpposite())) {
ElectricNetworkManager.networks.get(getLevel())
.remove(be.getPos());
be.setNetwork(be.getPos());
be.onPlaced();
be.updateNetwork();
be.updateNextTick();
}
}
if(network != getPos())
if (data.electricalNetworkId != getPos())
getOrCreateElectricNetwork().getMembers().remove(this);
if(network == getPos())
if (data.electricalNetworkId == getPos())
ElectricNetworkManager.networks.get(getLevel())
.remove(data.getId());
.remove(getData().getId());
}
@Override
public void tick() {
super.tick();
if(data.connectNextTick) {
if (data.connectNextTick) {
onPlaced();
data.connectNextTick = false;
}
if(data.updateNextTick) {
if (data.updateNextTick) {
updateNetwork();
data.updateNextTick = false;
}
if (data.setVoltageNextTick) {
setVoltage(data.voltageSupply);
data.setVoltageNextTick = false;
}
}
@Override
protected void write(CompoundTag tag, boolean clientPacket) {
super.write(tag, clientPacket);
protected void write(CompoundTag compound, boolean clientPacket) {
super.write(compound, clientPacket);
compound.putInt("GroupId", data.group.id);
compound.putFloat("GroupResistance", data.group.resistance);
}
@Override
protected void read(CompoundTag tag, boolean clientPacket) {
super.read(tag, clientPacket);
if(!clientPacket)
protected void read(CompoundTag compound, boolean clientPacket) {
super.read(compound, clientPacket);
data.group = new ElectricalGroup(compound.getInt("GroupId"));
data.group.resistance = compound.getFloat("GroupResistance");
if (!clientPacket)
data.connectNextTick = true;
}
@Override
public boolean hasElectricitySlot(Direction direction) {
return direction.getAxis() != getBlockState().getValue(FACING).getAxis();
}
@Override
public ElectricBlockValues getData() {
return data;
}
/// ////////////////
class ElectricPumpTransferBehavior extends FluidTransportBehaviour {
public ElectricPumpTransferBehavior(SmartBlockEntity be) {
@@ -452,7 +456,5 @@ public class ElectricPumpBlockEntity extends PumpBlockEntity implements IElectri
return AttachmentTypes.NONE;
return attachment;
}
}
}

View File

@@ -1,23 +1,23 @@
package com.drmangotea.tfmg.content.electricity.utilities.electrical_switch;
package com.drmangotea.tfmg.content.electricity.utilities.electric_switch;
import com.drmangotea.tfmg.base.TFMGHorizontalDirectionalBlock;
import com.drmangotea.tfmg.base.TFMGDirectionalBlock;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.electricity.base.IVoltageChanger;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
import com.drmangotea.tfmg.registry.TFMGPackets;
import com.simibubi.create.foundation.block.IBE;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.network.PacketDistributor;
public class ElectricalSwitchBlock extends TFMGHorizontalDirectionalBlock implements IBE<ElectricalSwitchBlockEntity> {
public ElectricalSwitchBlock(Properties p_54120_) {
public class ElectricSwitchBlock extends TFMGDirectionalBlock implements IBE<ElectricSwitchBlockEntity>, IVoltageChanger {
public ElectricSwitchBlock(Properties p_54120_) {
super(p_54120_);
}
@Override
public void onPlace(BlockState pState, Level level, BlockPos pos, BlockState pOldState, boolean pIsMoving) {
withBlockEntityDo(level,pos, IElectric::onPlaced);
withBlockEntityDo(level, pos, IElectric::onPlaced);
}
@Override
@@ -26,15 +26,13 @@ public class ElectricalSwitchBlock extends TFMGHorizontalDirectionalBlock implem
}
@Override
public Class<ElectricalSwitchBlockEntity> getBlockEntityClass() {
return ElectricalSwitchBlockEntity.class;
@Override
public Class<ElectricSwitchBlockEntity> getBlockEntityClass() {
return ElectricSwitchBlockEntity.class;
}
@Override
public BlockEntityType<? extends ElectricalSwitchBlockEntity> getBlockEntityType() {
return TFMGBlockEntities.ELECTRICAL_SWITCH.get();
public BlockEntityType<? extends ElectricSwitchBlockEntity> getBlockEntityType() {
return TFMGBlockEntities.ELECTRIC_SWITCH.get();
}
}

View File

@@ -1,30 +1,29 @@
package com.drmangotea.tfmg.content.electricity.utilities.electrical_switch;
package com.drmangotea.tfmg.content.electricity.utilities.electric_switch;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.electricity.utilities.diode.ElectricDiodeBlockEntity;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import static net.minecraft.world.level.block.HorizontalDirectionalBlock.FACING;
import static net.minecraft.world.level.block.DirectionalBlock.FACING;
public class ElectricalSwitchBlockEntity extends ElectricDiodeBlockEntity {
public class ElectricSwitchBlockEntity extends ElectricDiodeBlockEntity {
int signal;
boolean signalChanged;
public ElectricalSwitchBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
public ElectricSwitchBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
}
@Override
public void lazyTick() {
super.lazyTick();
neighbourChanged();
}
@Override
@@ -38,10 +37,12 @@ public class ElectricalSwitchBlockEntity extends ElectricDiodeBlockEntity {
}
protected void analogSignalChanged(int newSignal) {
signal = newSignal;
updateNetwork();
updateNextTick();
updateInFrontNextTick();
}
public void neighbourChanged() {
if (!hasLevel())
return;

View File

@@ -30,6 +30,8 @@ public class FuseBlockEntity extends ElectricDiodeBlockEntity {
public ItemStack fuse = ItemStack.EMPTY;
boolean testFuse = false;
public FuseBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
@@ -58,6 +60,7 @@ public class FuseBlockEntity extends ElectricDiodeBlockEntity {
be.updateNextTick();
}
}
sendStuff();
setChanged();
}
@@ -79,7 +82,12 @@ public class FuseBlockEntity extends ElectricDiodeBlockEntity {
public void onNetworkChanged(int oldVoltage, int oldPower) {
super.onNetworkChanged(oldVoltage, oldPower);
if (hasFuse() && getData().highestCurrent >= (float) fuse.getOrCreateTag().getInt("AmpRating")) {
blowFuse();
updateNetwork();
updateInFront();
}
Direction facing = getBlockState().getValue(FACING).getCounterClockWise();
if (level.getBlockEntity(getBlockPos().relative(facing)) instanceof IElectric be) {
@@ -92,6 +100,8 @@ public class FuseBlockEntity extends ElectricDiodeBlockEntity {
}
}
@Override
public void setVoltage(int newVoltage) {
super.setVoltage(newVoltage);
@@ -105,15 +115,50 @@ public class FuseBlockEntity extends ElectricDiodeBlockEntity {
}
}
if (hasFuse() && getData().highestCurrent >= (float) fuse.getOrCreateTag().getInt("AmpRating")) {
blowFuse();
updateNetwork();
updateInFront();
}
testFuse = true;
}
public void testFuse(){
Direction facing = getBlockState().getValue(FACING).getCounterClockWise();
if (level.getBlockEntity(getBlockPos().relative(facing)) instanceof IElectric be) {
if (hasFuse() && be.getData().highestCurrent >= (float) fuse.getOrCreateTag().getInt("AmpRating")) {
blowFuse();
updateNetwork();
updateInFront();
}
}
if (hasFuse() && getData().highestCurrent >= (float) fuse.getOrCreateTag().getInt("AmpRating")) {
blowFuse();
updateNetwork();
updateInFront();
}
testFuse = true;
}
@Override
public void tick() {
super.tick();
if(testFuse){
testFuse();
testFuse = false;
}
Direction facing = getBlockState().getValue(FACING).getCounterClockWise();
if (level.getBlockEntity(getBlockPos().relative(facing)) instanceof IElectric be) {
// TFMG.LOGGER.debug("AMPS " + be.getData().highestCurrent);
TFMG.LOGGER.debug("AMPS " + be.getData().highestCurrent);
}
}

View File

@@ -38,10 +38,8 @@ public class PolarizerBlockEntity extends ElectricBlockEntity {
LerpedFloat angle = LerpedFloat.angular();
public boolean shouldChargeItem = false;
public boolean chargeCapacitors = false;
public int capacitorPercentage = 0;
boolean charged = false;
public PolarizerBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
@@ -54,8 +52,9 @@ public class PolarizerBlockEntity extends ElectricBlockEntity {
}
public void onInventoryChanged(int count) {
sendData();
setChanged();
if (inventory.isEmpty()) {
shouldChargeItem = false;
chargeCapacitors = false;
updateNextTick();
return;
@@ -63,29 +62,22 @@ public class PolarizerBlockEntity extends ElectricBlockEntity {
ItemStack itemStack = inventory.getItem(0);
if (getRecipe(itemStack).isPresent()) {
shouldChargeItem = false;
TFMGUtils.debugMessage(level, "AMOGUS SIGMA");
chargeCapacitors = true;
updateNextTick();
if (capacitorPercentage == 200) {
if (capacitorPercentage >= 200) {
performRecipe(getRecipe(itemStack).get());
}
} else if (itemStack.getCapability(ForgeCapabilities.ENERGY).isPresent()) {
shouldChargeItem = true;
chargeCapacitors = false;
updateNextTick();
} else {
shouldChargeItem = false;
chargeCapacitors = false;
updateNextTick();
}
}
//@Override
//public boolean canBeInGroups() {
// return true;
//}
//
@Override
public float resistance() {
return chargeCapacitors ? 30 : 0;
@@ -98,8 +90,6 @@ public class PolarizerBlockEntity extends ElectricBlockEntity {
Lang.number((double) capacitorPercentage / 2f).forGoggles(tooltip);
if (chargeCapacitors)
Lang.text("CAPACITOR").forGoggles(tooltip);
if (shouldChargeItem)
Lang.text("ITEM").forGoggles(tooltip);
super.addToTooltip(tooltip, isPlayerSneaking);
@@ -114,20 +104,21 @@ public class PolarizerBlockEntity extends ElectricBlockEntity {
@Override
public void tick() {
super.tick();
if (level.isClientSide) {
angle.chase(180 * (capacitorPercentage / 200f), 0.2f, LerpedFloat.Chaser.EXP);
angle.tickChaser();
}
if (!networkUndersupplied())
if (getPowerUsage() > 5000)
if (chargeCapacitors)
if (!charged) {
if (capacitorPercentage < 200) {
capacitorPercentage++;
} else onInventoryChanged(inventory.getStackInSlot(0).getCount());
charged = true;
} else charged = false;
if (getPowerUsage() > 2000) {
if (chargeCapacitors) {
if (capacitorPercentage < 200) {
capacitorPercentage++;
} else onInventoryChanged(inventory.getStackInSlot(0).getCount());
}
}
}
@@ -159,7 +150,6 @@ public class PolarizerBlockEntity extends ElectricBlockEntity {
super.write(compound, clientPacket);
compound.put("Inventory", inventory.serializeNBT());
compound.putInt("CapacitorPercentage", capacitorPercentage);
compound.putBoolean("ChargeItem", shouldChargeItem);
compound.putBoolean("ChargeCapacitors", chargeCapacitors);
}
@@ -168,7 +158,6 @@ public class PolarizerBlockEntity extends ElectricBlockEntity {
super.read(compound, clientPacket);
inventory.deserializeNBT(compound.getCompound("Inventory"));
capacitorPercentage = compound.getInt("CapacitorPercentage");
shouldChargeItem = compound.getBoolean("ChargeItem");
chargeCapacitors = compound.getBoolean("ChargeCapacitors");
}

View File

@@ -1,8 +1,11 @@
package com.drmangotea.tfmg.content.electricity.utilities.potentiometer;
import com.drmangotea.tfmg.base.TFMGHorizontalDirectionalBlock;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.electricity.utilities.diode.ElectricDiodeBlockEntity;
import com.jozufozu.flywheel.util.transform.TransformStack;
import com.mojang.blaze3d.vertex.PoseStack;
import com.simibubi.create.content.kinetics.base.DirectionalKineticBlock;
import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour;
import com.simibubi.create.foundation.blockEntity.behaviour.ValueBoxTransform;
import com.simibubi.create.foundation.blockEntity.behaviour.scrollValue.ScrollValueBehaviour;
@@ -11,6 +14,7 @@ import com.simibubi.create.foundation.utility.Lang;
import com.simibubi.create.foundation.utility.VecHelper;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.block.DirectionalBlock;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
@@ -31,7 +35,7 @@ public class PotentiometerBlockEntity extends ElectricDiodeBlockEntity {
super.addBehaviours(behaviours);
int max = 100;
outputPercentage = new ScrollValueBehaviour(Lang.translateDirect("resistor.allowed_voltage"),
this, new ResistorValueBox());
this, new PotentiometerValueBox());
outputPercentage.between(0, max);
outputPercentage.value = 100;
outputPercentage.withCallback(i ->this.updateNextTick());
@@ -40,35 +44,39 @@ public class PotentiometerBlockEntity extends ElectricDiodeBlockEntity {
}
@Override
public int getPowerUsage() {
return (int) (((float)super.getPowerUsage()/100)* outputPercentage.getValue());
public Direction getDirection(){
if(!getBlockState().hasProperty(DirectionalBlock.FACING)){
return getBlockState().getValue(TFMGHorizontalDirectionalBlock.FACING).getCounterClockWise();
}
return getBlockState().getValue(DirectionalBlock.FACING);
}
@Override
public int getOutputVoltage() {
return (int) (((float)getData().getVoltage()/100)* outputPercentage.getValue());
}
@Override
public int getOutputPower() {
return getPowerUsage();
}
class ResistorValueBox extends ValueBoxTransform.Sided {
static class PotentiometerValueBox extends ValueBoxTransform.Sided {
@Override
protected Vec3 getSouthLocation() {
return VecHelper.voxelSpace(8, 8, 12.5);
}
@Override
public Vec3 getLocalOffset(BlockState state) {
Direction facing = state.getValue(FACING);
Direction facing = state.getValue(DirectionalKineticBlock.FACING);
return super.getLocalOffset(state).add(Vec3.atLowerCornerOf(facing.getNormal())
.scale(-1 / 16f));
}
@Override
public void rotate(BlockState state, PoseStack ms) {
super.rotate(state, ms);
Direction facing = state.getValue(FACING);
Direction facing = state.getValue(DirectionalKineticBlock.FACING);
if (facing.getAxis() == Direction.Axis.Y)
return;
if (getSide() != Direction.UP)
@@ -76,13 +84,17 @@ public class PotentiometerBlockEntity extends ElectricDiodeBlockEntity {
TransformStack.cast(ms)
.rotateZ(-AngleHelper.horizontalAngle(facing) + 180);
}
@Override
protected boolean isSideActive(BlockState state, Direction direction) {
Direction facing = state.getValue(FACING);
if (direction!=Direction.UP)
return false;
return direction.getAxis() != facing.getAxis();
Direction facing = state.getValue(DirectionalKineticBlock.FACING);
if (facing.getAxis().isVertical()) {
return direction.getAxis().isHorizontal();
} else return direction == Direction.UP;
}
}
}

View File

@@ -0,0 +1,30 @@
package com.drmangotea.tfmg.content.electricity.utilities.resistor;
import com.simibubi.create.foundation.utility.Lang;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.util.List;
public class ResistorItem extends Item {
public ResistorItem(Properties p_40566_) {
super(p_40566_);
}
@Override
@OnlyIn(Dist.CLIENT)
public void appendHoverText(ItemStack stack, Level world, List<Component> tooltip, TooltipFlag flag) {
tooltip.add(Lang.translateDirect("tooltip.resistor", stack.getOrCreateTag().getInt("Resistance")).append("Ω")
.withStyle(ChatFormatting.GREEN)
);
super.appendHoverText(stack, world, tooltip, flag);
}
}

View File

@@ -1,6 +1,7 @@
package com.drmangotea.tfmg.content.electricity.utilities.transformer;
import com.drmangotea.tfmg.base.TFMGHorizontalDirectionalBlock;
import com.drmangotea.tfmg.base.TFMGShapes;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.electricity.base.IVoltageChanger;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
@@ -11,10 +12,13 @@ import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
public class TransformerBlock extends TFMGHorizontalDirectionalBlock implements IBE<TransformerBlockEntity>, IVoltageChanger {
public TransformerBlock(Properties p_54120_) {
@@ -22,6 +26,11 @@ public class TransformerBlock extends TFMGHorizontalDirectionalBlock implements
}
@Override
public VoxelShape getShape(BlockState p_60555_, BlockGetter p_60556_, BlockPos p_60557_, CollisionContext p_60558_) {
return TFMGShapes.TRANSFORMER.get(p_60555_.getValue(FACING));
}
@Override
public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult p_60508_) {

View File

@@ -1,5 +1,6 @@
package com.drmangotea.tfmg.content.electricity.utilities.transformer;
import com.drmangotea.tfmg.base.TFMGHorizontalDirectionalBlock;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.electricity.base.VoltageAlteringBlockEntity;
import com.simibubi.create.foundation.utility.Lang;
@@ -48,6 +49,20 @@ public class TransformerBlockEntity extends VoltageAlteringBlockEntity {
}
}
@Override
public int getPowerUsage() {
Direction facing = getDirection();
if (level.getBlockEntity(getBlockPos().relative(facing)) instanceof IElectric be && be.getData().getId() != data.getId()) {
if (be.hasElectricitySlot(facing.getOpposite()))
return Math.max(be.getNetworkPowerUsage(this), 0);
}
return 0;
}
@Override
public boolean makeElectricityTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
super.makeElectricityTooltip(tooltip, isPlayerSneaking);
@@ -98,9 +113,14 @@ public class TransformerBlockEntity extends VoltageAlteringBlockEntity {
}
return 0;
}
public int getPowerUsage() {
return (int) ((float)super.getPowerUsage()* coilRatio);
public Direction getDirection(){
if(!getBlockState().hasProperty(DirectionalBlock.FACING)){
return getBlockState().getValue(TFMGHorizontalDirectionalBlock.FACING).getCounterClockWise();
}
return getBlockState().getValue(DirectionalBlock.FACING);
}
@Override
public boolean hasElectricitySlot(Direction direction) {
return direction == getBlockState().getValue(FACING).getClockWise();

View File

@@ -15,25 +15,28 @@ import static net.minecraft.world.level.block.HorizontalDirectionalBlock.FACING;
public class TransformerRenderer extends SafeBlockEntityRenderer<TransformerBlockEntity> {
public TransformerRenderer(BlockEntityRendererProvider.Context context){}
public TransformerRenderer(BlockEntityRendererProvider.Context context) {
}
@Override
protected void renderSafe(TransformerBlockEntity be, float partialTicks, PoseStack ms, MultiBufferSource bufferSource, int light, int overlay) {
BlockState blockState = be.getBlockState();
if(!be.primaryCoil.isEmpty()) {
if (!be.primaryCoil.isEmpty()) {
CachedBufferer.partial(TFMGPartialModels.TRANSFORMER_COIL, blockState)
.centre()
.rotateY(blockState.getValue(HORIZONTAL_FACING).getAxis() == Direction.Axis.Z ? Math.abs(blockState.getValue(FACING).toYRot() - 180) : blockState.getValue(FACING).toYRot())
.light(light)
.translateX(0.5)
.unCentre()
.renderInto(ms, bufferSource.getBuffer(RenderType.cutoutMipped()));
}
if(!be.secondaryCoil.isEmpty()) {
if (!be.secondaryCoil.isEmpty()) {
CachedBufferer.partial(TFMGPartialModels.TRANSFORMER_COIL, blockState)
.light(light)
.centre()
.rotateY(blockState.getValue(HORIZONTAL_FACING).getAxis() == Direction.Axis.Z ? Math.abs(blockState.getValue(FACING).toYRot() - 180) : blockState.getValue(FACING).toYRot())
.rotateY(blockState.getValue(HORIZONTAL_FACING).getAxis() == Direction.Axis.Z ? Math.abs(blockState.getValue(FACING).toYRot() - 180) : blockState.getValue(FACING).toYRot())
.unCentre()
.renderInto(ms, bufferSource.getBuffer(RenderType.cutoutMipped()));
}

View File

@@ -1,38 +0,0 @@
package com.drmangotea.tfmg.content.electricity.utilities.transistor;
import com.drmangotea.tfmg.base.TFMGHorizontalDirectionalBlock;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
import com.simibubi.create.foundation.block.IBE;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
public class TransistorBlock extends TFMGHorizontalDirectionalBlock implements IBE<TransistorBlockEntity> {
public TransistorBlock(Properties p_54120_) {
super(p_54120_);
}
@Override
public void onPlace(BlockState pState, Level level, BlockPos pos, BlockState pOldState, boolean pIsMoving) {
withBlockEntityDo(level,pos, IElectric::onPlaced);
}
@Override
public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
IBE.onRemove(state, level, pos, newState);
}
@Override
public Class<TransistorBlockEntity> getBlockEntityClass() {
return TransistorBlockEntity.class;
}
@Override
public BlockEntityType<? extends TransistorBlockEntity> getBlockEntityType() {
return TFMGBlockEntities.TRANSISTOR.get();
}
}

View File

@@ -1,35 +0,0 @@
package com.drmangotea.tfmg.content.electricity.utilities.transistor;
import com.drmangotea.tfmg.content.electricity.utilities.diode.ElectricDiodeBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import static net.minecraft.world.level.block.HorizontalDirectionalBlock.FACING;
public class TransistorBlockEntity extends ElectricDiodeBlockEntity {
public TransistorBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
}
public int findBestVoltage(){
return 0;
}
@Override
public int getOutputVoltage() {
return (int) (data.getVoltage()*(findBestVoltage()/100f));
}
@Override
public boolean hasElectricitySlot(Direction direction) {
return direction == getBlockState().getValue(FACING).getOpposite();
}
}

View File

@@ -29,7 +29,7 @@ public class VoltageObserverBlockEntity extends ElectricBlockEntity {
}
public int getComparatorOutput() {
return ComparatorUtil.fractionToRedstoneLevel((double) getData().getVoltage() /1000);
return ComparatorUtil.fractionToRedstoneLevel((double) getData().getVoltage() /250);
}
@Override

View File

@@ -0,0 +1,43 @@
package com.drmangotea.tfmg.content.engines;
import com.simibubi.create.foundation.utility.Lang;
import net.minecraft.ChatFormatting;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.util.List;
public class CylinderItem extends Item {
public CylinderItem(Properties p_41383_) {
super(p_41383_);
}
@Override
@OnlyIn(Dist.CLIENT)
public void appendHoverText(ItemStack stack, Level world, List<Component> tooltip, TooltipFlag flag) {
super.appendHoverText(stack, world, tooltip, flag);
CompoundTag fuels = stack.getOrCreateTag().getCompound("FuelNames");
if(fuels.isEmpty())
return;
tooltip.add(Lang.translateDirect("tooltip.cylinder")
.withStyle(ChatFormatting.GRAY));
for(String key : fuels.getAllKeys()) {
tooltip.add(Lang.text("- "+fuels.getString(key)).component()
.withStyle(ChatFormatting.AQUA));
}
}
}

View File

@@ -3,19 +3,27 @@ package com.drmangotea.tfmg.content.engines;
import com.drmangotea.tfmg.content.items.weapons.flamethrover.FlamethrowerItem;
import com.drmangotea.tfmg.registry.TFMGItems;
import com.simibubi.create.content.fluids.tank.FluidTankBlockEntity;
import com.simibubi.create.foundation.utility.Lang;
import com.tterrag.registrate.util.entry.FluidEntry;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler;
import java.util.List;
public class FluidContainingItem extends Item {
public final FluidEntry<?> fluid;
@@ -26,7 +34,14 @@ public class FluidContainingItem extends Item {
super(p_41383_);
this.fluid = fluid;
}
@Override
@OnlyIn(Dist.CLIENT)
public void appendHoverText(ItemStack stack, Level world, List<Component> tooltip, TooltipFlag flag) {
tooltip.add(Lang.translateDirect("tooltip.fluid_item", stack.getOrCreateTag().getInt("amount"))
.withStyle(ChatFormatting.GREEN)
);
super.appendHoverText(stack, world, tooltip, flag);
}
@Override
public InteractionResult useOn(UseOnContext context) {

View File

@@ -1,13 +1,19 @@
package com.drmangotea.tfmg.content.engines.base;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.base.TFMGUtils;
import com.drmangotea.tfmg.config.TFMGConfigs;
import com.drmangotea.tfmg.content.engines.FluidContainingItem;
import com.drmangotea.tfmg.content.electricity.base.KineticElectricBlockEntity;
import com.drmangotea.tfmg.content.engines.fuels.BaseFuelTypes;
import com.drmangotea.tfmg.content.engines.fuels.EngineFuelTypeManager;
import com.drmangotea.tfmg.content.engines.fuels.FuelType;
import com.drmangotea.tfmg.content.engines.regular_engine.RegularEngineBlockEntity;
import com.drmangotea.tfmg.content.engines.upgrades.EnginePipingUpgrade;
import com.drmangotea.tfmg.content.engines.upgrades.EngineUpgrade;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.drmangotea.tfmg.registry.TFMGFluids;
import com.drmangotea.tfmg.registry.TFMGItems;
import com.simibubi.create.AllBlocks;
import com.simibubi.create.content.kinetics.base.KineticBlockEntity;
import com.simibubi.create.foundation.fluid.CombinedTankWrapper;
import com.simibubi.create.foundation.utility.Lang;
import com.simibubi.create.foundation.utility.VecHelper;
@@ -18,6 +24,7 @@ import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.tags.TagKey;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
@@ -27,52 +34,62 @@ import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.templates.FluidTank;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import static com.drmangotea.tfmg.content.engines.base.EngineBlock.ENGINE_STATE;
import static com.drmangotea.tfmg.content.engines.base.EngineBlock.EngineState.NORMAL;
import static com.drmangotea.tfmg.content.engines.base.EngineBlock.EngineState.SHAFT;
import static com.simibubi.create.content.kinetics.base.HorizontalKineticBlock.HORIZONTAL_FACING;
public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
public abstract class AbstractEngineBlockEntity extends KineticElectricBlockEntity {
//
public EngineComponentsInventory componentsInventory;
public FluidTank fuelTank;
public FluidTank exhaustTank;
public EngineFluidTank fuelTank;
public EngineFluidTank exhaustTank;
public LazyOptional<IFluidHandler> fluidCapability;
//
public BlockPos controller = getBlockPos();
boolean connectNextTick = true;
List<Long> engines = new ArrayList<>();
int engineNumber = 0;
public List<Long> engines = new ArrayList<>();
public int engineNumber = 0;
//
int oil = 0;
int coolingFluid =0;
int coolingFluid = 0;
//
float rpm =0;
public float rpm = 0;
float torque = 0;
float fuelInjectionRate = 0;
//
boolean reverse = false;
//
int highestSignal;
int signal;
boolean signalChanged;
//
int fuelConsumptionTimer = 0;
//
public Optional<? extends EngineUpgrade> upgrade = Optional.empty();
public AbstractEngineBlockEntity(BlockEntityType<?> typeIn, BlockPos pos, BlockState state) {
super(typeIn, pos, state);
setLazyTickRate(10);
fuelTank = TFMGUtils.createTank(4000, false, this::tankUpdated);
exhaustTank = TFMGUtils.createTank(4000, true, false, this::tankUpdated);
fuelTank = new EngineFluidTank(4000, false, true, this::tankUpdated);
exhaustTank = new EngineFluidTank(8000, true, false, this::tankUpdated);
fluidCapability = LazyOptional.of(() -> new CombinedTankWrapper(fuelTank, exhaustTank));
componentsInventory = new EngineComponentsInventory(this, EngineProperties.commonRegularComponents());
@@ -80,14 +97,24 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
refreshCapability();
}
public boolean hasUpgrade() {
return upgrade.isPresent();
}
public void tankUpdated(FluidStack stack) {
if (stack.getFluid().isSame(TFMGFluids.CARBON_DIOXIDE.get()) && stack.getAmount() >= exhaustTank.getSpace())
updateRotation();
sendData();
setChanged();
}
public boolean hasAllComponents(){
if(level.getBlockEntity(controller) instanceof AbstractEngineBlockEntity be){
public boolean hasAllComponents() {
if (level.getBlockEntity(controller) instanceof AbstractEngineBlockEntity be) {
return be.nextComponent() == Ingredient.EMPTY;
}
@@ -98,6 +125,59 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
public void lazyTick() {
super.lazyTick();
neighbourChanged();
upgrade.ifPresent(engineUpgrade -> engineUpgrade.lazyTickUpgrade(this));
exhaustTank.forceFill(new FluidStack(TFMGFluids.CARBON_DIOXIDE.get(), Math.min(300, getFuelConsumption() * 7)), IFluidHandler.FluidAction.EXECUTE);
if (fuelConsumptionTimer <= 2) {
fuelConsumptionTimer++;
} else {
fuelConsumptionTimer = 0;
fuelTank.forceDrain(getFuelConsumption(), IFluidHandler.FluidAction.EXECUTE);
if (fuelTank.isEmpty())
updateRotation();
}
}
@Override
public int voltageGeneration() {
if (upgrade.isPresent() && upgrade.get().getItem() == TFMGBlocks.GENERATOR.asItem())
return (int) (20 * (rpm / 3000));
return 0;
}
@Override
public int powerGeneration() {
if (upgrade.isPresent() && upgrade.get().getItem() == TFMGBlocks.GENERATOR.asItem())
return (int) rpm;
return 0;
}
@Override
public boolean makeElectricityTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
return false;
}
public int getFuelConsumption() {
if (getGeneratedSpeed() == 0)
return 0;
return (int) (12.5f * (1 / efficiencyModifier()) * getSpeedEfficiency() * fuelInjectionRate) * engineLength();
}
public float getSpeedEfficiency() {
if (rpm >= 6000)
return 1;
return 1 / (0.08f * (rpm / 1000) + 0.5f);
}
public Ingredient nextComponent() {
@@ -112,20 +192,92 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
return Ingredient.EMPTY;
}
public void onUpdated(){}
public abstract List<TagKey<Fluid>> getSupportedFuels();
public void updateRotation(){
public void onUpdated() {
}
if(!canWork()||!isController()){
rpm = 0;
public void updateRotation() {
if (!isController()) {
if (level.getBlockEntity(controller) instanceof AbstractEngineBlockEntity be)
be.updateRotation();
return;
}
rpm = 4000*speedModifier()*fuelInjectionRate;
List<Long> allEngines = new ArrayList<>(engines);
allEngines.add(controller.asLong());
for (TagKey<Fluid> fluidTag : getSupportedFuels()) {
if (fuelTank.getFluid().getFluid().is(fluidTag)) {
if (!canWork()) {
allEngines.forEach(l -> {
BlockPos pos = BlockPos.of(l);
if (level.getBlockEntity(pos) instanceof AbstractEngineBlockEntity be) {
be.rpm = 0;
be.torque = 0;
be.updateGeneratedRotation();
}
});
return;
}
allEngines.forEach(l -> {
BlockPos pos = BlockPos.of(l);
if (level.getBlockEntity(pos) instanceof AbstractEngineBlockEntity be) {
be.rpm = 4000 * speedModifier() * fuelInjectionRate;
be.torque = 15 * torqueModifier() * fuelInjectionRate * engineLength();
be.updateGeneratedRotation();
}
});
return;
}
}
updateGeneratedRotation();
getAllEngines().forEach(l -> {
if (hasLevel())
if (level.getBlockEntity(BlockPos.of(l)) instanceof AbstractEngineBlockEntity be) {
be.updateGeneratedRotation();
}
});
}
public boolean canWork(){
if(!nextComponent().isEmpty())
@Override
public float getGeneratedSpeed() {
float speed;
if (getBlockState().getValue(ENGINE_STATE) != SHAFT)
return 0;
if (hasLevel())
if (level.getBlockEntity(controller) instanceof AbstractEngineBlockEntity controller) {
if (controller.fuelTank.isEmpty())
return 0;
if (!controller.canWork())
return 0;
speed = rpm / 23;
if (reverse)
speed = speed * -1;
return convertToDirection(Math.min((int) speed, 256), getBlockState().getValue(HORIZONTAL_FACING));
}
return 0;
}
public boolean canWork() {
if (exhaustTank.getSpace() == 0)
return false;
if (!nextComponent().isEmpty())
return false;
return true;
@@ -134,8 +286,7 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
@Override
public void tick() {
super.tick();
upgrade.ifPresent(engineUpgrade -> engineUpgrade.tickUpgrade(this));
if (connectNextTick) {
connect();
connectNextTick = false;
@@ -148,27 +299,29 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
protected void analogSignalChanged() {
int newSignal = level.getBestNeighborSignal(controller);
int newSignal = level.getBestNeighborSignal(getBlockPos());
for(long posLong : engines){
signal = newSignal;
if (!isController()) {
if (level.getBlockEntity(controller) instanceof AbstractEngineBlockEntity be) {
be.analogSignalChanged();
return;
}
}
for (long posLong : engines) {
BlockPos pos = BlockPos.of(posLong);
newSignal = Math.max(level.getBestNeighborSignal(pos), newSignal);
}
if(isController()){
signal = newSignal;
fuelInjectionRate = signal / 15f;
updateRotation();
}
if(level.getBlockEntity(controller) instanceof AbstractEngineBlockEntity be) {
newSignal = Math.max(level.getBestNeighborSignal(controller), newSignal);
highestSignal = newSignal;
fuelInjectionRate = highestSignal / 15f;
updateRotation();
be.signal = newSignal;
be.fuelInjectionRate = signal / 15f;
be.updateRotation();
}
}
public abstract int effectiveSpeed();
public abstract float efficiencyModifier();
@@ -179,6 +332,21 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
public abstract String engineId();
public FuelType getFuelType() {
AtomicReference<FuelType> matchingType = new AtomicReference<>(BaseFuelTypes.FALLBACK);
EngineFuelTypeManager.GLOBAL_TYPE_MAP.forEach((r, t) -> {
TagKey<Fluid> fluidTag = t.getFluid();
FluidStack fluid = fuelTank.getFluid();
if (fluid.getFluid().is(fluidTag)) {
matchingType.set(t);
}
});
return matchingType.get();
}
private void refreshCapability() {
LazyOptional<IFluidHandler> oldCap = fluidCapability;
fluidCapability = LazyOptional.of(this::handlerForCapability);
@@ -204,13 +372,15 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
return TFMGConfigs.common().machines.engineMaxLength.get();
}
public boolean insertItem(ItemStack itemStack, boolean shifting, Player player, InteractionHand hand) {
Direction facing = getBlockState().getValue(HORIZONTAL_FACING);
if (itemStack.is(AllBlocks.SHAFT.asItem()) && getBlockState().getValue(ENGINE_STATE) == NORMAL && !(level.getBlockEntity(getBlockPos().relative(facing)) instanceof AbstractEngineBlockEntity)) {
playInsertionSound();
level.setBlock(getBlockPos(), getBlockState().setValue(ENGINE_STATE, SHAFT), 2);
itemStack.shrink(1);
updateRotation();
setChanged();
sendData();
return true;
@@ -221,45 +391,67 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
dropItem(componentsInventory.getItem(i));
componentsInventory.setStackInSlot(i, ItemStack.EMPTY);
playRemovalSound();
updateRotation();
setChanged();
sendData();
return true;
}
}
}
if(itemStack.is(TFMGItems.COOLING_FLUID_BOTTLE.get())){
int toDrain = Math.min(2000-coolingFluid,itemStack.getOrCreateTag().getInt("amount"));
itemStack.getOrCreateTag().putInt("amount",itemStack.getOrCreateTag().getInt("amount")-toDrain);
coolingFluid+=toDrain;
level.playSound(null, getBlockPos(), SoundEvents.BUCKET_FILL, SoundSource.BLOCKS, 1f, 1f);
return true;
}
if(itemStack.is(TFMGItems.OIL_CAN.get())){
int toDrain = Math.min(2000-oil,itemStack.getOrCreateTag().getInt("amount"));
itemStack.getOrCreateTag().putInt("amount",itemStack.getOrCreateTag().getInt("amount")-toDrain);
oil+=toDrain;
level.playSound(null, getBlockPos(), SoundEvents.BUCKET_FILL, SoundSource.BLOCKS, 1f, 1f);
return true;
}
if(itemStack.is(TFMGFluids.COOLING_FLUID.getBucket().get())){
if(coolingFluid<=1000){
coolingFluid+=1000;
player.setItemInHand(hand, Items.BUCKET.getDefaultInstance());
if (itemStack.is(TFMGItems.COOLING_FLUID_BOTTLE.get())) {
if (level.getBlockEntity(controller) instanceof AbstractEngineBlockEntity be) {
int toDrain = Math.min(2000 - coolingFluid, itemStack.getOrCreateTag().getInt("amount"));
itemStack.getOrCreateTag().putInt("amount", itemStack.getOrCreateTag().getInt("amount") - toDrain);
be.coolingFluid += toDrain;
level.playSound(null, getBlockPos(), SoundEvents.BUCKET_FILL, SoundSource.BLOCKS, 1f, 1f);
return true;
}
}
if(itemStack.is(TFMGFluids.LUBRICATION_OIL.getBucket().get())){
if(oil<=1000){
oil+=1000;
player.setItemInHand(hand, Items.BUCKET.getDefaultInstance());
if (itemStack.is(TFMGItems.OIL_CAN.get())) {
if (level.getBlockEntity(controller) instanceof AbstractEngineBlockEntity be) {
int toDrain = Math.min(2000 - oil, itemStack.getOrCreateTag().getInt("amount"));
itemStack.getOrCreateTag().putInt("amount", itemStack.getOrCreateTag().getInt("amount") - toDrain);
be.oil += toDrain;
level.playSound(null, getBlockPos(), SoundEvents.BUCKET_FILL, SoundSource.BLOCKS, 1f, 1f);
updateRotation();
return true;
}
}
if (itemStack.is(TFMGFluids.COOLING_FLUID.getBucket().get())) {
if (coolingFluid <= 1000) {
coolingFluid += 1000;
player.setItemInHand(hand, Items.BUCKET.getDefaultInstance());
level.playSound(null, getBlockPos(), SoundEvents.BUCKET_FILL, SoundSource.BLOCKS, 1f, 1f);
updateRotation();
return true;
}
}
if (itemStack.is(TFMGFluids.LUBRICATION_OIL.getBucket().get())) {
if (oil <= 1000) {
oil += 1000;
player.setItemInHand(hand, Items.BUCKET.getDefaultInstance());
level.playSound(null, getBlockPos(), SoundEvents.BUCKET_FILL, SoundSource.BLOCKS, 1f, 1f);
updateRotation();
return true;
}
}
if (EngineUpgrade.getUpgrades().containsKey(itemStack.getItem())) {
Optional<? extends EngineUpgrade> itemUpgrade = EngineUpgrade.getUpgrades().get(itemStack.getItem()).createUpgrade();
if (itemUpgrade.isPresent() && isUpgradeFirst(itemUpgrade.get())) {
upgrade = itemUpgrade;
playInsertionSound();
updateRotation();
upgrade.ifPresent(u->u.updateUpgrade(this));
itemStack.shrink(1);
setChanged();
sendData();
return true;
}
}
if (!isController())
@@ -269,6 +461,7 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
if (!itemStack.is(TFMGItems.SCREWDRIVER.get()))
itemStack.shrink(1);
playInsertionSound();
updateRotation();
setChanged();
sendData();
return true;
@@ -277,6 +470,33 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
return false;
}
public boolean isUpgradeFirst(EngineUpgrade itemUpgrade) {
for (AbstractEngineBlockEntity be : getEngines()) {
if (be.upgrade.isPresent() && be.upgrade.get().getItem() == itemUpgrade.getItem())
return false;
}
return true;
}
public List<Long> getAllEngines() {
List<Long> list = new ArrayList<>(engines);
list.add(controller.asLong());
return list;
}
public void changeDirection() {
playInsertionSound();
reverse = !reverse;
updateRotation();
}
public void dropItem(ItemStack stack) {
Vec3 dropVec = VecHelper.getCenterOf(worldPosition).add(0, 0.3f, 0);
ItemEntity dropped = new ItemEntity(level, dropVec.x, dropVec.y, dropVec.z, stack);
@@ -297,10 +517,22 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
level.playSound(null, getBlockPos(), SoundEvents.ITEM_PICKUP, SoundSource.BLOCKS, 0.4f, 0.5f);
}
@Override
public void onLoad() {
super.onLoad();
if(this.hasUpgrade()&&this.upgrade.get().getItem() == TFMGBlocks.INDUSTRIAL_PIPE.asItem()){
((EnginePipingUpgrade)this.upgrade.get()).findTank(this);
}
}
@Override
protected void read(CompoundTag compound, boolean clientPacket) {
super.read(compound, clientPacket);
controller = BlockPos.of(compound.getLong("Controller"));
reverse = compound.getBoolean("Reverse");
if (EngineUpgrade.getUpgrades().get(ItemStack.of(compound.getCompound("UpgradeItem")).getItem()) != null)
upgrade = Optional.of(EngineUpgrade.getUpgrades().get(ItemStack.of(compound.getCompound("UpgradeItem")).getItem()));
if (isController()) {
componentsInventory.deserializeNBT(compound.getCompound("Components"));
fuelTank.readFromNBT(compound.getCompound("FuelTank"));
@@ -314,11 +546,14 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
protected void write(CompoundTag compound, boolean clientPacket) {
super.write(compound, clientPacket);
compound.putLong("Controller", controller.asLong());
compound.putBoolean("Reverse", reverse);
if (upgrade.isPresent())
compound.put("UpgradeItem", upgrade.get().getItem().getDefaultInstance().serializeNBT());
if (isController()) {
compound.put("Components", componentsInventory.serializeNBT());
compound.put("FuelTank", fuelTank.writeToNBT(new CompoundTag()));
compound.put("ExhaustTank", exhaustTank.writeToNBT(new CompoundTag()));
compound.putInt("Oil",oil);
compound.putInt("Oil", oil);
compound.putInt("CoolingFluid", coolingFluid);
}
}
@@ -329,8 +564,12 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
@Override
public boolean addToGoggleTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
Lang.number(fuelInjectionRate).forGoggles(tooltip);
Lang.text("Speed Efficiency " + getSpeedEfficiency()).forGoggles(tooltip);
Lang.text("Efficiency " + efficiencyModifier()).forGoggles(tooltip);
Lang.text("Fuel Consumption " + getFuelConsumption()).forGoggles(tooltip);
Lang.text("Rpm " + rpm).forGoggles(tooltip);
Lang.text("Torque " + torque).forGoggles(tooltip);
Lang.text("Injection Rate " + fuelInjectionRate).forGoggles(tooltip);
Lang.number(rpm).style(ChatFormatting.AQUA).forGoggles(tooltip);
@@ -369,26 +608,19 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
}
}
}
//
public void neighbourChanged() {
if (!hasLevel())
return;
if(isController()){
int power = level.getBestNeighborSignal(worldPosition);
int power = level.getBestNeighborSignal(getBlockPos());
if (power != signal)
signalChanged = true;
}
if(level.getBlockEntity(controller) instanceof AbstractEngineBlockEntity be) {
int power = level.getBestNeighborSignal(worldPosition);
if (power != this.signal)
this.signalChanged = true;
if (power != be.signal)
be.signalChanged = true;
}
}
//
public void connect() {
Direction updateDirection = getBlockState().getValue(HORIZONTAL_FACING).getAxis() == Direction.Axis.X ? Direction.WEST : Direction.NORTH;
@@ -403,7 +635,7 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
if (level.getBlockEntity(pos) instanceof AbstractEngineBlockEntity be) {
if (be.getBlockState().getValue(HORIZONTAL_FACING).getAxis() != updateDirection.getAxis())
return;
if(be instanceof RegularEngineBlockEntity be1&&this instanceof RegularEngineBlockEntity be2 && be1.type!=be2.type)
if (be instanceof RegularEngineBlockEntity be1 && this instanceof RegularEngineBlockEntity be2 && be1.type != be2.type)
return;
be.detashEngines();
engines.add(pos.asLong());
@@ -411,12 +643,12 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
be.engines = new ArrayList<>();
be.controller = getBlockPos();
be.refreshCapability();
if(i>0)
if (i > 0)
level.setBlock(pos, be.getBlockState().setValue(HORIZONTAL_FACING, i > 0 ? updateDirection.getOpposite() : updateDirection), 2);
onUpdated();
be.sendData();
be.setChanged();
if (be.getBlockState().getValue(ENGINE_STATE) != NORMAL&&i!=0) {
if (be.getBlockState().getValue(ENGINE_STATE) != NORMAL && i != 0) {
break;
}
} else return;
@@ -441,4 +673,44 @@ public abstract class AbstractEngineBlockEntity extends KineticBlockEntity {
}
public List<AbstractEngineBlockEntity> getEngines() {
List<AbstractEngineBlockEntity> values = new ArrayList<>();
for (Long position : getAllEngines()) {
BlockPos pos = BlockPos.of(position);
if (level.getBlockEntity(pos) instanceof AbstractEngineBlockEntity be)
values.add(be);
}
return values;
}
public float getUpgradeSpeedModifier() {
float modifier = 1;
for (AbstractEngineBlockEntity be : getEngines()) {
if (be.upgrade.isPresent())
modifier *= be.upgrade.get().getSpeedModifier(this);
}
return modifier;
}
public float getUpgradeTorqueModifier() {
float modifier = 1;
for (AbstractEngineBlockEntity be : getEngines()) {
if (be.upgrade.isPresent())
modifier *= be.upgrade.get().getTorqueModifier(this);
}
return modifier;
}
public float getUpgradeEfficiencyModifier() {
float modifier = 1;
for (AbstractEngineBlockEntity be : getEngines()) {
if (be.upgrade.isPresent())
modifier *= be.upgrade.get().getEfficiencyModifier(this);
}
return modifier;
}
}

View File

@@ -1,6 +1,9 @@
package com.drmangotea.tfmg.content.engines.base;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.base.TFMGShapes;
import com.drmangotea.tfmg.content.engines.upgrades.EnginePipingUpgrade;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.simibubi.create.AllBlocks;
import com.simibubi.create.content.kinetics.base.HorizontalKineticBlock;
import net.minecraft.core.BlockPos;
@@ -9,13 +12,11 @@ import net.minecraft.util.StringRepresentable;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.RenderShape;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.EnumProperty;
@@ -23,6 +24,8 @@ import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import java.util.Optional;
import static com.drmangotea.tfmg.content.engines.base.EngineBlock.EngineState.NORMAL;
import static com.drmangotea.tfmg.content.engines.base.EngineBlock.EngineState.SHAFT;
@@ -39,16 +42,30 @@ public class EngineBlock extends HorizontalKineticBlock {
public InteractionResult onWrenched(BlockState state, UseOnContext context) {
Level level = context.getLevel();
BlockPos pos = context.getClickedPos();
if (level.getBlockEntity(pos) instanceof AbstractEngineBlockEntity be)
if (level.getBlockEntity(pos) instanceof AbstractEngineBlockEntity be) {
if(be.hasUpgrade()){
be.playRemovalSound();
be.dropItem(be.upgrade.get().getItem().getDefaultInstance());
be.upgrade = Optional.empty();
be.updateRotation();
return InteractionResult.SUCCESS;
}
if (state.getValue(ENGINE_STATE) == SHAFT) {
be.playRemovalSound();
be.dropItem(AllBlocks.SHAFT.asStack());
level.setBlock(pos, state.setValue(ENGINE_STATE, NORMAL), 2);
be.connectNextTick = true;
be.detachKinetics();
if (be.getOrCreateNetwork() != null)
be.getOrCreateNetwork().remove(be);
be.setChanged();
be.sendData();
return InteractionResult.SUCCESS;
}
}
return InteractionResult.PASS;
}
@@ -78,6 +95,17 @@ public class EngineBlock extends HorizontalKineticBlock {
builder.add(ENGINE_STATE);
}
@Override
public void neighborChanged(BlockState state, Level level, BlockPos pos, Block block, BlockPos neighbor, boolean b) {
if(level.getBlockEntity(pos) instanceof AbstractEngineBlockEntity be){
if(be.hasUpgrade()&&be.upgrade.get().getItem() == TFMGBlocks.INDUSTRIAL_PIPE.asItem()){
((EnginePipingUpgrade)be.upgrade.get()).findTank(be);
}
}
super.neighborChanged(state, level, pos, block, neighbor, b);
}
@Override

View File

@@ -0,0 +1,52 @@
package com.drmangotea.tfmg.content.engines.base;
import com.simibubi.create.foundation.fluid.SmartFluidTank;
import net.minecraft.world.level.material.Fluid;
import net.minecraftforge.fluids.FluidStack;
import java.util.function.Consumer;
public class EngineFluidTank extends SmartFluidTank {
final boolean extractionAllowed;
final boolean insertionAllowed;
public EngineFluidTank(int capacity, boolean extractionAllowed, boolean insertionAllowed, Consumer<FluidStack> updateCallback) {
super(capacity, updateCallback);
this.extractionAllowed = extractionAllowed;
this.insertionAllowed = insertionAllowed;
}
@Override
public FluidStack drain(FluidStack resource, FluidAction action) {
if (!extractionAllowed) return FluidStack.EMPTY;
return super.drain(resource, action);
}
public FluidStack forceDrain(FluidStack resource, FluidAction action){
return super.drain(resource,action);
}
public FluidStack forceDrain(int resource, FluidAction action){
return super.drain(resource,action);
}
@Override
public FluidStack drain(int maxDrain, FluidAction action) {
if (!extractionAllowed) return FluidStack.EMPTY;
return super.drain(maxDrain, action);
}
public int forceFill(FluidStack resource, FluidAction action) {
return super.fill(resource, action);
}
@Override
public int fill(FluidStack resource, FluidAction action) {
if (!insertionAllowed) return 0;
return super.fill(resource, action);
}
}

View File

@@ -22,6 +22,12 @@ public class EngineRenderer extends KineticBlockEntityRenderer<AbstractEngineBlo
@Override
protected void renderSafe(AbstractEngineBlockEntity be, float partialTicks, PoseStack ms, MultiBufferSource buffer, int light, int overlay) {
if(be.hasUpgrade()){
be.upgrade.get().render(be, partialTicks, ms, buffer,light);
}
if(be.getBlockState().getValue(ENGINE_STATE) == EngineBlock.EngineState.SHAFT)
super.renderSafe(be, partialTicks, ms, buffer, light, overlay);
}

View File

@@ -1,13 +0,0 @@
package com.drmangotea.tfmg.content.engines.engine_block;
import com.drmangotea.tfmg.base.TFMGHorizontalDirectionalBlock;
import com.simibubi.create.content.kinetics.base.KineticBlock;
import net.minecraft.core.Direction;
import net.minecraft.world.level.block.state.BlockState;
public class EngineBlockBlock extends TFMGHorizontalDirectionalBlock {
public EngineBlockBlock(Properties properties) {
super(properties);
}
}

View File

@@ -0,0 +1,78 @@
package com.drmangotea.tfmg.content.engines.fuels;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.registry.TFMGTags;
public class BaseFuelTypes {
public static final FuelType
FALLBACK = create("fallback")
.speed(1)
.efficiency(1)
.stress(1)
.register(),
GASOLINE = create("gasoline")
.speed(1)
.efficiency(1)
.stress(1)
.registerAndAssign(TFMGTags.TFMGFluidTags.GASOLINE.tag),
DIESEL = create("diesel")
.speed(0.8f)
.efficiency(0.8f)
.stress(1.4f)
.registerAndAssign(TFMGTags.TFMGFluidTags.DIESEL.tag),
LPG = create("lpg")
.speed(1.2f)
.efficiency(0.7f)
.stress(0.7f)
.registerAndAssign(TFMGTags.TFMGFluidTags.LPG.tag),
KEROSENE = create("kerosene")
.speed(0.7f)
.efficiency(1f)
.stress(1.4f)
.registerAndAssign(TFMGTags.TFMGFluidTags.KEROSENE.tag),
NAPHTHA = create("naphtha")
.speed(1f)
.efficiency(0.7f)
.stress(1.3f)
.registerAndAssign(TFMGTags.TFMGFluidTags.NAPHTHA.tag),
//MAZUT = create("mazut")
// .speed(0)
// .efficiency(0)
// .stress(0)
// .registerAndAssign(TFMGTags.TFMGFluidTags.GAS.tag),
CREOSOTE = create("creosote")
.speed(0.7f)
.efficiency(0.4f)
.stress(0.5f)
.registerAndAssign(TFMGTags.TFMGFluidTags.CREOSOTE.tag),
//HYDROGEN = create("hydrogen")
// .speed(0)
// .efficiency(0)
// .stress(0)
// .registerAndAssign(TFMGTags.TFMGFluidTags.GAS.tag),
FURNACE_GAS = create("furnace_gas")
.speed(0.5f)
.efficiency(0.3f)
.stress(0.3f)
.registerAndAssign(TFMGTags.TFMGFluidTags.FURNACE_GAS.tag);
private static FuelType.Builder create(String name) {
return new FuelType.Builder(TFMG.asResource(name));
}
public static void register() {
}
}

View File

@@ -0,0 +1,189 @@
package com.drmangotea.tfmg.content.engines.fuels;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.registry.TFMGPackets;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.simibubi.create.foundation.networking.SimplePacketBase;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener;
import net.minecraft.tags.TagKey;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.world.level.material.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
public class EngineFuelTypeManager {
public static final Map<ResourceLocation, FuelType> BUILTIN_TYPE_MAP = new HashMap<>();
public static final Map<ResourceLocation, FuelType> CUSTOM_TYPE_MAP = new HashMap<>();
public static final Map<ResourceLocation, FuelType> GLOBAL_TYPE_MAP = new HashMap<>();
private static final Map<TagKey<Fluid>, FuelType> FLUID_TO_TYPE_MAP = new IdentityHashMap<>();
public static void registerBuiltinType(ResourceLocation id, FuelType type) {
synchronized (BUILTIN_TYPE_MAP) {
BUILTIN_TYPE_MAP.put(id, type);
}
synchronized (GLOBAL_TYPE_MAP) {
GLOBAL_TYPE_MAP.put(id, type);
}
}
public static FuelType getBuiltinType(ResourceLocation id) {
return BUILTIN_TYPE_MAP.get(id);
}
public static FuelType getCustomType(ResourceLocation id) {
return CUSTOM_TYPE_MAP.get(id);
}
public static FuelType getGlobalType(ResourceLocation id) {
return GLOBAL_TYPE_MAP.get(id);
}
public static FuelType getTypeForFluid(Fluid fluid) {
return FLUID_TO_TYPE_MAP.get(fluid);
}
public static FuelType getTypeForFluid(ResourceLocation fluidId) {
return getTypeForFluid(ForgeRegistries.FLUIDS.getValue(fluidId));
}
public static Optional<FuelType> getTypeForStack(FluidStack fluidStack) {
if (fluidStack.isEmpty())
return Optional.empty();
return Optional.ofNullable(getTypeForFluid(fluidStack.getFluid()));
}
public static ResourceLocation getIdForType(FuelType type) {
for (Map.Entry<ResourceLocation, FuelType> entry : GLOBAL_TYPE_MAP.entrySet()) {
if (entry.getValue() == type)
return entry.getKey();
}
return null;
}
public static FuelType getTypeForId(ResourceLocation id) {
for (Map.Entry<ResourceLocation, FuelType> entry : GLOBAL_TYPE_MAP.entrySet()) {
if (entry.getKey().equals(id))
return entry.getValue();
}
return null;
}
public static void clear() {
GLOBAL_TYPE_MAP.clear();
CUSTOM_TYPE_MAP.clear();
FLUID_TO_TYPE_MAP.clear();
}
//public static void fillFluidMap() {
// for (Map.Entry<ResourceLocation, FuelType> entry : BUILTIN_TYPE_MAP.entrySet()) {
// FuelType type = entry.getValue();
// for (Supplier<Fluid> delegate : type.getFluids()) {
// FLUID_TO_TYPE_MAP.put(delegate.get(), type);
// }
// }
// for (Map.Entry<ResourceLocation, FuelType> entry : CUSTOM_TYPE_MAP.entrySet()) {
// FuelType type = entry.getValue();
// for (Supplier<Fluid> delegate : type.getFluids()) {
// FLUID_TO_TYPE_MAP.put(delegate.get(), type);
// }
// }
//}
public static void fillGlobalMap() {
GLOBAL_TYPE_MAP.putAll(BUILTIN_TYPE_MAP);
GLOBAL_TYPE_MAP.putAll(CUSTOM_TYPE_MAP);
TFMG.LOGGER.info("Added {} Engine Fuel Types", GLOBAL_TYPE_MAP.size());
}
public static void toBuffer(FriendlyByteBuf buffer) {
buffer.writeVarInt(CUSTOM_TYPE_MAP.size());
for (Map.Entry<ResourceLocation, FuelType> entry : CUSTOM_TYPE_MAP.entrySet()) {
buffer.writeResourceLocation(entry.getKey());
FuelType.toBuffer(entry.getValue(), buffer);
}
}
public static void fromBuffer(FriendlyByteBuf buffer) {
clear();
int size = buffer.readVarInt();
for (int i = 0; i < size; i++) {
CUSTOM_TYPE_MAP.put(buffer.readResourceLocation(), FuelType.fromBuffer(buffer));
}
// fillFluidMap();
fillGlobalMap();
}
public static void syncTo(ServerPlayer player) {
TFMGPackets.getChannel().send(PacketDistributor.PLAYER.with(() -> player), new SyncPacket());
}
public static void syncToAll() {
TFMGPackets.getChannel().send(PacketDistributor.ALL.noArg(), new SyncPacket());
}
public static class ReloadListener extends SimpleJsonResourceReloadListener {
private static final Gson GSON = new Gson();
public static final ReloadListener INSTANCE = new ReloadListener();
protected ReloadListener() {
super(GSON, "tfmg_engine_fuels");
}
@Override
protected void apply(Map<ResourceLocation, JsonElement> map, ResourceManager resourceManager, ProfilerFiller profiler) {
clear();
for (Map.Entry<ResourceLocation, JsonElement> entry : map.entrySet()) {
JsonElement element = entry.getValue();
if (element.isJsonObject()) {
ResourceLocation id = entry.getKey();
JsonObject object = element.getAsJsonObject();
FuelType type = FuelType.fromJson(object);
CUSTOM_TYPE_MAP.put(id, type);
}
}
// fillFluidMap();
fillGlobalMap();
}
}
public static class SyncPacket extends SimplePacketBase {
private FriendlyByteBuf buffer;
public SyncPacket() {
}
public SyncPacket(FriendlyByteBuf buffer) {
this.buffer = buffer;
}
@Override
public void write(FriendlyByteBuf buffer) {
toBuffer(buffer);
}
@Override
public boolean handle(NetworkEvent.Context context) {
context.enqueueWork(() -> {
fromBuffer(buffer);
});
return true;
}
}
}

View File

@@ -0,0 +1,138 @@
package com.drmangotea.tfmg.content.engines.fuels;
import com.drmangotea.tfmg.registry.TFMGTags;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import net.minecraft.ResourceLocationException;
import net.minecraft.core.Holder;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.material.Fluid;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static com.drmangotea.tfmg.registry.TFMGTags.optionalTag;
public class FuelType {
TagKey<Fluid> fluid = TFMGTags.TFMGFluidTags.GASOLINE.tag;
private float speed = 1;
private float efficiency = 1;
private float stress = 1;
public FuelType() {
}
public TagKey<Fluid> getFluid() {
return fluid;
}
public float getSpeed() {
return speed;
}
public float getEfficiency() {
return efficiency;
}
public float getStress() {
return stress;
}
public static FuelType fromJson(JsonObject object) {
FuelType type = new FuelType();
try {
parseJsonPrimitive(object, "fluid", JsonPrimitive::isString, primitive -> type.fluid = optionalTag(ForgeRegistries.FLUIDS,new ResourceLocation(primitive.getAsString())));
parseJsonPrimitive(object, "speed", JsonPrimitive::isNumber, primitive -> type.speed = primitive.getAsFloat());
parseJsonPrimitive(object, "efficiency", JsonPrimitive::isNumber, primitive -> type.efficiency = primitive.getAsFloat());
parseJsonPrimitive(object, "stress", JsonPrimitive::isNumber, primitive -> type.stress = primitive.getAsFloat());
} catch (Exception e) {
//
}
return type;
}
private static void parseJsonPrimitive(JsonObject object, String key, Predicate<JsonPrimitive> predicate, Consumer<JsonPrimitive> consumer) {
JsonElement element = object.get(key);
if (element != null && element.isJsonPrimitive()) {
JsonPrimitive primitive = element.getAsJsonPrimitive();
if (predicate.test(primitive)) {
consumer.accept(primitive);
}
}
}
public static void toBuffer(FuelType type, FriendlyByteBuf buffer) {
buffer.writeResourceLocation(type.fluid.location());
buffer.writeFloat(type.speed);
buffer.writeFloat(type.efficiency);
buffer.writeFloat(type.stress);
}
public static FuelType fromBuffer(FriendlyByteBuf buffer) {
FuelType type = new FuelType();
type.fluid = optionalTag(ForgeRegistries.FLUIDS,buffer.readResourceLocation());
type.speed = buffer.readFloat();
type.efficiency = buffer.readFloat();
type.stress = buffer.readFloat();
return type;
}
public static class Builder {
protected ResourceLocation id;
protected FuelType result;
public Builder(ResourceLocation id) {
this.id = id;
this.result = new FuelType();
}
public Builder speed(float speed) {
result.speed = speed;
return this;
}
public Builder efficiency(float efficiency) {
result.efficiency = efficiency;
return this;
}
public Builder stress(float stress) {
result.stress = stress;
return this;
}
public final Builder addFluids(TagKey<Fluid> tag) {
result.fluid = tag;
return this;
}
public FuelType register() {
EngineFuelTypeManager.registerBuiltinType(id, result);
return result;
}
public final FuelType registerAndAssign(TagKey<Fluid> tag) {
addFluids(tag);
register();
return result;
}
}
}

View File

@@ -1,5 +1,6 @@
package com.drmangotea.tfmg.content.engines.regular_engine;
import com.drmangotea.tfmg.content.electricity.base.IElectric;
import com.drmangotea.tfmg.content.engines.base.AbstractEngineBlockEntity;
import com.drmangotea.tfmg.content.engines.base.EngineBlock;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
@@ -38,12 +39,13 @@ public class RegularEngineBlock extends EngineBlock implements IBE<RegularEngine
ItemStack itemStack = player.getItemInHand(hand);
if (level.getBlockEntity(pos) instanceof AbstractEngineBlockEntity be && !be.isController() && level.getBlockEntity(be.controller) instanceof AbstractEngineBlockEntity controller) {
if (level.getBlockEntity(pos) instanceof RegularEngineBlockEntity be && !be.isController() && level.getBlockEntity(be.controller) instanceof AbstractEngineBlockEntity controller) {
if (controller.nextComponent().test(itemStack))
if (controller.componentsInventory.insertItem(itemStack)) {
if (!itemStack.is(TFMGItems.SCREWDRIVER.get()))
itemStack.shrink(1);
controller.playInsertionSound();
controller.updateRotation();
controller.setChanged();
controller.sendData();
return InteractionResult.SUCCESS;
@@ -52,12 +54,13 @@ public class RegularEngineBlock extends EngineBlock implements IBE<RegularEngine
if(controller instanceof RegularEngineBlockEntity be1&&!be1.pistonInventory.isEmpty()&&!((RegularEngineBlockEntity) controller).pistonInventory.isEmpty())
return super.use(blockState, level, pos, player, hand, blockHitResult);
if (itemStack.is(TFMGItems.SCREWDRIVER.get())) {
if (itemStack.is(TFMGItems.SCREWDRIVER.get())&&be.pistonInventory.isEmpty()) {
for (int i = controller.componentsInventory.components.size() - 1; i >= 0; i--) {
if (!controller.componentsInventory.getItem(i).isEmpty()) {
controller.dropItem(controller.componentsInventory.getItem(i));
controller.componentsInventory.setStackInSlot(i, ItemStack.EMPTY);
controller.playRemovalSound();
controller.updateRotation();
controller.setChanged();
controller.sendData();
return InteractionResult.SUCCESS;
@@ -70,7 +73,14 @@ public class RegularEngineBlock extends EngineBlock implements IBE<RegularEngine
return super.use(blockState, level, pos, player, hand, blockHitResult);
}
@Override
public void onPlace(BlockState pState, Level level, BlockPos pos, BlockState pOldState, boolean pIsMoving) {
withBlockEntityDo(level, pos, IElectric::onPlaced);
}
@Override
public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
IBE.onRemove(state, level, pos, newState);
}
@Override
public Class<RegularEngineBlockEntity> getBlockEntityClass() {
return RegularEngineBlockEntity.class;

View File

@@ -2,17 +2,22 @@ package com.drmangotea.tfmg.content.engines.regular_engine;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.content.engines.base.AbstractEngineBlockEntity;
import com.drmangotea.tfmg.content.engines.fuels.FuelType;
import com.drmangotea.tfmg.registry.TFMGItems;
import com.drmangotea.tfmg.registry.TFMGTags;
import com.simibubi.create.AllItems;
import com.simibubi.create.AllSoundEvents;
import com.simibubi.create.foundation.item.SmartInventory;
import com.simibubi.create.foundation.utility.Lang;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.tags.TagKey;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
@@ -21,6 +26,7 @@ import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Fluid;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.ArrayList;
import java.util.List;
@@ -28,6 +34,8 @@ import java.util.Set;
import static com.drmangotea.tfmg.content.engines.base.EngineProperties.*;
import static com.drmangotea.tfmg.content.engines.regular_engine.RegularEngineBlock.EXTENDED;
import static com.drmangotea.tfmg.registry.TFMGTags.forgeFluidTag;
import static com.drmangotea.tfmg.registry.TFMGTags.optionalTag;
import static com.simibubi.create.content.kinetics.base.HorizontalKineticBlock.HORIZONTAL_FACING;
public class RegularEngineBlockEntity extends AbstractEngineBlockEntity {
@@ -37,96 +45,131 @@ public class RegularEngineBlockEntity extends AbstractEngineBlockEntity {
public SmartInventory pistonInventory;
List<TagKey<Fluid>> supportedFuels = new ArrayList<>();
boolean updateFuel = true;
public RegularEngineBlockEntity(BlockEntityType<?> typeIn, BlockPos pos, BlockState state) {
super(typeIn, pos, state);
pistonInventory = createInventory();
}
public void updateInventory(){
public void updateInventory() {
pistonInventory = createInventory();
}
public SmartInventory createInventory(){
return new SmartInventory(type.pistons.size(),this)
public SmartInventory createInventory() {
return new SmartInventory(type.pistons.size(), this)
.withMaxStackSize(1)
.whenContentsChanged(this::onInventoryChanged)
;
}
private void onInventoryChanged(int integer) {
refreshFuels();
updateRotation();
sendData();
setChanged();
}
public void refreshFuels() {
CompoundTag fuelsToAllow = pistonInventory.getItem(0).getOrCreateTag().getCompound("Fuels");
List<TagKey<Fluid>> fuelsFound = new ArrayList<>();
for (String key : fuelsToAllow.getAllKeys()) {
String id = fuelsToAllow.getString(key);
TagKey<Fluid> tag = optionalTag(ForgeRegistries.FLUIDS, new ResourceLocation(id));
fuelsFound.add(tag);
}
if (level.getBlockEntity(controller) instanceof RegularEngineBlockEntity be) {
be.supportedFuels = new ArrayList<>(fuelsFound);
for (Long position : be.engines) {
BlockPos pos = BlockPos.of(position);
if (level.getBlockEntity(pos) instanceof RegularEngineBlockEntity be1) {
be1.supportedFuels = new ArrayList<>(fuelsFound);
}
}
}
}
@Override
public List<TagKey<Fluid>> getSupportedFuels() {
return supportedFuels;
}
@Override
public boolean canWork() {
for(int i =0;i<pistonInventory.getSlots();i++){
if(pistonInventory.getStackInSlot(i).isEmpty())
return false;
}
return super.canWork();
if (level.getBlockEntity(controller) instanceof RegularEngineBlockEntity controller) {
for (Long position : controller.getAllEngines()) {
if (level.getBlockEntity(BlockPos.of(position)) instanceof RegularEngineBlockEntity be) {
for(int i =0;i<be.pistonInventory.getSlots();i++){
if(be.pistonInventory.getItem(i).isEmpty()) {
return false;
}
}
}
}
return super.canWork();
}
return false;
}
@Override
public boolean insertItem(ItemStack itemStack, boolean shifting, Player player, InteractionHand hand) {
if(itemStack.is(AllItems.EMPTY_SCHEMATIC.get())){
if (itemStack.is(AllItems.EMPTY_SCHEMATIC.get())) {
boolean next = false;
if(type == EngineType.BOXER){
if (type == EngineType.BOXER) {
updateEngineType(EngineType.I);
AllSoundEvents.CONFIRM.play(level, null, getBlockPos(), 1, 1);
return true;
}
for(EngineType engineType : EngineType.values()){
if(next){
for (EngineType engineType : EngineType.values()) {
if (next) {
updateEngineType(engineType);
AllSoundEvents.CONFIRM.play(level, null, getBlockPos(), 1, 1);
return true;
}
if(engineType == type){
if (engineType == type) {
next = true;
}
}
}
if(hasAllComponents())
if(itemStack.is(TFMGItems.ENGINE_CYLINDER.get())){
for (int i = pistonInventory.getSlots() - 1; i >= 0; i--) {
if (pistonInventory.getItem(i).isEmpty()) {
pistonInventory.setItem(i,new ItemStack(itemStack.getItem(),1));
itemStack.shrink(1);
playInsertionSound();
setChanged();
sendData();
return true;
}
}
}
if (itemStack.is(TFMGItems.SCREWDRIVER.get())) {
if(!pistonInventory.isEmpty()){
for (int i = pistonInventory.getSlots()-1; i >= 0; i--) {
if (!pistonInventory.isEmpty()) {
for (int i = 0; i < pistonInventory.getSlots(); i++) {
if (!pistonInventory.getItem(i).isEmpty()) {
dropItem(pistonInventory.getItem(i));
pistonInventory.setItem(i, ItemStack.EMPTY);
playRemovalSound();
updateRotation();
setChanged();
sendData();
return true;
}
}
}
for (int i = componentsInventory.components.size() - 1; i >= 0; i--) {
if (!componentsInventory.getItem(i).isEmpty()) {
dropItem(componentsInventory.getItem(i));
componentsInventory.setItem(i, ItemStack.EMPTY);
playRemovalSound();
updateRotation();
setChanged();
sendData();
return true;
@@ -134,20 +177,75 @@ public class RegularEngineBlockEntity extends AbstractEngineBlockEntity {
}
}
if (nextComponent().test(itemStack)&&!isController()) {
if (hasAllComponents())
if (itemStack.is(TFMGItems.ENGINE_CYLINDER.get()) && isCylinderSame(itemStack)) {
for (int i = pistonInventory.getSlots() - 1; i >= 0; i--) {
if (pistonInventory.getItem(i).isEmpty()) {
ItemStack toInsert = itemStack.copy();
toInsert.setCount(1);
pistonInventory.setItem(i, toInsert);
itemStack.shrink(1);
playInsertionSound();
updateRotation();
setChanged();
sendData();
return true;
}
}
}
if (nextComponent().test(itemStack) && !isController()) {
if(level.getBlockEntity(controller) instanceof AbstractEngineBlockEntity be){
return be.insertItem(itemStack,shifting,player,hand);
if (level.getBlockEntity(controller) instanceof AbstractEngineBlockEntity be) {
return be.insertItem(itemStack, shifting, player, hand);
}
}
return super.insertItem(itemStack, shifting,player, hand);
return super.insertItem(itemStack, shifting, player, hand);
}
public boolean isCylinderSame(ItemStack stack) {
CompoundTag tag = stack.getOrCreateTag().getCompound("Fuels");
public boolean updateEngineType(EngineType newType){
if (level.getBlockEntity(controller) instanceof RegularEngineBlockEntity controller) {
List<Long> engines = new ArrayList<>(controller.engines);
engines.add(this.controller.asLong());
for (int i = 0; i < controller.engineLength() + 1; i++) {
BlockPos pos = BlockPos.of(engines.get(i));
if (level.getBlockEntity(pos) instanceof RegularEngineBlockEntity be) {
for (int y = 0; y < be.pistonInventory.getSlots(); y++) {
if (!be.pistonInventory.getItem(y).is(TFMGItems.ENGINE_CYLINDER.get()))
continue;
CompoundTag tagInside = be.pistonInventory.getItem(y).getOrCreateTag().getCompound("Fuels");
if (!tagInside.toString().equals(tag.toString()))
return false;
}
}
}
}
return true;
}
@Override
public void tick() {
super.tick();
if (updateFuel) {
refreshFuels();
updateFuel = false;
}
}
public boolean updateEngineType(EngineType newType) {
Direction updateDirection = getBlockState().getValue(HORIZONTAL_FACING).getAxis() == Direction.Axis.X ? Direction.WEST : Direction.NORTH;
if (level.getBlockEntity(getBlockPos().relative(updateDirection)) instanceof RegularEngineBlockEntity be) {
@@ -155,18 +253,18 @@ public class RegularEngineBlockEntity extends AbstractEngineBlockEntity {
}
for (int i = 0; i <= engineLength(); i++) {
BlockPos pos = getBlockPos().relative(updateDirection.getOpposite(), i);
if(level.getBlockEntity(pos) instanceof RegularEngineBlockEntity be){
if (level.getBlockEntity(pos) instanceof RegularEngineBlockEntity be) {
//be.type = EngineType.I;
if(!be.pistonInventory.isEmpty())
if (!be.pistonInventory.isEmpty())
return false;
}
}
for (int i = 0; i <= engineLength(); i++) {
BlockPos pos = getBlockPos().relative(updateDirection.getOpposite(), i);
if(level.getBlockEntity(pos) instanceof RegularEngineBlockEntity be){
if (level.getBlockEntity(pos) instanceof RegularEngineBlockEntity be) {
be.type = newType;
be.updateInventory();
level.setBlockAndUpdate(pos,be.getBlockState().setValue(EXTENDED, newType == EngineType.I||newType == EngineType.U));
level.setBlockAndUpdate(pos, be.getBlockState().setValue(EXTENDED, newType == EngineType.I || newType == EngineType.U));
}
}
@@ -177,98 +275,91 @@ public class RegularEngineBlockEntity extends AbstractEngineBlockEntity {
protected void write(CompoundTag compound, boolean clientPacket) {
super.write(compound, clientPacket);
compound.putString("Type", type.name);
compound.put("Cylinders", pistonInventory.serializeNBT());
}
@Override
protected void read(CompoundTag compound, boolean clientPacket) {
super.read(compound, clientPacket);
for(EngineType engineType : EngineType.values()){
if(engineType.name.matches(compound.getString("Type"))){
for (EngineType engineType : EngineType.values()) {
if (engineType.name.matches(compound.getString("Type"))) {
type = engineType;
break;
}
}
//TFMG.LOGGER.debug(compound.getString("Type"));
//
//type = EngineType.V;
//type = EngineType.valueOf(compound.getString("Type"));
//
//TFMG.LOGGER.debug(compound.getString("TypeE"));
pistonInventory.deserializeNBT(compound.getCompound("Cylinders"));
}
@Override
public int effectiveSpeed() {
return type.effectiveSpeed;
}
@Override
public float efficiencyModifier() {
return type.effeciencyModifier;
return type.effeciencyModifier * getFuelType().getEfficiency()*getUpgradeEfficiencyModifier();
}
@Override
public float speedModifier() {
return type.speedModifier;
return type.speedModifier * getFuelType().getSpeed()*getUpgradeSpeedModifier();
}
@Override
public float torqueModifier() {
return type.torqueModifier;
return type.torqueModifier * getFuelType().getStress()*getUpgradeTorqueModifier();
}
@Override
public boolean addToGoggleTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
Lang.text("Piston Inv Size: "+pistonInventory.getSlots()).forGoggles(tooltip);
for (TagKey<Fluid> tag : supportedFuels) {
Lang.text("Type: "+type.name).forGoggles(tooltip);
Lang.text(tag.toString()).forGoggles(tooltip);
super.addToGoggleTooltip(tooltip, isPlayerSneaking);
}
return true;
Lang.text("Type: " + type.name).forGoggles(tooltip);
super.addToGoggleTooltip(tooltip, isPlayerSneaking);
return true;
}
@Override
public String engineId() {
return type.name;
}
enum EngineType{
I("engine_i",pistonsI(),12,1,1,1),
V("engine_v",pistonsV(),14,1.2f,1.3f,0.8f),
W("engine_w",pistonsW(),16,1.3f,1.1f,0.5f),
U("engine_u",pistonsU(),12,1,1.5f,0.9f),
BOXER("engine_boxer",pistonsBoxer(),11,1,0.8f,1.2f)
;
public final int effectiveSpeed;
public enum EngineType {
I("engine_i", pistonsI(), 1, 1, 1,true),
V("engine_v", pistonsV(), 1.2f, 1.3f, 0.8f),
W("engine_w", pistonsW(), 1.3f, 1.1f, 0.5f),
U("engine_u", pistonsU(), 1, 1.5f, 0.9f,true),
BOXER("engine_boxer", pistonsBoxer(), 1, 0.8f, 1.2f);
public final float speedModifier;
public final float torqueModifier;
public final float effeciencyModifier;
public final List<PistonPosition> pistons;
public final List<Fluid> fluidBlacklist;
public final String name;
public final boolean upgradesOnSide;
EngineType(String name, List<PistonPosition> positions, int effectiveSpeed, float speedModifier,
float torqueModifier, float efficiencyModifier){
this(name,positions, effectiveSpeed, speedModifier, torqueModifier, efficiencyModifier, new ArrayList<>());
EngineType(String name, List<PistonPosition> positions, float speedModifier,
float torqueModifier, float efficiencyModifier, boolean upgradesOnSide) {
this(name, positions, speedModifier, torqueModifier, efficiencyModifier,upgradesOnSide, new ArrayList<>());
}
EngineType(String name, List<PistonPosition> positions, int effectiveSpeed, float speedModifier,
float torqueModifier, float efficiencyModifier , List<Fluid> fluidBlacklist){
EngineType(String name, List<PistonPosition> positions, float speedModifier,
float torqueModifier, float efficiencyModifier) {
this(name, positions, speedModifier, torqueModifier, efficiencyModifier,false, new ArrayList<>());
}
EngineType(String name, List<PistonPosition> positions, float speedModifier,
float torqueModifier, float efficiencyModifier,boolean upgradesOnSide , List<Fluid> fluidBlacklist) {
this.name = name;
this.pistons = positions;
this.effectiveSpeed = effectiveSpeed;
this.speedModifier = speedModifier;
this.torqueModifier = torqueModifier;
this.effeciencyModifier = efficiencyModifier;
this.fluidBlacklist = fluidBlacklist;
this.upgradesOnSide = upgradesOnSide;
}

View File

@@ -0,0 +1,70 @@
package com.drmangotea.tfmg.content.engines.upgrades;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.content.engines.base.AbstractEngineBlockEntity;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.simibubi.create.content.fluids.tank.FluidTankBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.Level;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler;
import java.util.Optional;
public class EnginePipingUpgrade extends EngineUpgrade {
public Optional<FluidTankBlockEntity> tank = Optional.empty();
public void findTank(AbstractEngineBlockEntity be) {
Level level = be.getLevel();
for (Direction direction : Direction.values()) {
BlockPos pos = be.getBlockPos().relative(direction);
if (level.getBlockEntity(pos) instanceof FluidTankBlockEntity foundTank) {
tank = Optional.of(foundTank);
return;
}
}
tank = Optional.empty();
}
@Override
public void updateUpgrade(AbstractEngineBlockEntity be) {
findTank(be);
}
@Override
public void lazyTickUpgrade(AbstractEngineBlockEntity engine) {
if (tank.isPresent()) {
AbstractEngineBlockEntity controller = engine.getControllerBE();
FluidTankBlockEntity tankBE = tank.get();
int maxOutput = tankBE.getTankInventory().drain(500, IFluidHandler.FluidAction.SIMULATE).getAmount();
int maxInput = tankBE.getTankInventory().fill(new FluidStack(tankBE.getFluid(0), 500), IFluidHandler.FluidAction.SIMULATE);
int amount = Math.min(maxInput, Math.min(maxOutput, controller.fuelTank.getSpace()));
tankBE.getTankInventory().drain(amount, IFluidHandler.FluidAction.EXECUTE);
controller.getControllerBE().fuelTank.fill(new FluidStack(tankBE.getFluid(0), amount), IFluidHandler.FluidAction.EXECUTE);
}
}
@Override
public Optional<? extends EngineUpgrade> createUpgrade() {
return Optional.of(new EnginePipingUpgrade());
}
@Override
public Item getItem() {
return TFMGBlocks.INDUSTRIAL_PIPE.asItem();
}
}

View File

@@ -0,0 +1,54 @@
package com.drmangotea.tfmg.content.engines.upgrades;
import com.drmangotea.tfmg.content.engines.base.AbstractEngineBlockEntity;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.drmangotea.tfmg.registry.TFMGItems;
import com.jozufozu.flywheel.backend.instancing.Engine;
import com.jozufozu.flywheel.core.PartialModel;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.world.item.Item;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public abstract class EngineUpgrade {
public EngineUpgrade(){
}
public abstract Optional<? extends EngineUpgrade> createUpgrade();
public void tickUpgrade(AbstractEngineBlockEntity engine) {}
public void lazyTickUpgrade(AbstractEngineBlockEntity engine) {}
public void render(AbstractEngineBlockEntity be, float partialTicks, PoseStack ms, MultiBufferSource buffer, int light) {}
public float getTorqueModifier(AbstractEngineBlockEntity engine) {
return 1;
}
public void updateUpgrade(AbstractEngineBlockEntity be ){}
public abstract Item getItem();
public float getSpeedModifier(AbstractEngineBlockEntity engine) {
return 1;
}
public float getEfficiencyModifier(AbstractEngineBlockEntity engine) {
return 1;
}
public static Map<Item, EngineUpgrade> getUpgrades(){
Map<Item, EngineUpgrade> map = new HashMap<>();
map.put(TFMGItems.TURBO.get(), new TurboUpgradeData());
map.put(TFMGItems.GOLDEN_TURBO.get(), new GoldenTurboUpgradeData());
map.put(TFMGBlocks.GENERATOR.asItem(), new GeneratorEngineUpgrade());
map.put(TFMGBlocks.INDUSTRIAL_PIPE.asItem(), new EnginePipingUpgrade());
return map;
}
}

View File

@@ -0,0 +1,62 @@
package com.drmangotea.tfmg.content.engines.upgrades;
import com.drmangotea.tfmg.content.engines.base.AbstractEngineBlockEntity;
import com.drmangotea.tfmg.content.engines.regular_engine.RegularEngineBlockEntity;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.drmangotea.tfmg.registry.TFMGPartialModels;
import com.mojang.blaze3d.vertex.PoseStack;
import com.simibubi.create.foundation.render.CachedBufferer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.core.Direction;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.state.BlockState;
import java.util.Optional;
import static net.minecraft.world.level.block.HorizontalDirectionalBlock.FACING;
public class GeneratorEngineUpgrade extends EngineUpgrade {
@Override
public Optional<? extends EngineUpgrade> createUpgrade() {
return Optional.of(new GeneratorEngineUpgrade());
}
@Override
public void render(AbstractEngineBlockEntity be, float partialTicks, PoseStack ms, MultiBufferSource buffer, int light) {
BlockState state = be.getBlockState();
Direction facing = state.getValue(FACING);
boolean side = false;
ms.pushPose();
if (be instanceof RegularEngineBlockEntity blockEntity) {
side = blockEntity.type.upgradesOnSide;
}
CachedBufferer.partial(TFMGPartialModels.ENGINE_GENERATOR, state)
.centre()
.translateY(side ? -2/16f :0)
.rotateY(facing.toYRot())
.rotateZ(side ? 90 : 0)
.translateY(side ? 4 / 16f : 0)
.unCentre()
.light(light)
.renderInto(ms, buffer.getBuffer(RenderType.solid()));
ms.popPose();
}
@Override
public Item getItem() {
return TFMGBlocks.GENERATOR.asItem();
}
@Override
public float getTorqueModifier(AbstractEngineBlockEntity engine) {
return 0.7f;
}
}

View File

@@ -0,0 +1,101 @@
package com.drmangotea.tfmg.content.engines.upgrades;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.content.engines.base.AbstractEngineBlockEntity;
import com.drmangotea.tfmg.content.engines.regular_engine.RegularEngineBlockEntity;
import com.drmangotea.tfmg.registry.TFMGItems;
import com.drmangotea.tfmg.registry.TFMGPartialModels;
import com.jozufozu.flywheel.core.PartialModel;
import com.mojang.blaze3d.vertex.PoseStack;
import com.simibubi.create.foundation.render.CachedBufferer;
import com.simibubi.create.foundation.utility.animation.LerpedFloat;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.core.Direction;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.state.BlockState;
import java.util.Optional;
import static net.minecraft.world.level.block.HorizontalDirectionalBlock.FACING;
public class GoldenTurboUpgradeData extends EngineUpgrade {
LerpedFloat speed = LerpedFloat.linear();
float angle;
public GoldenTurboUpgradeData() {
}
@Override
public Optional<? extends EngineUpgrade> createUpgrade() {
return Optional.of(new GoldenTurboUpgradeData());
}
public PartialModel getModel() {
return TFMGPartialModels.GOLDEN_TURBO;
}
@Override
public void tickUpgrade(AbstractEngineBlockEntity engine) {
if (!engine.getLevel().isClientSide)
return;
speed.chase(engine.rpm / 200, 1 / 128f, LerpedFloat.Chaser.EXP);
speed.tickChaser();
}
@Override
public void render(AbstractEngineBlockEntity be, float partialTicks, PoseStack ms, MultiBufferSource buffer, int light) {
angle+=be.rpm/500f;
angle %= 360;
BlockState state = be.getBlockState();
Direction facing = state.getValue(FACING);
boolean side = false;
ms.pushPose();
if (be instanceof RegularEngineBlockEntity blockEntity) {
side = blockEntity.type.upgradesOnSide;
}
CachedBufferer.partial(getModel(), state)
.centre()
.rotateY(facing.toYRot())
.translateX(side ? -4/16f : 0)
.rotateZ(side ? 90 : 0)
.unCentre()
.light(light)
.renderInto(ms, buffer.getBuffer(RenderType.solid()));
CachedBufferer.partial(TFMGPartialModels.GOLDEN_TURBO_PROPELLER, state)
.centre()
.rotateY(facing.toYRot())
.translateX(side ? -4/16f : 0)
.rotateZ(side ? 90 : 0)
.rotateY(angle)
.unCentre()
.light(light)
.renderInto(ms, buffer.getBuffer(RenderType.solid()));
ms.popPose();
}
@Override
public float getTorqueModifier(AbstractEngineBlockEntity engine) {
return 1.4f;
}
@Override
public Item getItem() {
return TFMGItems.GOLDEN_TURBO.asItem();
}
@Override
public float getSpeedModifier(AbstractEngineBlockEntity engine) {
return 1.3f;
}
}

View File

@@ -0,0 +1,116 @@
package com.drmangotea.tfmg.content.engines.upgrades;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.content.engines.base.AbstractEngineBlockEntity;
import com.drmangotea.tfmg.content.engines.regular_engine.RegularEngineBlockEntity;
import com.drmangotea.tfmg.registry.TFMGItems;
import com.drmangotea.tfmg.registry.TFMGPartialModels;
import com.jozufozu.flywheel.core.PartialModel;
import com.mojang.blaze3d.vertex.PoseStack;
import com.simibubi.create.foundation.render.CachedBufferer;
import com.simibubi.create.foundation.render.SuperByteBuffer;
import com.simibubi.create.foundation.utility.animation.LerpedFloat;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.core.Direction;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import java.util.Optional;
import static net.minecraft.world.level.block.HorizontalDirectionalBlock.FACING;
public class TurboUpgradeData extends EngineUpgrade {
LerpedFloat speed = LerpedFloat.linear();
float angle;
public TurboUpgradeData() {
}
@Override
public Optional<? extends EngineUpgrade> createUpgrade() {
return Optional.of(new TurboUpgradeData());
}
public PartialModel getModel() {
return TFMGPartialModels.TURBO;
}
@Override
public void tickUpgrade(AbstractEngineBlockEntity engine) {
if (!engine.getLevel().isClientSide)
return;
}
@Override
public void render(AbstractEngineBlockEntity be, float partialTicks, PoseStack ms, MultiBufferSource buffer, int light) {
if(!Minecraft.getInstance().isPaused()) {
speed.chase(be.rpm / 100, 1 / 32f, LerpedFloat.Chaser.EXP);
speed.tickChaser();
// angle += speed.getValue(partialTicks) * 3 / 10f;
angle+=be.rpm/100;
angle %= 360;
}
BlockState state = be.getBlockState();
Direction facing = state.getValue(FACING);
boolean side = false;
ms.pushPose();
if (be instanceof RegularEngineBlockEntity blockEntity) {
side = blockEntity.type.upgradesOnSide;
}
CachedBufferer.partial(getModel(), state)
.centre()
.rotateY(facing.toYRot())
.translateX(side ? -4/16f : 0)
.rotateZ(side ? 90 : 0)
.unCentre()
.light(light)
.renderInto(ms, buffer.getBuffer(RenderType.solid()));
CachedBufferer.partial(TFMGPartialModels.TURBO_PROPELLER, state)
.centre()
.rotateY(facing.toYRot())
.translateX(side ? -4/16f : 0)
.rotateZ(side ? 90 : 0)
.rotateY(angle)
.unCentre()
.light(light)
.renderInto(ms, buffer.getBuffer(RenderType.solid()));
ms.popPose();
}
@Override
public float getTorqueModifier(AbstractEngineBlockEntity engine) {
return 1.2f;
}
@Override
public Item getItem() {
return TFMGItems.TURBO.asItem();
}
@Override
public float getSpeedModifier(AbstractEngineBlockEntity engine) {
return 1.3f;
}
@Override
public float getEfficiencyModifier(AbstractEngineBlockEntity engine) {
return 0.7f;
}
}

View File

@@ -2,15 +2,21 @@ package com.drmangotea.tfmg.content.machinery.metallurgy.blast_furnace;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
import com.simibubi.create.foundation.block.IBE;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
public class BlastFurnaceHatchBlock extends Block implements IBE<BlastFurnaceHatchBlockEntity> {
public BlastFurnaceHatchBlock(Properties p_49795_) {
super(p_49795_);
}
@Override
public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
IBE.onRemove(state, level, pos, newState);
}
@Override
public Class<BlastFurnaceHatchBlockEntity> getBlockEntityClass() {
return BlastFurnaceHatchBlockEntity.class;

View File

@@ -5,6 +5,7 @@ import com.drmangotea.tfmg.registry.TFMGFluids;
import com.simibubi.create.content.equipment.goggles.IHaveGoggleInformation;
import com.simibubi.create.foundation.blockEntity.SmartBlockEntity;
import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour;
import com.simibubi.create.foundation.item.ItemHelper;
import com.simibubi.create.foundation.item.SmartInventory;
import com.simibubi.create.foundation.utility.VecHelper;
import net.minecraft.core.BlockPos;
@@ -64,6 +65,11 @@ public class BlastFurnaceHatchBlockEntity extends SmartBlockEntity implements IH
dropItems();
}
@Override
public void destroy() {
super.destroy();
ItemHelper.dropContents(level, worldPosition, inventory);
}
public void dropItems(){

View File

@@ -3,14 +3,20 @@ package com.drmangotea.tfmg.content.machinery.metallurgy.blast_furnace;
import com.drmangotea.tfmg.base.TFMGHorizontalDirectionalBlock;
import com.drmangotea.tfmg.registry.TFMGBlockEntities;
import com.simibubi.create.foundation.block.IBE;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
public class BlastFurnaceOutputBlock extends TFMGHorizontalDirectionalBlock implements IBE<BlastFurnaceOutputBlockEntity> {
public BlastFurnaceOutputBlock(Properties properties) {
super(properties);
}
@Override
public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
IBE.onRemove(state, level, pos, newState);
}
@Override
public Class<BlastFurnaceOutputBlockEntity> getBlockEntityClass() {

View File

@@ -361,6 +361,7 @@ public class BlastFurnaceOutputBlockEntity extends SmartBlockEntity implements I
public void destroy() {
super.destroy();
ItemHelper.dropContents(level, worldPosition, inputInventory);
ItemHelper.dropContents(level, worldPosition, fluxInventory);
}
public int getSize() {

View File

@@ -3,12 +3,14 @@ package com.drmangotea.tfmg.content.machinery.metallurgy.blast_stove;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.base.TFMGUtils;
import com.drmangotea.tfmg.content.decoration.pipes.TFMGPipeBlockEntity;
import com.drmangotea.tfmg.recipes.DistillationRecipe;
import com.drmangotea.tfmg.recipes.HotBlastRecipe;
import com.drmangotea.tfmg.registry.TFMGFluids;
import com.simibubi.create.Create;
import com.simibubi.create.api.connectivity.ConnectivityHandler;
import com.simibubi.create.content.equipment.goggles.IHaveGoggleInformation;
import com.simibubi.create.content.fluids.pipes.FluidPipeBlockEntity;
import com.simibubi.create.content.fluids.tank.FluidTankBlockEntity;
import com.simibubi.create.foundation.blockEntity.IMultiBlockEntityContainer;
import com.simibubi.create.foundation.fluid.CombinedTankWrapper;
@@ -91,6 +93,8 @@ public class BlastStoveBlockEntity extends FluidTankBlockEntity implements IHave
worldPosition.offset(xOffset, yOffset, zOffset)) instanceof BlastStoveBlockEntity fbe)
fbe.refreshCapability();
if (level.isClientSide)
return;
refreshCapability();
@@ -272,6 +276,7 @@ public class BlastStoveBlockEntity extends FluidTankBlockEntity implements IHave
secondaryCapability = LazyOptional.of(() -> handlerForSecondaryCapability());
oldCap.invalidate();
oldSecondaryCap.invalidate();
}

View File

@@ -7,6 +7,7 @@ import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.simibubi.create.foundation.block.IBE;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.shapes.CollisionContext;
@@ -21,7 +22,10 @@ public class CastingBasinBlock extends TFMGHorizontalDirectionalBlock implements
public VoxelShape getShape(BlockState p_60555_, BlockGetter p_60556_, BlockPos p_60557_, CollisionContext p_60558_) {
return TFMGShapes.CASTING_BASIN.get(p_60555_.getValue(FACING));
}
@Override
public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean isMoving) {
IBE.onRemove(state, level, pos, newState);
}
@Override
public Class<CastingBasinBlockEntity> getBlockEntityClass() {
return CastingBasinBlockEntity.class;

View File

@@ -6,8 +6,10 @@ import com.simibubi.create.content.equipment.goggles.IHaveGoggleInformation;
import com.simibubi.create.foundation.blockEntity.SmartBlockEntity;
import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour;
import com.simibubi.create.foundation.fluid.SmartFluidTank;
import com.simibubi.create.foundation.item.ItemHelper;
import com.simibubi.create.foundation.item.SmartInventory;
import com.simibubi.create.foundation.recipe.RecipeFinder;
import com.simibubi.create.foundation.utility.animation.LerpedFloat;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
@@ -41,6 +43,8 @@ public class CastingBasinBlockEntity extends SmartBlockEntity implements IHaveGo
public int timer = 0;
private static final Object castingRecipeKey = new Object();
LerpedFloat fluidLevel = LerpedFloat.linear();
public CastingBasinBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
fluidCapability = LazyOptional.of(() -> tank);
@@ -81,8 +85,14 @@ public class CastingBasinBlockEntity extends SmartBlockEntity implements IHaveGo
} else findRecipe();
} else timer = 0;
}
if(level.isClientSide&&flowTimer>0){
flowTimer--;
if(level.isClientSide){
if(flowTimer>0)
flowTimer--;
fluidLevel.chase(tank.getFluidAmount(), 0.3f, LerpedFloat.Chaser.EXP);
fluidLevel.tickChaser();
}
}
@@ -111,6 +121,12 @@ public class CastingBasinBlockEntity extends SmartBlockEntity implements IHaveGo
setChanged();
}
@Override
public void destroy() {
super.destroy();
ItemHelper.dropContents(level, worldPosition, inventory);
}
@Override
public boolean addToGoggleTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
TFMGUtils.createFluidTooltip(this, tooltip);

View File

@@ -18,7 +18,7 @@ public class CastingBasinRenderer extends SafeBlockEntityRenderer<CastingBasinBl
if (be.tank.isEmpty())
return;
BlockState blockState = be.getBlockState();
FluidRenderer.renderFluidBox(be.tank.getFluid(), 0.1f, 0.1f, 0.1f, 0.9f, be.fluidLevel.getValue(partialTicks)/400, 0.9f, buffer, ms, light, false);
if (be.flowTimer > 0) {
Direction facing = blockState.getValue(FACING);

View File

@@ -1,5 +1,6 @@
package com.drmangotea.tfmg.content.machinery.misc.concrete_hose;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.registry.TFMGFluids;
import com.simibubi.create.content.fluids.transfer.FluidManipulationBehaviour;
import com.simibubi.create.foundation.advancement.AllAdvancements;
@@ -120,14 +121,14 @@ public class ConcreteFillingBehavior extends TFMGFluidManipulationBehaviour {
if (affectedArea == null)
affectedArea = BoundingBox.fromCorners(root, root);
if (revalidateIn == 0) {
visited.clear();
infinityCheckFrontier.clear();
infinityCheckVisited.clear();
infinityCheckFrontier.add(new BlockPosEntry(root, 0));
setValidationTimer();
softReset(root);
}
//if (revalidateIn == 0) {
// visited.clear();
// infinityCheckFrontier.clear();
// infinityCheckVisited.clear();
// infinityCheckFrontier.add(new BlockPosEntry(root, 0));
// setValidationTimer();
// softReset(root);
//}
Level world = getWorld();
int maxRange = maxRange();
@@ -152,16 +153,17 @@ public class ConcreteFillingBehavior extends TFMGFluidManipulationBehaviour {
int k = root.getZ();
world.playSound(null, i, j, k, SoundEvents.FIRE_EXTINGUISH, SoundSource.BLOCKS, 0.5F,
2.6F + (world.random.nextFloat() - world.random.nextFloat()) * 0.8F);
} else if (!canPlaceSources)
blockEntity.award(AllAdvancements.HOSE_PULLEY);
}
return true;
}
boolean success = false;
TFMG.LOGGER.debug("queueweueue "+queue.size());
for (int i = 0; !success && !queue.isEmpty() && i < searchedPerTick; i++) {
BlockPosEntry entry = queue.first();
BlockPos currentPos = entry.pos();
if (visited.contains(currentPos)) {
queue.dequeue();
continue;
@@ -186,8 +188,6 @@ public class ConcreteFillingBehavior extends TFMGFluidManipulationBehaviour {
success = true;
if (!simulate) {
playEffect(world, currentPos, fluid, false);
BlockState blockState = world.getBlockState(currentPos);
if (blockState.hasProperty(CONCRETELOGGED) && fluid.isSame(TFMGFluids.LIQUID_CONCRETE.getSource())) {
if (!blockEntity.isVirtual())

View File

@@ -30,11 +30,11 @@ public class ConcreteHoseBlockEntity extends KineticBlockEntity {
LerpedFloat offset;
boolean isMoving;
private SmartFluidTank internalTank;
private LazyOptional<IFluidHandler> capability;
private ConcreteFillingBehavior filler;
private ConcreteHoseFluidHandler handler;
private boolean infinite;
public SmartFluidTank internalTank;
public LazyOptional<IFluidHandler> capability;
public ConcreteFillingBehavior filler;
public ConcreteHoseFluidHandler handler;
public boolean infinite;
public ConcreteHoseBlockEntity(BlockEntityType<?> typeIn, BlockPos pos, BlockState state) {
super(typeIn, pos, state);

View File

@@ -769,8 +769,8 @@ public class VatBlockEntity extends SmartBlockEntity implements IHaveGoggleInfor
Lang.text("Heat "+heatLevel).forGoggles(tooltip);
for(String operation : machines)
Lang.text(operation).forGoggles(tooltip);
if(true)
return true;
Lang.translate("gui.goggles.basin_contents")
.forGoggles(tooltip);
@@ -887,8 +887,13 @@ public class VatBlockEntity extends SmartBlockEntity implements IHaveGoggleInfor
}
public float getFillState() {
// return (float) tankInventory.getFluidAmount() / tankInventory.getCapacity();
return 1;
IFluidHandler fluidHandler = this.getCapability(ForgeCapabilities.FLUID_HANDLER).orElse(null);
for(int i =0;i<fluidHandler.getTanks();i++)
if(!fluidHandler.getFluidInTank(i).isEmpty())
return (float) fluidHandler.getFluidInTank(i).getAmount() / fluidHandler.getTankCapacity(0);
return 0;
}
@Override

View File

@@ -1,11 +1,15 @@
package com.drmangotea.tfmg.content.machinery.misc.vat_machines.base;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.registry.TFMGPartialModels;
import com.drmangotea.tfmg.registry.TFMGTags;
import com.jozufozu.flywheel.util.transform.TransformStack;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.simibubi.create.AllPartialModels;
import com.simibubi.create.content.fluids.FlowSource;
import com.simibubi.create.foundation.blockEntity.behaviour.fluid.SmartFluidTankBehaviour;
import com.simibubi.create.foundation.blockEntity.renderer.SafeBlockEntityRenderer;
import com.simibubi.create.foundation.fluid.FluidRenderer;
import com.simibubi.create.foundation.render.CachedBufferer;
@@ -17,9 +21,14 @@ import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.minecraft.core.Direction;
import net.minecraft.util.Mth;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.templates.FluidTank;
import java.util.ArrayList;
import java.util.List;
public class VatRenderer extends SafeBlockEntityRenderer<VatBlockEntity> {
public VatRenderer(BlockEntityRendererProvider.Context context) {}
@@ -32,11 +41,11 @@ public class VatRenderer extends SafeBlockEntityRenderer<VatBlockEntity> {
if (!be.isController())
return;
LerpedFloat fluidLevel = be.getFluidLevel();
if (fluidLevel == null)
return;
if(!be.window)
return;
float capHeight = 1 / 4f;
float tankHullWidth = 1 / 16f + 1 / 128f;
float minPuddleHeight = 1 / 16f;
@@ -45,34 +54,32 @@ public class VatRenderer extends SafeBlockEntityRenderer<VatBlockEntity> {
float level = fluidLevel.getValue(partialTicks);
if (level < 1 / (512f * totalHeight))
return;
float clampedLevel = Mth.clamp(level * totalHeight, 0, totalHeight);
//FluidTank tank = be.tankInventory;
//FluidStack fluidStack = tank.getFluid();
//if (fluidStack.isEmpty())
// return;
//
//boolean top = fluidStack.getFluid()
// .getFluidType()
// .isLighterThanAir();
IFluidHandler fluidHandler = be.getCapability(ForgeCapabilities.FLUID_HANDLER).orElse(null);
float xMin = tankHullWidth;
float xMax = xMin + be.width - 2 * tankHullWidth;
float yMin = totalHeight + capHeight + minPuddleHeight - clampedLevel;
float yMax = yMin + clampedLevel;
//if (top) {
// yMin += totalHeight - clampedLevel;
// yMax += totalHeight - clampedLevel;
//}
float zMin = tankHullWidth;
float zMax = zMin + be.width - 2 * tankHullWidth;
ms.pushPose();
ms.translate(0, clampedLevel - totalHeight, 0);
//FluidRenderer.renderFluidBox(fluidStack, xMin, yMin, zMin, xMax, yMax, zMax, bufferSource, ms, light, false);
for(int i =0;i<fluidHandler.getTanks();i++) {
if(!fluidHandler.getFluidInTank(i).isEmpty()){
FluidRenderer.renderFluidBox(fluidHandler.getFluidInTank(i), xMin, yMin, zMin, xMax, yMax, zMax, bufferSource, ms, light, false);
break;
}
}
ms.popPose();
}

View File

@@ -1,94 +0,0 @@
Map<Integer, Integer> isFound = new HashMap<>();
for(int i = 0; i<testedRecipe.getIngredients().size();i++){
Ingredient ingredient = testedRecipe.getIngredients().get(i);
Integer foundAt = null;
if(ingredient.isEmpty())
break;
for(int y = 0; y<inputInventory.getSlots();y++){
if(isFound.containsValue(y))
continue;
ItemStack stack = inputInventory.getItem(y);
if(ingredient.test(stack)){
foundAt = y;
break;
}
}
if(foundAt!=null){
isFound.put(i, foundAt);
} else doesntMatch = true;
}
//
Map<Integer, Integer> isFluidFound = new HashMap<>();
for(int i = 0; i<testedRecipe.getFluidIngredients().size();i++){
FluidIngredient ingredient = testedRecipe.getFluidIngredients().get(i);
Integer foundAt = null;
if(ingredient.getMatchingFluidStacks().isEmpty())
break;
for(int y = 0; y<inputInventory.getSlots();y++){
if(isFluidFound.containsValue(y))
continue;
FluidStack stack = inputTank.getPrimaryHandler().getFluidInTank(y);
if(ingredient.test(stack)){
foundAt = y;
break;
}
}
if(foundAt!=null){
isFluidFound.put(i, foundAt);
} else doesntMatch = true;
}
if(doesntMatch)
continue;
//
Map<net.minecraft.world.level.material.Fluid,Integer> fluids = new HashMap<>();
List<FluidStack> totalFluidStacks = new ArrayList<>();
for(int i = 0;i<outputTank.getPrimaryHandler().getTanks();i++){
totalFluidStacks.add(outputTank.getPrimaryHandler().getFluidInTank(i));
}
totalFluidStacks.addAll(testedRecipe.getFluidResults());
for(FluidStack stack : totalFluidStacks){
if(stack.isEmpty())
continue;
if(fluids.containsKey(stack.getFluid())){
fluids.replace(stack.getFluid(),fluids.get(stack.getFluid())+stack.getAmount());
}else fluids.put(stack.getFluid(),stack.getAmount());
}
AtomicBoolean cantOutput= new AtomicBoolean(false);
fluids.forEach((f,a)-> {
if(a>4000)
cantOutput.set(true);
});
//
Map<Item,Integer> items = new HashMap<>();
List<ItemStack> totalItemStacks = new ArrayList<>();
for(int i = 0;i<outputInventory.getSlots();i++){
totalItemStacks.add(outputInventory.getStackInSlot(i));
}
totalItemStacks.addAll(testedRecipe.getRollableResultsAsItemStacks());
for(ItemStack stack : totalItemStacks){
if(stack.isEmpty())
continue;
if(items.containsKey(stack.getItem())){
items.replace(stack.getItem(),items.get(stack.getItem())+stack.getCount());
}else items.put(stack.getItem(),stack.getCount());
}
items.forEach((f,a)-> {
if(a>64)
cantOutput.set(true);
});
if(cantOutput.get())
continue;

View File

@@ -33,9 +33,9 @@ import static com.simibubi.create.foundation.utility.Debug.debugMessage;
public class SpoolItem extends Item {
final PartialModel model;
final int barColor;
final CableConnection.CableType type;
public final PartialModel model;
public final int barColor;
public final CableConnection.CableType type;
public SpoolItem(Properties properties, PartialModel model, int barColor, CableConnection.CableType type) {
super(properties);
@@ -106,13 +106,13 @@ public class SpoolItem extends Item {
return InteractionResult.SUCCESS;
}
if(level.getBlockEntity(posToConnect) instanceof CableConnectorBlockEntity be2) {
CableConnectorBlockEntity connectedBe1 = pos.asLong()>posToConnect.asLong() ? be2 : be;
CableConnectorBlockEntity connectedBe2= pos.asLong()>posToConnect.asLong() ? be : be2;
if(level.getBlockEntity(posToConnect) instanceof CableConnectorBlockEntity otherBE) {
//CableConnectorBlockEntity connectedBe1 = pos.asLong()>posToConnect.asLong() ? otherBE : be;
//CableConnectorBlockEntity connectedBe2= pos.asLong()>posToConnect.asLong() ? be : otherBE;
//
CableConnection connection1 = new CableConnection(connectedBe1.getCablePosition(), connectedBe2.getCablePosition(), connectedBe1.getBlockPos(), connectedBe2.getBlockPos(),type,true);
CableConnection connection2 = new CableConnection(connectedBe1.getCablePosition(), connectedBe2.getCablePosition(), connectedBe1.getBlockPos(), connectedBe2.getBlockPos(),type,false);
if(connectedBe1.connections.contains(connection1)||connectedBe1.connections.contains(connection1)){
CableConnection connection1 = new CableConnection(be.getCablePosition(), otherBE.getCablePosition(), otherBE.getBlockPos(),type,true);
CableConnection connection2 = new CableConnection(otherBE.getCablePosition(), be.getCablePosition(), be.getBlockPos(),type,false);
if(be.connections.contains(connection1)||otherBE.connections.contains(connection1)){
if (level.isClientSide)
player.displayClientMessage(Lang.translateDirect("wires.connection_already_created")
.withStyle(ChatFormatting.YELLOW), true);
@@ -122,18 +122,19 @@ public class SpoolItem extends Item {
return InteractionResult.SUCCESS;
}
if(!level.isClientSide) {
connectedBe1.connections.add(connection2);
connectedBe2.connections.add(connection1);
be.connections.add(connection1);
otherBE.connections.add(connection2);
be.onPlaced();
}
// connectedBe1.wiresUpdated();
connectedBe1.player = null;
connectedBe2.player = null;
connectedBe1.setChanged();
connectedBe2.setChanged();
connectedBe1.sendData();
connectedBe2.sendData();
be.player = null;
otherBE.player = null;
be.setChanged();
otherBE.setChanged();
be.sendData();
otherBE.sendData();
stack.getOrCreateTag().remove("Position");
stack.getOrCreateTag().remove("XPos");
stack.getOrCreateTag().remove("YPos");

View File

@@ -1,10 +1,14 @@
package com.drmangotea.tfmg.content.machinery.misc.winding_machine;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.content.engines.base.AbstractEngineBlockEntity;
import com.drmangotea.tfmg.recipes.PolarizingRecipe;
import com.drmangotea.tfmg.recipes.WindingRecipe;
import com.drmangotea.tfmg.registry.TFMGItems;
import com.drmangotea.tfmg.registry.TFMGRecipeTypes;
import com.simibubi.create.content.equipment.goggles.IHaveGoggleInformation;
import com.simibubi.create.content.kinetics.base.KineticBlockEntity;
import com.simibubi.create.content.processing.sequenced.SequencedAssemblyRecipe;
import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour;
import com.simibubi.create.foundation.blockEntity.behaviour.ValueBoxTransform;
import com.simibubi.create.foundation.blockEntity.behaviour.scrollValue.ScrollValueBehaviour;
@@ -25,6 +29,7 @@ import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.IItemHandlerModifiable;
import net.minecraftforge.items.ItemHandlerHelper;
import net.minecraftforge.items.wrapper.RecipeWrapper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -45,6 +50,7 @@ public class WindingMachineBlockEntity extends KineticBlockEntity implements IHa
public WindingRecipe recipe;
public int amountWinded = 0;
public boolean update = false;
protected ScrollValueBehaviour turnPercentage;
public WindingMachineBlockEntity(BlockEntityType<?> typeIn, BlockPos pos, BlockState state) {
@@ -52,10 +58,15 @@ public class WindingMachineBlockEntity extends KineticBlockEntity implements IHa
setLazyTickRate(10);
inventory = new SmartInventory(1, this)
.withMaxStackSize(1)
.whenContentsChanged(i->this.onContentsChanged());
.whenContentsChanged(i -> this.onContentsChanged());
itemCapability = LazyOptional.of(() -> inventory);
}
@Override
public void addBehaviours(List<BlockEntityBehaviour> behaviours) {
super.addBehaviours(behaviours);
@@ -67,74 +78,76 @@ public class WindingMachineBlockEntity extends KineticBlockEntity implements IHa
behaviours.add(turnPercentage);
}
public void onContentsChanged(){
findRecipe();
public void onContentsChanged() {
if(inventory.isEmpty())
findRecipe();
if (inventory.isEmpty())
amountWinded = 0;
}
public void findRecipe(){
Optional<WindingRecipe> optional = TFMGRecipeTypes.WINDING.find(new RecipeWrapper(inventory), level);
if(optional.isEmpty()) {
public void findRecipe() {
Optional<WindingRecipe> optional = TFMGRecipeTypes.WINDING.find(new RecipeWrapper(inventory), level);
Optional<WindingRecipe> assemblyRecipe = SequencedAssemblyRecipe.getRecipe(this.level, inventory, TFMGRecipeTypes.WINDING.getType(), WindingRecipe.class);
if (assemblyRecipe.isPresent()) {
recipe = assemblyRecipe.get();
return;
}
if (optional.isEmpty()) {
recipe = null;
return;
}
WindingRecipe windingRecipe = optional.get();
if(windingRecipe.getIngredient().test(inventory.getItem(0))){
if (windingRecipe.getIngredient().test(inventory.getItem(0))) {
recipe = windingRecipe;
}
}
@Override
public void lazyTick() {
super.lazyTick();
onContentsChanged();
if(spool.is(TFMGItems.EMPTY_SPOOL.get())&&!getBlockState().getValue(POWERED)){
level.setBlock(getBlockPos(), getBlockState().setValue(POWERED, true),2);
if (spool.is(TFMGItems.EMPTY_SPOOL.get()) && !getBlockState().getValue(POWERED)) {
level.setBlock(getBlockPos(), getBlockState().setValue(POWERED, true), 2);
update = true;
}
if(!spool.is(TFMGItems.EMPTY_SPOOL.get())&&getBlockState().getValue(POWERED)){
level.setBlock(getBlockPos(), getBlockState().setValue(POWERED, false),2);
if (!spool.is(TFMGItems.EMPTY_SPOOL.get()) && getBlockState().getValue(POWERED)) {
level.setBlock(getBlockPos(), getBlockState().setValue(POWERED, false), 2);
update = true;
}
}
@Override
public boolean addToGoggleTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
Lang.translate("goggles.winding_machine.header")
.style(ChatFormatting.WHITE)
.forGoggles(tooltip,1);
if(!spool.isEmpty())
Lang.translate("goggles.winding_machine.header")
.style(ChatFormatting.WHITE)
.forGoggles(tooltip, 1);
if (!spool.isEmpty())
Lang.text(" ")
.add(Component.translatable("recipe.winding_machine.wire_left"))
.style(ChatFormatting.WHITE)
.add(Component.literal(" "+spool.getOrCreateTag().getInt("Amount")))
.add(Component.literal(" " + spool.getOrCreateTag().getInt("Amount")))
.color(spool.getBarColor())
.add(Component.literal("/1000"))
.style(ChatFormatting.WHITE)
.forGoggles(tooltip);
if(inventory.getItem(0).is(TFMGItems.ELECTROMAGNETIC_COIL.get())) {
if (inventory.getItem(0).is(TFMGItems.ELECTROMAGNETIC_COIL.get())) {
Lang.text(" ")
.add(Component.translatable("goggles.winding_machine.coil_turns"))
.style(ChatFormatting.WHITE)
.add(Component.literal(" " + inventory.getItem(0).getOrCreateTag().getInt("Turns")))
.forGoggles(tooltip);
}else
if(recipe!=null)
} else if (recipe != null)
Lang.text(" ")
.add(Component.translatable("goggles.winding_machine.wire_needed"))
.style(ChatFormatting.WHITE)
.add(Component.literal(" "+amountWinded))
.add(Component.literal(" " + amountWinded))
.color(spool.getBarColor())
.add(Component.literal("/"+recipe.getProcessingDuration()))
.add(Component.literal("/" + recipe.getProcessingDuration()))
.style(ChatFormatting.WHITE)
.forGoggles(tooltip);
return true;
@@ -143,58 +156,60 @@ public class WindingMachineBlockEntity extends KineticBlockEntity implements IHa
@Override
public void tick() {
super.tick();
performRecipe();
if(update){
if (update) {
level.updateNeighborsAt(getBlockPos(), getBlockState().getBlock());
update = false;
}
if(level.isClientSide)
if (level.isClientSide)
manageRotation();
}
public void performRecipe(){
if(getSpeed() ==0 )
public void performRecipe() {
if (getSpeed() == 0)
return;
if(inventory.getItem(0).is(TFMGItems.ELECTROMAGNETIC_COIL.get())&&spool.is(TFMGItems.COPPER_SPOOL.get())&&spool.getOrCreateTag().getInt("Amount")>0&&inventory.getItem(0).getOrCreateTag().getInt("Turns")< turnPercentage.getValue()*10){
if (inventory.getItem(0).is(TFMGItems.ELECTROMAGNETIC_COIL.get()) && spool.is(TFMGItems.COPPER_SPOOL.get()) && spool.getOrCreateTag().getInt("Amount") > 0 && inventory.getItem(0).getOrCreateTag().getInt("Turns") < turnPercentage.getValue() * 10) {
spool.getOrCreateTag().putInt("Amount", spool.getOrCreateTag().getInt("Amount") - 1);
inventory.getItem(0).getOrCreateTag().putInt("Turns", inventory.getItem(0).getOrCreateTag().getInt("Turns") + 1);
return;
}
if (inventory.getItem(0).is(TFMGItems.UNFINISHED_RESISTOR.get()) && spool.is(TFMGItems.CONSTANTAN_SPOOL.get()) && spool.getOrCreateTag().getInt("Amount") > 0 && inventory.getItem(0).getOrCreateTag().getInt("Resistance") < turnPercentage.getValue() * 10) {
spool.getOrCreateTag().putInt("Amount", spool.getOrCreateTag().getInt("Amount") - 1);
inventory.getItem(0).getOrCreateTag().putInt("Resistance", inventory.getItem(0).getOrCreateTag().getInt("Resistance") + 1);
return;
}
if(spool.getOrCreateTag().getInt("Amount") == 0&&!spool.is(TFMGItems.EMPTY_SPOOL.get())&&spool.getItem() instanceof SpoolItem)
if (spool.getOrCreateTag().getInt("Amount") == 0 && !spool.is(TFMGItems.EMPTY_SPOOL.get()) && spool.getItem() instanceof SpoolItem)
spool = TFMGItems.EMPTY_SPOOL.asStack();
if(recipe == null) {
if (recipe == null) {
return;
}
if(amountWinded >= recipe.getProcessingDuration()){
inventory.setStackInSlot(0, recipe.getResultItem(level.registryAccess()));
if (amountWinded >= recipe.getProcessingDuration()) {
inventory.setStackInSlot(0, recipe.rollResults().get(0));
recipe = null;
amountWinded = 0;
sendData();
setChanged();
}else {
if(spool.isEmpty()||spool.is(TFMGItems.EMPTY_SPOOL.get())) {
} else {
if (spool.isEmpty() || spool.is(TFMGItems.EMPTY_SPOOL.get())) {
return;
}
if(spool.getOrCreateTag().getInt("Amount")>0) {
if(recipe.getSpool().test(spool)) {
if (spool.getOrCreateTag().getInt("Amount") > 0) {
if (recipe.getSpool().test(spool)) {
spool.getOrCreateTag().putInt("Amount", spool.getOrCreateTag().getInt("Amount") - 1);
amountWinded++;
}
} else {
inventory.setStackInSlot(0, recipe.getResultItem(level.registryAccess()));
inventory.setStackInSlot(0, recipe.rollResults().get(0));
sendData();
setChanged();
}
@@ -205,14 +220,14 @@ public class WindingMachineBlockEntity extends KineticBlockEntity implements IHa
@Override
public @NotNull <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) {
if(cap == ForgeCapabilities.ITEM_HANDLER)
if (cap == ForgeCapabilities.ITEM_HANDLER)
return itemCapability.cast();
return super.getCapability(cap, side);
}
public void manageRotation(){
float targetSpeed = (float) Math.min(Math.abs(getSpeed()*1.5),30);
public void manageRotation() {
float targetSpeed = (float) Math.min(Math.abs(getSpeed() * 1.5), 30);
spoolSpeed.updateChaseTarget(targetSpeed);
spoolSpeed.tickChaser();
@@ -238,7 +253,8 @@ public class WindingMachineBlockEntity extends KineticBlockEntity implements IHa
if (clientPacket)
spoolSpeed.chase(getGeneratedSpeed(), 1 / 16f, LerpedFloat.Chaser.EXP);
}
class WindingMachineValueBox extends ValueBoxTransform.Sided {
public static class WindingMachineValueBox extends ValueBoxTransform.Sided {
@Override
protected Vec3 getSouthLocation() {
return VecHelper.voxelSpace(8, 4, 16.05);

View File

@@ -42,6 +42,7 @@ public class WindingMachineRenderer extends KineticBlockEntityRenderer<WindingMa
}
if(!be.spool.isEmpty()) {
CachedBufferer.partial(TFMGPartialModels.SPOOL, blockState)
.light(light)
.centre()
.rotateY(blockState.getValue(HORIZONTAL_FACING).getAxis() == Direction.Axis.Z ? Math.abs(blockState.getValue(FACING).toYRot() - 180) : blockState.getValue(FACING).toYRot())
.translateZ(-0.4)
@@ -51,6 +52,7 @@ public class WindingMachineRenderer extends KineticBlockEntityRenderer<WindingMa
.renderInto(ms, bufferSource.getBuffer(RenderType.cutoutMipped()));
if(((SpoolItem)be.spool.getItem()).model !=null){
CachedBufferer.partial(((SpoolItem)be.spool.getItem()).model, blockState)
.light(light)
.centre()
.rotateY(blockState.getValue(HORIZONTAL_FACING).getAxis() == Direction.Axis.Z ? Math.abs(blockState.getValue(FACING).toYRot() - 180) : blockState.getValue(FACING).toYRot())
.translateZ(-0.4)
@@ -62,6 +64,7 @@ public class WindingMachineRenderer extends KineticBlockEntityRenderer<WindingMa
if(!be.inventory.isEmpty()){
CachedBufferer.partial(be.getSpeed()!=0 ? TFMGPartialModels.CONNNECTING_WIRE_ANIMATED : TFMGPartialModels.CONNNECTING_WIRE, blockState)
.light(light)
.centre()
.rotateY(blockState.getValue(HORIZONTAL_FACING).getAxis() == Direction.Axis.Z ? Math.abs(blockState.getValue(FACING).toYRot() - 180) : blockState.getValue(FACING).toYRot())
.translateY(0.4f)

View File

@@ -98,7 +98,7 @@ public class DistillationControllerBlockEntity extends SmartBlockEntity implemen
return;
for (DistillationOutputBlockEntity be1 : outputs) {
if (be1.tank.getSpace() == 0)
if (be1.tank.getSpace() == 0&&be1.mode.get() == DistillationOutputBlockEntity.DistillationOutputMode.KEEP_FLUID)
return;
}
int numero = 0;
@@ -106,7 +106,7 @@ public class DistillationControllerBlockEntity extends SmartBlockEntity implemen
FluidStack fluidStack = recipe.getFluidResults().get(numero);
if (fluidStack.isEmpty())
break;
if (output.tank.fill(new FluidStack(fluidStack, (int) (fluidStack.getAmount() * speedModifier)), IFluidHandler.FluidAction.SIMULATE) > output.tank.getCapacity())
if (output.tank.fill(new FluidStack(fluidStack, (int) (fluidStack.getAmount() * speedModifier)), IFluidHandler.FluidAction.SIMULATE) > output.tank.getCapacity()&&output.mode.get() == DistillationOutputBlockEntity.DistillationOutputMode.KEEP_FLUID)
break;
output.tank.fill(new FluidStack(fluidStack, (int) (fluidStack.getAmount() * speedModifier)), IFluidHandler.FluidAction.EXECUTE);

View File

@@ -1,15 +1,25 @@
package com.drmangotea.tfmg.content.machinery.oil_processing.distillation_tower.output;
import com.drmangotea.tfmg.base.TFMGIcons;
import com.simibubi.create.content.equipment.goggles.IHaveGoggleInformation;
import com.simibubi.create.content.kinetics.mechanicalArm.ArmBlockEntity;
import com.simibubi.create.foundation.advancement.AllAdvancements;
import com.simibubi.create.foundation.blockEntity.SmartBlockEntity;
import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour;
import com.simibubi.create.foundation.blockEntity.behaviour.ValueBoxTransform;
import com.simibubi.create.foundation.blockEntity.behaviour.scrollValue.INamedIconOptions;
import com.simibubi.create.foundation.blockEntity.behaviour.scrollValue.ScrollOptionBehaviour;
import com.simibubi.create.foundation.fluid.SmartFluidTank;
import com.simibubi.create.foundation.gui.AllIcons;
import com.simibubi.create.foundation.utility.Lang;
import com.simibubi.create.foundation.utility.VecHelper;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.common.util.LazyOptional;
@@ -20,11 +30,15 @@ import net.minecraftforge.fluids.capability.templates.FluidTank;
import javax.annotation.Nonnull;
import java.util.List;
import static com.simibubi.create.content.kinetics.base.HorizontalKineticBlock.HORIZONTAL_FACING;
public class DistillationOutputBlockEntity extends SmartBlockEntity implements IHaveGoggleInformation {
protected LazyOptional<IFluidHandler> fluidCapability;
public ScrollOptionBehaviour<DistillationOutputMode> mode;
public final FluidTank tank = new SmartFluidTank(8000,this::onFluidStackChanged);
public DistillationOutputBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
@@ -32,20 +46,19 @@ public class DistillationOutputBlockEntity extends SmartBlockEntity implements I
}
@Override
public void addBehaviours(List<BlockEntityBehaviour> behaviours) {}
public void addBehaviours(List<BlockEntityBehaviour> behaviours) {
mode = new ScrollOptionBehaviour<DistillationOutputMode>(DistillationOutputMode.class,
Lang.translateDirect("distillation_output.when_tank_is_full"), this, new DistillationOutputValueBox());
behaviours.add(mode);
}
protected void onFluidStackChanged(FluidStack newFluidStack) {
if (!hasLevel())
return;
if (!level.isClientSide) {
setChanged();
sendData();
}
}
@Nonnull
@@ -66,7 +79,7 @@ public class DistillationOutputBlockEntity extends SmartBlockEntity implements I
@Override
public void write(CompoundTag compound, boolean clientPacket) {
super.write(compound,clientPacket);
compound.put("TankContent", tank.writeToNBT(new CompoundTag()));
@@ -80,4 +93,37 @@ public class DistillationOutputBlockEntity extends SmartBlockEntity implements I
}
public static class DistillationOutputValueBox extends ValueBoxTransform.Sided {
@Override
protected Vec3 getSouthLocation() {
return VecHelper.voxelSpace(8, 8, 16.05);
}
@Override
protected boolean isSideActive(BlockState state, Direction direction) {
return direction.getAxis().isHorizontal();
}
}
public enum DistillationOutputMode implements INamedIconOptions {
KEEP_FLUID(TFMGIcons.DISTILLATION_OUTPUT_ICON_DO_NOT_VOID),
VOID_WHEN_FULL(TFMGIcons.DISTILLATION_OUTPUT_ICON_VOID);
final AllIcons icon;
DistillationOutputMode(AllIcons icon){
this.icon = icon;
}
@Override
public AllIcons getIcon() {
return icon;
}
@Override
public String getTranslationKey() {
return "distillation_output.mode."+ Lang.asId(name());
}
}
}

View File

@@ -3,10 +3,7 @@ package com.drmangotea.tfmg.datagen;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.base.TFMGRegistrateTags;
import com.drmangotea.tfmg.datagen.recipes.TFMGProcessingRecipeGen;
import com.drmangotea.tfmg.datagen.recipes.values.CastingRecipeGen;
import com.drmangotea.tfmg.datagen.recipes.values.TFMGStandardRecipeGen;
import com.drmangotea.tfmg.datagen.recipes.values.IndustrialBlastingRecipeGen;
import com.drmangotea.tfmg.datagen.recipes.values.VatRecipeGen;
import com.drmangotea.tfmg.datagen.recipes.values.*;
import com.drmangotea.tfmg.ponder.TFMGPonderIndex;
import com.drmangotea.tfmg.ponder.TFMGPonderTag;
import com.google.gson.JsonElement;
@@ -48,6 +45,7 @@ public class TFMGDatagen {
generator.addProvider(true, new CastingRecipeGen(output));
generator.addProvider(true, new VatRecipeGen(output));
generator.addProvider(true, new TFMGStandardRecipeGen(output));
generator.addProvider(true, new TFMGSequencedAssemblyRecipeGen(output));
TFMGProcessingRecipeGen.registerAll(generator, output);
}

View File

@@ -90,6 +90,9 @@ public class TFMGRecipeProvider extends RecipeProvider {
public static TagKey<Item> steelNugget() {
return TFMGTags.forgeItemTag("nuggets/steel");
}
public static TagKey<Item> steelSheet() {
return TFMGTags.forgeItemTag("plates/steel");
}
public static TagKey<Item> steelBlock() {
return TFMGTags.forgeItemTag("storage_blocks/steel");
}
@@ -102,6 +105,9 @@ public class TFMGRecipeProvider extends RecipeProvider {
public static TagKey<Item> aluminumBlock() {
return TFMGTags.forgeItemTag("storage_blocks/aluminum");
}
public static TagKey<Item> aluminumSheet() {
return TFMGTags.forgeItemTag("plates/aluminum");
}
public static TagKey<Item> castIronIngot() {
return TFMGTags.forgeItemTag("ingots/cast_iron");
}
@@ -129,6 +135,9 @@ public class TFMGRecipeProvider extends RecipeProvider {
public static TagKey<Item> nickelBlock() {
return TFMGTags.forgeItemTag("storage_blocks/nickel");
}
public static TagKey<Item> nickelSheet() {
return TFMGTags.forgeItemTag("plates/nickel");
}
public static TagKey<Item> lithiumIngot() {
return TFMGTags.forgeItemTag("ingots/lithium");
}
@@ -147,6 +156,9 @@ public class TFMGRecipeProvider extends RecipeProvider {
public static TagKey<Item> constantanBlock() {
return TFMGTags.forgeItemTag("storage_blocks/constantan");
}
public static TagKey<Item> copperWire() {
return TFMGTags.forgeItemTag("wires/copper");
}
//
public static ItemLike bitumen() {
@@ -278,6 +290,9 @@ public class TFMGRecipeProvider extends RecipeProvider {
public static ItemLike magneticIngot() {
return TFMGItems.MAGNETIC_ALLOY_INGOT.get();
}
public static ItemLike magnet() {
return TFMGItems.MAGNET.get();
}
//
public static TagKey<Item> redstone() {
return Tags.Items.DUSTS_REDSTONE;

View File

@@ -0,0 +1,100 @@
package com.drmangotea.tfmg.datagen.recipes.values;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.recipes.WindingRecipe;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.drmangotea.tfmg.registry.TFMGFluids;
import com.drmangotea.tfmg.registry.TFMGItems;
import com.simibubi.create.AllItems;
import com.simibubi.create.content.fluids.transfer.FillingRecipe;
import com.simibubi.create.content.kinetics.deployer.DeployerApplicationRecipe;
import com.simibubi.create.content.kinetics.press.PressingRecipe;
import com.simibubi.create.content.processing.sequenced.SequencedAssemblyRecipeBuilder;
import com.simibubi.create.foundation.data.recipe.CreateRecipeProvider;
import net.minecraft.data.PackOutput;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import java.util.function.UnaryOperator;
import static com.drmangotea.tfmg.datagen.recipes.TFMGRecipeProvider.I.*;
import static com.drmangotea.tfmg.datagen.recipes.TFMGRecipeProvider.F.*;
public class TFMGSequencedAssemblyRecipeGen extends CreateRecipeProvider {
GeneratedRecipe POTENTIOMETER = create("potentiometer", b -> b.require(TFMGBlocks.HEAVY_MACHINERY_CASING.get())
.transitionTo(TFMGItems.UNFINISHED_POTENTIOMETER.get())
.addOutput(TFMGBlocks.POTENTIOMETER.get(), 120)
.addOutput(TFMGBlocks.STEEL_CASING.get(), 8)
.addOutput(TFMGBlocks.STEEL_COGWHEEL.get(), 8)
.addOutput(TFMGBlocks.ELECTRIC_POST.get(), 8)
.loops(3)
.addStep(WindingRecipe::new, rb -> rb.require(TFMGItems.CONSTANTAN_SPOOL.get()).duration(100))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(TFMGBlocks.STEEL_COGWHEEL))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(TFMGItems.COPPER_WIRE))
.addStep(FillingRecipe::new, rb -> rb.require(lubricationOil(), 50))),
GENERATOR = create("generator", b -> b.require(shaft())
.transitionTo(TFMGItems.UNFINISHED_GENERATOR.get())
.addOutput(TFMGBlocks.GENERATOR.get(), 120)
.addOutput(TFMGBlocks.STEEL_CASING.get(), 8)
.addOutput(TFMGBlocks.STEEL_COGWHEEL.get(), 8)
.addOutput(TFMGItems.CAPACITOR.get(), 8)
.loops(5)
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(TFMGItems.CAPACITOR))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(steelSheet()))
.addStep(WindingRecipe::new, rb -> rb.require(TFMGItems.COPPER_SPOOL.get()).duration(75))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(magnet()))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(steelMechanism()))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(TFMGItems.SCREWDRIVER))
),
MOTOR = create("motor", b -> b.require(shaft())
.transitionTo(TFMGItems.UNFINISHED_GENERATOR.get())
.addOutput(TFMGBlocks.ELECTRIC_MOTOR.get(), 120)
.addOutput(TFMGBlocks.STEEL_CASING.get(), 8)
.addOutput(TFMGItems.NICKEL_SHEET.get(), 8)
.loops(5)
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(nickelSheet()))
.addStep(WindingRecipe::new, rb -> rb.require(TFMGItems.COPPER_SPOOL.get()).duration(75))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(magnet()))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(steelSheet()))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(steelMechanism()))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(TFMGItems.SCREWDRIVER))
),
TRANSISTOR_PLASTIC = create("transistor", b -> b.require(plasticSheet())
.transitionTo(TFMGItems.UNFINISHED_TRANSISTOR.get())
.addOutput(new ItemStack(TFMGItems.TRANSISTOR.get(),4), 120)
.addOutput(TFMGItems.SILICON_INGOT.get(), 8)
.addOutput(TFMGItems.P_SEMICONDUCTOR.get(), 8)
.addOutput(TFMGItems.N_SEMICONDUCTOR.get(), 8)
.loops(1)
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(copperWire()))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(TFMGItems.N_SEMICONDUCTOR))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(TFMGItems.P_SEMICONDUCTOR))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(TFMGItems.N_SEMICONDUCTOR))),
CAPACITOR = create("capacitor", b -> b.require(steelSheet())
.transitionTo(TFMGItems.UNFINISHED_CAPACITOR.get())
.addOutput(new ItemStack(TFMGItems.CAPACITOR.get(),4), 1)
.loops(1)
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(copperSheet()))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(Items.PAPER))
.addStep(DeployerApplicationRecipe::new, rb -> rb.require(copperSheet())));
public TFMGSequencedAssemblyRecipeGen(PackOutput p_i48262_1_) {
super(p_i48262_1_);
}
protected GeneratedRecipe create(String name, UnaryOperator<SequencedAssemblyRecipeBuilder> transform) {
GeneratedRecipe generatedRecipe =
c -> transform.apply(new SequencedAssemblyRecipeBuilder(TFMG.asResource(name)))
.build(c);
all.add(generatedRecipe);
return generatedRecipe;
}
}

View File

@@ -1,6 +1,7 @@
package com.drmangotea.tfmg.mixin;
import com.drmangotea.tfmg.content.decoration.pipes.TFMGPipes;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.simibubi.create.AllBlocks;
import com.simibubi.create.AllTags;
import com.simibubi.create.content.fluids.FluidPropagator;
@@ -90,8 +91,8 @@ public class FluidPropagatorMixin {
!TFMGPipes.TFMG_PIPES.get(TFMGPipes.PipeMaterial.PLASTIC).get(3).has(targetState)&&
!TFMGPipes.TFMG_PIPES.get(TFMGPipes.PipeMaterial.BRASS).get(3).has(targetState)&&
!TFMGPipes.TFMG_PIPES.get(TFMGPipes.PipeMaterial.ALUMINUM).get(3).has(targetState)&&
!TFMGPipes.TFMG_PIPES.get(TFMGPipes.PipeMaterial.CAST_IRON).get(3).has(targetState)
!TFMGPipes.TFMG_PIPES.get(TFMGPipes.PipeMaterial.CAST_IRON).get(3).has(targetState)&&
!TFMGBlocks.ELECTRIC_PUMP.has(targetState)
|| targetState.getValue(PumpBlock.FACING)
.getAxis() != direction.getAxis())
continue;

View File

@@ -1,5 +1,6 @@
package com.drmangotea.tfmg.mixin;
import com.drmangotea.tfmg.datagen.recipes.values.TFMGSequencedAssemblyRecipeGen;
import com.drmangotea.tfmg.datagen.recipes.values.TFMGStandardRecipeGen;
import com.drmangotea.tfmg.datagen.recipes.values.IndustrialBlastingRecipeGen;
import com.drmangotea.tfmg.datagen.recipes.values.VatRecipeGen;
@@ -21,6 +22,8 @@ public class RecipeProviderMixin {
cir.setReturnValue("TFMG'S Vat Recipes");
if((Object)this instanceof TFMGStandardRecipeGen)
cir.setReturnValue("TFMG'S Standard Recipes");
if((Object)this instanceof TFMGSequencedAssemblyRecipeGen)
cir.setReturnValue("TFMG'S Sequenced Assembly Recipes");
}

View File

@@ -1,5 +1,6 @@
package com.drmangotea.tfmg.recipes;
import com.drmangotea.tfmg.recipes.jei.PolarizingCategory;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.drmangotea.tfmg.registry.TFMGRecipeTypes;
import com.google.gson.JsonObject;
@@ -58,8 +59,7 @@ public class PolarizingRecipe extends ProcessingRecipe<RecipeWrapper> implements
@Override
public Supplier<Supplier<SequencedAssemblySubCategory>> getJEISubCategory() {
// return () -> PolarizingCategory.AssemblyPolarizing::new;
return null;
return () -> PolarizingCategory.AssemblyPolarizing::new;
}

View File

@@ -1,5 +1,6 @@
package com.drmangotea.tfmg.recipes;
import com.drmangotea.tfmg.recipes.jei.WindingCategory;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.drmangotea.tfmg.registry.TFMGRecipeTypes;
import com.simibubi.create.compat.jei.category.sequencedAssembly.SequencedAssemblySubCategory;
@@ -61,11 +62,11 @@ public class WindingRecipe extends ProcessingRecipe<RecipeWrapper> implements I
@Override
public void addAssemblyIngredients(List<Ingredient> list) {
list.add(ingredients.get(1));
}
@Override
public Supplier<Supplier<SequencedAssemblySubCategory>> getJEISubCategory() {
return null;
return ()->WindingCategory.AssemblyWinding::new;
}
}

View File

@@ -1,8 +1,6 @@
package com.drmangotea.tfmg.recipes.jei;
import com.drmangotea.tfmg.recipes.CastingRecipe;
import com.drmangotea.tfmg.recipes.jei.machines.CastingSetup;
import com.drmangotea.tfmg.registry.TFMGItems;
@@ -23,59 +21,42 @@ import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
public class CastingCategory extends CreateRecipeCategory<CastingRecipe> {
private final CastingSetup castingSetup = new CastingSetup();
private final CastingSetup castingSetup = new CastingSetup();
public CastingCategory(Info<CastingRecipe> info) {
super(info);
}
public CastingCategory(Info<CastingRecipe> info) {
super(info);
}
@Override
public void setRecipe(IRecipeLayoutBuilder builder, CastingRecipe recipe, IFocusGroup focuses) {
@Override
public void setRecipe(IRecipeLayoutBuilder builder, CastingRecipe recipe, IFocusGroup focuses) {
RegistryAccess registryAccess = Minecraft.getInstance().level.registryAccess();
builder
.addSlot(RecipeIngredientRole.OUTPUT, 130, 20)
.setBackground(getRenderedSlot(), -1, -1)
.addItemStack(recipe.getResultItem(registryAccess));
builder
.addSlot(RecipeIngredientRole.INPUT, 15, 20)
.setBackground(getRenderedSlot(), -1, -1)
.addIngredients(ForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getFluidIngredients().get(0).getMatchingFluidStacks()))
.addTooltipCallback(addFluidTooltip(recipe.getFluidIngredients().get(0).getRequiredAmount()));
RegistryAccess registryAccess = Minecraft.getInstance().level.registryAccess();
builder
.addSlot(RecipeIngredientRole.OUTPUT, 130, 0)
.setBackground(getRenderedSlot(), -1, -1)
.addItemStack(recipe.getResultItem(registryAccess));
}
@Override
public void draw(CastingRecipe recipe, IRecipeSlotsView iRecipeSlotsView, GuiGraphics graphics, double mouseX, double mouseY) {
castingSetup
.draw(graphics, 72, 40);
AllGuiTextures.JEI_ARROW.render(graphics, 78, 23);
//fluid
builder
.addSlot(RecipeIngredientRole.INPUT, 2, 33)
.setBackground(getRenderedSlot(), -1, -1)
.addIngredients(ForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getFluidIngredients().get(0).getMatchingFluidStacks()))
.addTooltipCallback(addFluidTooltip(recipe.getFluidIngredients().get(0).getRequiredAmount()));
}
@Override
public void draw(CastingRecipe recipe, IRecipeSlotsView iRecipeSlotsView, GuiGraphics graphics, double mouseX, double mouseY) {
castingSetup
.draw(graphics, 65, 50);
AllGuiTextures.JEI_ARROW.render(graphics, 20, 36);
}
}
}

View File

@@ -0,0 +1,71 @@
package com.drmangotea.tfmg.recipes.jei;
import com.drmangotea.tfmg.recipes.DistillationRecipe;
import com.drmangotea.tfmg.recipes.HotBlastRecipe;
import com.drmangotea.tfmg.registry.TFMGGuiTextures;
import com.simibubi.create.compat.jei.category.CreateRecipeCategory;
import com.simibubi.create.foundation.fluid.FluidIngredient;
import com.simibubi.create.foundation.gui.AllGuiTextures;
import mezz.jei.api.forge.ForgeTypes;
import mezz.jei.api.gui.builder.IRecipeLayoutBuilder;
import mezz.jei.api.gui.ingredient.IRecipeSlotsView;
import mezz.jei.api.recipe.IFocusGroup;
import mezz.jei.api.recipe.RecipeIngredientRole;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraftforge.fluids.FluidStack;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
public class HotBlastCategory extends CreateRecipeCategory<HotBlastRecipe> {
public HotBlastCategory(Info<HotBlastRecipe> info) {
super(info);
}
@Override
public void setRecipe(IRecipeLayoutBuilder builder, HotBlastRecipe recipe, IFocusGroup focuses) {
builder
.addSlot(RecipeIngredientRole.INPUT, 18, 52)
.setBackground(getRenderedSlot(), -1, -1)
.addIngredients(ForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getFluidIngredients().get(0).getMatchingFluidStacks()))
.addTooltipCallback(addFluidTooltip(recipe.getFluidIngredients().get(0).getRequiredAmount()));
builder
.addSlot(RecipeIngredientRole.INPUT, 18, 74)
.setBackground(getRenderedSlot(), -1, -1)
.addIngredients(ForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getFluidIngredients().get(1).getMatchingFluidStacks()))
.addTooltipCallback(addFluidTooltip(recipe.getFluidIngredients().get(1).getRequiredAmount()));
/// /
builder
.addSlot(RecipeIngredientRole.OUTPUT, 105, 51)
.setBackground(getRenderedSlot(), -1, -1)
.addIngredient(ForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getFluidResults().get(0)))
.addTooltipCallback(addFluidTooltip(recipe.getFluidResults().get(0).getAmount()));
builder
.addSlot(RecipeIngredientRole.OUTPUT, 105, 75)
.setBackground(getRenderedSlot(), -1, -1)
.addIngredient(ForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getFluidResults().get(1)))
.addTooltipCallback(addFluidTooltip(recipe.getFluidResults().get(1).getAmount()));
}
@Override
public void draw(HotBlastRecipe recipe, IRecipeSlotsView iRecipeSlotsView, GuiGraphics graphics, double mouseX, double mouseY) {
TFMGGuiTextures.BLAST_STOVE.render(graphics, 10, 0);
AllGuiTextures.JEI_ARROW.render(graphics, 56, 55);
AllGuiTextures.JEI_ARROW.render(graphics, 56, 78);
}
}

View File

@@ -32,41 +32,41 @@ public class IndustrialBlastingCategory extends CreateRecipeCategory<IndustrialB
public void setRecipe(IRecipeLayoutBuilder builder, IndustrialBlastingRecipe recipe, IFocusGroup focuses) {
builder
.addSlot(RecipeIngredientRole.INPUT, 25, 13)
.setBackground(getRenderedSlot(), -1, -1)
.addIngredients(recipe.getIngredients().get(0));
// builder
// .addSlot(RecipeIngredientRole.INPUT, 25, 13)
// .setBackground(getRenderedSlot(), -1, -1)
// .addIngredients(recipe.getIngredients().get(0));
builder
.addSlot(RecipeIngredientRole.INPUT, 5, 13)
.setBackground(getRenderedSlot(), -1, -1)
.addItemStack(new ItemStack(TFMGItems.COAL_COKE_DUST.get(),2));
// builder
// .addSlot(RecipeIngredientRole.INPUT, 5, 13)
// .setBackground(getRenderedSlot(), -1, -1)
// .addItemStack(new ItemStack(TFMGItems.COAL_COKE_DUST.get(),2));
//fluid
// //fluid
builder
.addSlot(RecipeIngredientRole.OUTPUT,140, 117)
.setBackground(getRenderedSlot(), -1, -1)
.addIngredient(ForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getFluidResults().get(0)))
.addTooltipCallback(addFluidTooltip(recipe.getFluidResults().get(0).getAmount()));
// builder
// .addSlot(RecipeIngredientRole.OUTPUT,140, 117)
// .setBackground(getRenderedSlot(), -1, -1)
// .addIngredient(ForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getFluidResults().get(0)))
// .addTooltipCallback(addFluidTooltip(recipe.getFluidResults().get(0).getAmount()));
builder
.addSlot(RecipeIngredientRole.OUTPUT,160, 117)
.setBackground(getRenderedSlot(), -1, -1)
.addIngredient(ForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getFluidResults().get(1)))
.addTooltipCallback(addFluidTooltip(recipe.getFluidResults().get(1).getAmount()));
//builder
// .addSlot(RecipeIngredientRole.OUTPUT,160, 117)
// .setBackground(getRenderedSlot(), -1, -1)
// .addIngredient(ForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getFluidResults().get(1)))
// .addTooltipCallback(addFluidTooltip(recipe.getFluidResults().get(1).getAmount()));
}
@Override
public void draw(IndustrialBlastingRecipe recipe, IRecipeSlotsView iRecipeSlotsView, GuiGraphics graphics, double mouseX, double mouseY) {
blastFurnace
.draw(graphics, 50, 135);
AllGuiTextures.JEI_ARROW.render(graphics, 96, 121);
AllGuiTextures.JEI_DOWN_ARROW.render(graphics, 45, 15);
//blastFurnace
// .draw(graphics, 50, 135);
//
//
//AllGuiTextures.JEI_ARROW.render(graphics, 96, 121);
//
//AllGuiTextures.JEI_DOWN_ARROW.render(graphics, 45, 15);
}

View File

@@ -48,8 +48,6 @@ public class PolarizingCategory extends CreateRecipeCategory<PolarizingRecipe> {
}
public void setRecipe(IRecipeLayoutBuilder builder, SequencedRecipe<?> recipe, IFocusGroup focuses, int x) {
IRecipeSlotBuilder slot = builder.addSlot(RecipeIngredientRole.INPUT, x + 4, 15).setBackground(CreateRecipeCategory.getRenderedSlot(), -1, -1).addIngredients(recipe.getRecipe().getIngredients().get(0));
IAssemblyRecipe var7 = recipe.getAsAssemblyRecipe();
}

View File

@@ -1,5 +1,6 @@
package com.drmangotea.tfmg.recipes.jei;
import com.drmangotea.tfmg.TFMG;
import com.drmangotea.tfmg.recipes.*;
import com.drmangotea.tfmg.registry.TFMGBlocks;
import com.drmangotea.tfmg.registry.TFMGRecipeTypes;
@@ -43,7 +44,7 @@ import java.util.function.Supplier;
@ParametersAreNonnullByDefault
public class TFMGJei implements IModPlugin {
private static final ResourceLocation ID = Create.asResource("jei_plugin");
private static final ResourceLocation ID = TFMG.asResource("jei_plugin");
private final List<CreateRecipeCategory<?>> allCategories = new ArrayList<>();
private IIngredientManager ingredientManager;
@@ -53,8 +54,6 @@ public class TFMGJei implements IModPlugin {
CreateRecipeCategory<?>
advancedDistillation = builder(DistillationRecipe.class)
.addTypedRecipes(TFMGRecipeTypes.DISTILLATION)
.catalyst(TFMGBlocks.STEEL_DISTILLATION_CONTROLLER::get)
@@ -63,38 +62,51 @@ public class TFMGJei implements IModPlugin {
.emptyBackground(177, 150)
.build("advanced_distillation", DistillationCategory::new),
coking = builder(CokingRecipe.class)
.addTypedRecipes(TFMGRecipeTypes.COKING)
.catalyst(TFMGBlocks.COKE_OVEN::get)
.emptyBackground(177, 123)
.build("coking", CokingCategory::new),
coking = builder(CokingRecipe.class)
.addTypedRecipes(TFMGRecipeTypes.COKING)
.catalyst(TFMGBlocks.COKE_OVEN::get)
.emptyBackground(177, 123)
.build("coking", CokingCategory::new),
industrial_blasting = builder(IndustrialBlastingRecipe.class)
.addTypedRecipes(TFMGRecipeTypes.INDUSTRIAL_BLASTING)
.catalyst(TFMGBlocks.BLAST_FURNACE_OUTPUT::get)
.catalyst(TFMGBlocks.FIREPROOF_BRICKS::get)
.itemIcon(TFMGBlocks.BLAST_FURNACE_OUTPUT.get())
.emptyBackground(177, 150)
.build("industrial_blasting", IndustrialBlastingCategory::new),
industrial_blasting = builder(IndustrialBlastingRecipe.class)
.addTypedRecipes(TFMGRecipeTypes.INDUSTRIAL_BLASTING)
.catalyst(TFMGBlocks.BLAST_FURNACE_OUTPUT::get)
.catalyst(TFMGBlocks.FIREPROOF_BRICKS::get)
.catalyst(TFMGBlocks.FIREPROOF_BRICK_REINFORCEMENT::get)
.catalyst(TFMGBlocks.BLAST_FURNACE_REINFORCEMENT::get)
.catalyst(TFMGBlocks.BLAST_FURNACE_REINFORCEMENT_WALL::get)
.catalyst(TFMGBlocks.BLAST_FURNACE_HATCH::get)
.itemIcon(TFMGBlocks.BLAST_FURNACE_OUTPUT.get())
.emptyBackground(177, 150)
.build("industrial_blasting", IndustrialBlastingCategory::new),
casting = builder(CastingRecipe.class)
.addTypedRecipes(TFMGRecipeTypes.CASTING)
.catalyst(TFMGBlocks.CASTING_BASIN::get)
.itemIcon(TFMGBlocks.CASTING_BASIN.get())
.emptyBackground(177, 53)
.build("casting", CastingCategory::new),
casting = builder(CastingRecipe.class)
.addTypedRecipes(TFMGRecipeTypes.CASTING)
.catalyst(TFMGBlocks.CASTING_BASIN::get)
.itemIcon(TFMGBlocks.STEEL_BLOCK.get())
.emptyBackground(177, 140)
.build("casting", CastingCategory::new),
hot_blast = builder(HotBlastRecipe.class)
.addTypedRecipes(TFMGRecipeTypes.HOT_BLAST)
.catalyst(TFMGBlocks.BLAST_STOVE::get)
.itemIcon(TFMGBlocks.BLAST_STOVE.get())
.emptyBackground(177, 110)
.build("hot_blast", HotBlastCategory::new),
polarizing = builder(PolarizingRecipe.class)
.addTypedRecipes(TFMGRecipeTypes.POLARIZING)
.catalyst(TFMGBlocks.POLARIZER::get)
.itemIcon(TFMGBlocks.POLARIZER.get())
.emptyBackground(177, 53)
.build("polarizing", PolarizingCategory::new),
polarizing = builder(PolarizingRecipe.class)
.addTypedRecipes(TFMGRecipeTypes.POLARIZING)
.catalyst(TFMGBlocks.POLARIZER::get)
.itemIcon(TFMGBlocks.POLARIZER.get())
.emptyBackground(177, 53)
.build("polarizing", PolarizingCategory::new)
;
winding = builder(WindingRecipe.class)
.addTypedRecipes(TFMGRecipeTypes.WINDING)
.catalyst(TFMGBlocks.WINDING_MACHINE::get)
.itemIcon(TFMGBlocks.WINDING_MACHINE.get())
.emptyBackground(177, 53)
.build("winding", WindingCategory::new);
}
@@ -134,7 +146,6 @@ public class TFMGJei implements IModPlugin {
}
/**
*
* check
*/
/*
@@ -147,8 +158,7 @@ public class TFMGJei implements IModPlugin {
}
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public void registerGuiHandlers(IGuiHandlerRegistration registration) {
registration.addGenericGuiContainerHandler(AbstractSimiContainerScreen.class, new SlotMover());

Some files were not shown because too many files have changed in this diff Show More