Skip to content

Commit

Permalink
The charge meter can measure the charge in electric carts
Browse files Browse the repository at this point in the history
  • Loading branch information
Edivad99 committed Sep 26, 2023
1 parent ad8eb29 commit 773beca
Show file tree
Hide file tree
Showing 9 changed files with 71 additions and 34 deletions.
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
// 1.20.1 2023-09-10T16:28:13.344594 Languages: en_us
3d94fe9dac885db8064e1f5978c4aaafa0026200 assets/railcraft/lang/en_us.json
// 1.20.1 2023-09-26T11:16:14.330781 Languages: en_us
6c90e792080e4adf933d2540dea658da1fa5b843 assets/railcraft/lang/en_us.json
1 change: 1 addition & 0 deletions src/generated/resources/assets/railcraft/lang/en_us.json
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,7 @@
"block.railcraft.zinc_ore": "Zinc Ore",
"block.railcraft.zinc_silver_battery": "Zinc-Silver Battery",
"block.railcraft.zinc_silver_battery_empty": "Zinc-Silver Empty Battery",
"charge_meter.railcraft.cart": "Cart -> Charge: %s FE | Draw: %s FE/t | Loss: %s FE/t",
"charge_meter.railcraft.network": "Network -> Size: %s | Charge: %s FE | Draw: %s FE/t | MaxDraw: %s FE/t | Loss: %s FE/t | Eff: %s%%",
"charge_meter.railcraft.node": "Node -> Draw: %s FE/t | Loss: %s FE/t",
"charge_meter.railcraft.producer": "Supply -> Charge: %s FE | Production: %s FE/t | MaxDraw: %s FE/t | Loss: %s FE/t | Eff: %s%%",
Expand Down
33 changes: 27 additions & 6 deletions src/main/java/mods/railcraft/Railcraft.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import mods.railcraft.api.charge.Charge;
import mods.railcraft.api.core.RailcraftConstants;
import mods.railcraft.api.fuel.FuelUtil;
import mods.railcraft.charge.ChargeCartStorageImpl;
import mods.railcraft.charge.ChargeProviderImpl;
import mods.railcraft.charge.ZapEffectProviderImpl;
import mods.railcraft.client.ClientManager;
Expand Down Expand Up @@ -42,6 +43,7 @@
import mods.railcraft.world.entity.vehicle.MinecartHandler;
import mods.railcraft.world.entity.vehicle.RollingStockImpl;
import mods.railcraft.world.inventory.RailcraftMenuTypes;
import mods.railcraft.world.item.ChargeMeterItem;
import mods.railcraft.world.item.CrowbarHandler;
import mods.railcraft.world.item.RailcraftCreativeModeTabs;
import mods.railcraft.world.item.RailcraftItems;
Expand All @@ -63,6 +65,7 @@
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.npc.VillagerProfession;
Expand All @@ -73,6 +76,7 @@
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.brewing.BrewingRecipeRegistry;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
import net.minecraftforge.data.event.GatherDataEvent;
import net.minecraftforge.event.AttachCapabilitiesEvent;
Expand Down Expand Up @@ -266,15 +270,32 @@ public void handlePlayerTick(TickEvent.PlayerTickEvent event) {
}

@SubscribeEvent
public void handleMinecartInteract(PlayerInteractEvent.EntityInteract event) {
public void handleEntityInteract(PlayerInteractEvent.EntityInteract event) {
if (event.getTarget() instanceof AbstractMinecart cart) {
var player = event.getEntity();
var hand = event.getHand();
event.setCanceled(this.minecartHandler.handleInteract(cart, player));
var crowbarActionResult = this.crowbarHandler.handleInteract(cart, player, hand);
if (crowbarActionResult.consumesAction()) {
event.setCanceled(true);
event.setCancellationResult(crowbarActionResult);
var stack = event.getItemStack();

if (!stack.isEmpty() && stack.is(RailcraftItems.CHARGE_METER.get())) {
player.swing(hand);
if (!player.level().isClientSide()) {
cart.getCapability(ForgeCapabilities.ENERGY)
.filter(ChargeCartStorageImpl.class::isInstance)
.map(ChargeCartStorageImpl.class::cast)
.ifPresent(battery -> {
ChargeMeterItem.sendChat(player, Translations.ChargeMeter.CART,
battery.getEnergyStored(), battery.getDraw(), battery.getLosses());
event.setCanceled(true);
event.setCancellationResult(InteractionResult.SUCCESS);
});
}
} else {
event.setCanceled(this.minecartHandler.handleInteract(cart, player));
var crowbarActionResult = this.crowbarHandler.handleInteract(cart, player, hand);
if (crowbarActionResult.consumesAction()) {
event.setCanceled(true);
event.setCancellationResult(crowbarActionResult);
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions src/main/java/mods/railcraft/Translations.java
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,7 @@ public static class RoutingTable {

public static class ChargeMeter {
public static final String START = makeKey("charge_meter", "start");
public static final String CART = makeKey("charge_meter", "cart");
public static final String NETWORK = makeKey("charge_meter", "network");
public static final String NODE = makeKey("charge_meter", "node");
public static final String PRODUCER = makeKey("charge_meter", "producer");
Expand Down
29 changes: 17 additions & 12 deletions src/main/java/mods/railcraft/charge/ChargeCartStorageImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,15 @@ public class ChargeCartStorageImpl extends EnergyStorage implements ChargeCartSt

protected static final Random RANDOM = new Random();
private static final int DRAW_INTERVAL = 8;
protected final float lossPerTick;
protected double draw;
protected int clock = RANDOM.nextInt();
protected int drewFromTrack;

public ChargeCartStorageImpl() {
this(5000, 0);
}
protected final int lossPerTick;
protected double draw, chargeDrawnThisTick;
protected int drewFromTrack, clock = RANDOM.nextInt(0, DRAW_INTERVAL);

public ChargeCartStorageImpl(int capacity) {
this(capacity, 0);
}

public ChargeCartStorageImpl(int capacity, float lossPerTick) {
public ChargeCartStorageImpl(int capacity, int lossPerTick) {
super(capacity);
this.lossPerTick = lossPerTick;
}
Expand Down Expand Up @@ -61,7 +56,8 @@ public void tick(AbstractMinecart owner) {
clock++;
removeLosses();

draw = (draw * 24.0) / 25.0;
this.draw = (this.draw * 24.0 + this.chargeDrawnThisTick) / 25.0;
this.chargeDrawnThisTick = 0;

if (drewFromTrack > 0) {
drewFromTrack--;
Expand All @@ -79,17 +75,26 @@ public void tick(AbstractMinecart owner) {
@Override
public void tickOnTrack(AbstractMinecart owner, BlockPos pos) {
if (!owner.level().isClientSide() && needsCharging()) {
double drawnFromTrack = Charge.distribution
int drawnFromTrack = Charge.distribution
.network((ServerLevel) owner.level())
.access(pos)
.removeCharge(capacity - energy, false);
if (drawnFromTrack > 0.0) {
if (drawnFromTrack > 0) {
drewFromTrack = DRAW_INTERVAL * 4;
}
energy += drawnFromTrack;
}
}

@Override
public int extractEnergy(int maxExtract, boolean simulate) {
int extracted = super.extractEnergy(maxExtract, simulate);
if (!simulate) {
this.chargeDrawnThisTick += extracted;
}
return extracted;
}

private boolean needsCharging() {
return this.energy < this.capacity;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1199,6 +1199,8 @@ private void routingTableTranslations() {

private void chargeMeterTranslations() {
this.add(Translations.ChargeMeter.START, "Recording data over %s seconds...");
this.add(Translations.ChargeMeter.CART, """
Cart -> Charge: %s FE | Draw: %s FE/t | Loss: %s FE/t""");
this.add(Translations.ChargeMeter.NETWORK, """
Network -> Size: %s | Charge: %s FE | Draw: %s FE/t | MaxDraw: %s FE/t | Loss: %s FE/t | \
Eff: %s%%""");
Expand Down
20 changes: 7 additions & 13 deletions src/main/java/mods/railcraft/network/NetworkChannel.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
*/
public enum NetworkChannel {

GAME {
GAME("game") {
@Override
public void registerMessages(SimpleChannel simpleChannel) {
simpleChannel
Expand Down Expand Up @@ -170,25 +170,19 @@ public void registerMessages(SimpleChannel simpleChannel) {
}
};

/**
* Network protocol version.
*/
private static final String NETWORK_VERSION = "1";
/**
* Prevents re-registering messages.
*/
private static boolean REGISTERED;
/**
* Simple channel.
*/
private final SimpleChannel simpleChannel;

NetworkChannel() {
NetworkChannel(String name) {
var networkVersion = "1";
this.simpleChannel = NetworkRegistry.ChannelBuilder
.named(Railcraft.rl("game"))
.clientAcceptedVersions(NETWORK_VERSION::equals)
.serverAcceptedVersions(NETWORK_VERSION::equals)
.networkProtocolVersion(() -> NETWORK_VERSION)
.named(Railcraft.rl(name))
.clientAcceptedVersions(networkVersion::equals)
.serverAcceptedVersions(networkVersion::equals)
.networkProtocolVersion(() -> networkVersion)
.simpleChannel();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.energy.IEnergyStorage;

public class ElectricLocomotive extends Locomotive implements WorldlyContainer {
Expand All @@ -46,14 +49,17 @@ public class ElectricLocomotive extends Locomotive implements WorldlyContainer {
new ContainerMapper(this, SLOT_TICKET, 2).ignoreItemChecks();

private ChargeCartStorageImpl cartStorage = new ChargeCartStorageImpl(MAX_CHARGE);
private final LazyOptional<IEnergyStorage> energyHandler;

public ElectricLocomotive(EntityType<?> type, Level level) {
super(type, level);
this.energyHandler = LazyOptional.of(() -> this.cartStorage);
}

public ElectricLocomotive(ItemStack itemStack, double x, double y, double z,
ServerLevel serverLevel) {
super(itemStack, RailcraftEntityTypes.ELECTRIC_LOCOMOTIVE.get(), x, y, z, serverLevel);
this.energyHandler = LazyOptional.of(() -> this.cartStorage);
}

@Override
Expand Down Expand Up @@ -185,6 +191,13 @@ public ItemStack getPickResult() {
return itemStack;
}

@Override
public <T> LazyOptional<T> getCapability(Capability<T> capability, @Nullable Direction facing) {
return ForgeCapabilities.ENERGY == capability
? this.energyHandler.cast()
: super.getCapability(capability, facing);
}

@Override
protected AbstractContainerMenu createMenu(int id, Inventory playerInventory) {
return new ElectricLocomotiveMenu(id, playerInventory, this);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public InteractionResult useOn(UseOnContext context) {
return returnValue;
}

private void sendChat(Player player, String translation, Object... args) {
public static void sendChat(Player player, String translation, Object... args) {
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof Double doubleArg)
args[i] = HumanReadableNumberFormatter.format(doubleArg);
Expand Down

0 comments on commit 773beca

Please sign in to comment.