CreateMod/src/main/java/com/simibubi/create/compat/computercraft/implementation/peripherals/StationPeripheral.java
simibubi 3ad4195dd6 Squashed commit of the following:
commit a162e18c9c4d91c4020e86cf718d59d3a33b2817
Merge: 374848f97 beb61708a
Author: simibubi <31564874+simibubi@users.noreply.github.com>
Date:   Fri May 12 13:40:58 2023 +0200

    Merge branch 'mc1.18/dev' into mc1.18/computercraft

commit 374848f978
Author: simibubi <31564874+simibubi@users.noreply.github.com>
Date:   Fri May 12 13:22:29 2023 +0200

    Compilation dependency toggle

commit b2cd60b619
Merge: 8e1e4e8bd ee3a079ba
Author: simibubi <31564874+simibubi@users.noreply.github.com>
Date:   Wed May 10 14:37:32 2023 +0200

    Merge pull request #4650 from ChristianLW/mc1.18/computercraft

    Small tweaks to the wiki pages for ComputerCraft integration

commit ee3a079bac
Author: Christian L.W <bebeu@bebeu.dk>
Date:   Thu Apr 13 00:55:20 2023 +0200

    Small tweaks to the wiki pages

commit 8e1e4e8bd3
Author: caelwarner <caelawarner@gmail.com>
Date:   Mon Mar 13 18:31:56 2023 -0700

    Added computer to display source ponder tag

    - Added advanced computer to display source ponder tag
    - Added missing lang entry for computer display source

commit 952941e5fc
Author: caelwarner <caelawarner@gmail.com>
Date:   Mon Mar 13 16:31:16 2023 -0700

    Added documentation for train station peripherals and train schedules

    - Added in depth documentation for working with train stations and train schedules in Lua
    - Fixed small formatting issues in Lua-Rotation-Speed-Controller.md and Lua-Sequenced-Gearshift.md

commit 7f3ca1cfa0
Author: caelwarner <caelawarner@gmail.com>
Date:   Mon Mar 13 16:29:05 2023 -0700

    Added isTrainEnroute to station peripheral API

    - isTrainEnroute checks if a train is currently navigating to the station
    - Reworded null station exception to "station is not connected to a track"
    - Refactored StationPeripheral#inAssemblyMode to StationPeripheral#isInAssemblyMode
    - Added a check to StationPeripheral#disassemble to make sure the station isn't in assembly mode

commit fac1ebcd3f
Author: caelwarner <caelawarner@gmail.com>
Date:   Sat Mar 11 16:12:58 2023 -0800

    Added documentation for most peripherals

    - Lua documentation has been added for all peripherals except the train station (not looking forward to writing that one)
    - This documentation will be added to the GitHub wiki pages

commit 3e21996984
Author: caelwarner <caelawarner@gmail.com>
Date:   Sat Mar 11 15:54:36 2023 -0800

    Updated DisplayLinkPeripheral#write to move cursor to the end of the text

    - This change was made to be more inline with ComputerCraft's builtin display API

commit 7141c10025
Author: caelwarner <caelawarner@gmail.com>
Date:   Sat Mar 11 11:45:43 2023 -0800

    Added isTrainImminent and hasSchedule to train station API

    - Added isTrainImminent to check if a train is incoming to the station and hasSchedule to check if the currently present train has a schedule
    - Added StationPeripheral#getTrainOrThrow to consolidate repetitive null checks

commit 909484ed5b
Author: caelwarner <caelawarner@gmail.com>
Date:   Sat Mar 11 11:15:58 2023 -0800

    Added getSchedule to train station lua API

    - Added getSchedule which serializes the currently present train's schedule into a lua table
    - Refactored StationPeripheral#setSchedule to use a more generic method of serializing NBT tags to lua tables
    - Moved schedule entry special data from root tag to "Data"
    - Added StringHelper#camelCaseToSnakeCase
    - Added variety of put methods to CreateLuaTable

commit 31ad3aa671
Author: caelwarner <caelawarner@gmail.com>
Date:   Wed Mar 8 18:22:23 2023 -0800

    Extended train station peripheral API

    - Train station peripherals can now assemble and disassemble trains, check if the station is in assembly mode, set the assembly mode of the station, get and change the station name, check if a train is present at the station and get and change the currently present train name.
    - Refactored StationEditPacket. Moved most of the logic that was previously in StationEditPacket to StationTileEntity. This allows us to call this logic without having to send a packet.
    - Made Train#owner nullable. This is needed so that computers can assemble trains. All Train#owner is currently used for is to display the train status to the correct play.

commit 574cd93a89
Author: caelwarner <caelawarner@gmail.com>
Date:   Wed Nov 30 00:37:47 2022 -0800

    Serialize hasAttachedComputer in ComputerBehaviour

    - This eliminates some edge cases were peripherals don't realize they're being controlled by a computer on a world save and load

commit 94e3ed44ad
Author: caelwarner <caelawarner@gmail.com>
Date:   Wed Oct 26 16:57:12 2022 -0700

    Added ComputerScreen

    - ComputerScreen shows that tile entity currently has computers attached and therefore cannot be controlled manually

commit 9afdcaded7
Author: caelwarner <caelawarner@gmail.com>
Date:   Thu Oct 20 10:18:37 2022 -0700

    Refactored PeripheralBase to SyncedPeripheral

commit 7d47fdcd06
Author: caelwarner <caelawarner@gmail.com>
Date:   Wed Oct 19 22:45:47 2022 -0700

    Made LuaFunction's final

commit 56a1210fff
Author: caelwarner <caelawarner@gmail.com>
Date:   Wed Oct 19 22:39:38 2022 -0700

    Created ComputerBehaviour behaviour

    - ComputerBehaviour replaces ComputerControllable and SyncedComputerControllable

commit 19d283b923
Author: caelwarner <caelawarner@gmail.com>
Date:   Wed Oct 19 16:05:48 2022 -0700

    Moved all peripheral classes to computercraft.peripherals package

commit ab18034b98
Author: caelwarner <caelawarner@gmail.com>
Date:   Wed Oct 19 15:58:56 2022 -0700

    Added Train Station as peripheral

    - Train station can set a new auto-schedule for the train currently at the station
    - Added CreateLuaTable to add helper functions for working with lua tables
    - Added StringHelper util class to convert snake case to camel case

commit 1091f3227c
Author: caelwarner <caelawarner@gmail.com>
Date:   Thu Oct 6 21:11:24 2022 -0700

    Changed Display Link Peripheral API

    - Changed the Display Link Peripheral API to be more in line with the Monitor API
    - Added write, setCursorPos, getCursorPos, getSize, isColor, isColour, clearLine
    - Removed void writeLine, setLine, writeLines, setLines

commit 18bfb216b1
Author: caelwarner <caelawarner@gmail.com>
Date:   Thu Oct 6 02:50:41 2022 -0700

    Changed method of checking if a computer attached

    - After talking with SquidDev from CC: Tweaked I've changed to monitoring IPeripheral#attach and IPeripheral#detach for changes in the number of computers connected to the network, then updating the client using AttachedComputerPacket
    - This works with wired full modems, wired cabled modems and directly connected computers
    - Added SyncedPeripheralBase and SyncedComputerControllable for TE's and peripherals that want to be aware of attached computers

commit 96dc4db6dc
Author: caelwarner <caelawarner@gmail.com>
Date:   Tue Oct 4 21:11:38 2022 -0700

    Sequenced Gearshift screen "greys out" when being controlled by a computer

    - This is to stop players from trying to using both the builtin sequencing and a computer to control the Sequenced Gearshift at the same time, leading to undefined behaviour
    - The "greyed out" screen should have a message added explaining why it's greyed out.
    - Added ComputerControllable#isComputerControlled to check if a tile entity is connected to a modem

commit 9a80781401
Author: caelwarner <caelawarner@gmail.com>
Date:   Tue Oct 4 19:36:08 2022 -0700

    Added PeripheralBase

commit d404f07319
Author: caelwarner <caelawarner@gmail.com>
Date:   Mon Oct 3 20:46:16 2022 -0700

    Added invalidateCaps

    - Changed setRemoved to invalidateCaps. I don't know why I wasn't just using invalidateCaps from the beginning

commit 654476d9f3
Author: caelwarner <caelawarner@gmail.com>
Date:   Mon Oct 3 20:05:25 2022 -0700

    Added Rotation Speed Controller and Sequenced Gearshift as peripherals

    - Rotation Speed Controller can get and set targetSpeed
    - Sequenced Gearshift can rotate by a certain angle and move a certain distance

commit 1420406ab7
Author: caelwarner <caelawarner@gmail.com>
Date:   Mon Oct 3 16:38:12 2022 -0700

    Added Speedometer and Stressometer as peripherals

    - Speedometer can get current speed
    - Stressometer can get current stress level as well as network stress capacity
    - Made GaugeTileEntity abstract

commit 47b8619d07
Author: caelwarner <caelawarner@gmail.com>
Date:   Mon Oct 3 16:17:05 2022 -0700

    Refactored peripheralHandler to peripheral

    - peripheralHandler was the wrong name. It's just a peripheral.
    - Changed peripheral type from "cdl" to "Create_DisplayLink"
    - Added equals function to DisplayLinkPeripheral

commit 6591c2d46e
Author: caelwarner <caelawarner@gmail.com>
Date:   Mon Oct 3 14:29:04 2022 -0700

    ComputerCraft integration for Display Links

    - CC computers can now control display links through a variety of functions
    - Added ComputerControllable interface to define a tile entity as controllable by CC computers
    - Added CC: Tweaked soft dependency
2023-05-12 13:41:28 +02:00

270 lines
8.7 KiB
Java

package com.simibubi.create.compat.computercraft.implementation.peripherals;
import java.util.Map;
import javax.annotation.Nullable;
import org.jetbrains.annotations.NotNull;
import com.simibubi.create.compat.computercraft.implementation.CreateLuaTable;
import com.simibubi.create.content.logistics.trains.entity.Train;
import com.simibubi.create.content.logistics.trains.management.edgePoint.station.GlobalStation;
import com.simibubi.create.content.logistics.trains.management.edgePoint.station.StationTileEntity;
import com.simibubi.create.content.logistics.trains.management.edgePoint.station.TrainEditPacket;
import com.simibubi.create.content.logistics.trains.management.schedule.Schedule;
import com.simibubi.create.foundation.networking.AllPackets;
import com.simibubi.create.foundation.utility.Components;
import com.simibubi.create.foundation.utility.StringHelper;
import dan200.computercraft.api.lua.IArguments;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.lua.LuaFunction;
import net.minecraft.nbt.ByteTag;
import net.minecraft.nbt.CollectionTag;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.DoubleTag;
import net.minecraft.nbt.IntTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NumericTag;
import net.minecraft.nbt.StringTag;
import net.minecraft.nbt.Tag;
import net.minecraftforge.network.PacketDistributor;
public class StationPeripheral extends SyncedPeripheral<StationTileEntity> {
public StationPeripheral(StationTileEntity tile) {
super(tile);
}
@LuaFunction(mainThread = true)
public final void assemble() throws LuaException {
if (!tile.isAssembling())
throw new LuaException("station must be in assembly mode");
tile.assemble(null);
if (tile.getStation() == null || tile.getStation().getPresentTrain() == null)
throw new LuaException("failed to assemble train");
if (!tile.exitAssemblyMode())
throw new LuaException("failed to exit assembly mode");
}
@LuaFunction(mainThread = true)
public final void disassemble() throws LuaException {
if (tile.isAssembling())
throw new LuaException("station must not be in assembly mode");
getTrainOrThrow();
if (!tile.enterAssemblyMode(null))
throw new LuaException("could not disassemble train");
}
@LuaFunction(mainThread = true)
public final void setAssemblyMode(boolean assemblyMode) throws LuaException {
if (assemblyMode) {
if (!tile.enterAssemblyMode(null))
throw new LuaException("failed to enter assembly mode");
} else {
if (!tile.exitAssemblyMode())
throw new LuaException("failed to exit assembly mode");
}
}
@LuaFunction
public final boolean isInAssemblyMode() {
return tile.isAssembling();
}
@LuaFunction
public final String getStationName() throws LuaException {
GlobalStation station = tile.getStation();
if (station == null)
throw new LuaException("station is not connected to a track");
return station.name;
}
@LuaFunction(mainThread = true)
public final void setStationName(String name) throws LuaException {
if (!tile.updateName(name))
throw new LuaException("could not set station name");
}
@LuaFunction
public final boolean isTrainPresent() throws LuaException {
GlobalStation station = tile.getStation();
if (station == null)
throw new LuaException("station is not connected to a track");
return station.getPresentTrain() != null;
}
@LuaFunction
public final boolean isTrainImminent() throws LuaException {
GlobalStation station = tile.getStation();
if (station == null)
throw new LuaException("station is not connected to a track");
return station.getImminentTrain() != null;
}
@LuaFunction
public final boolean isTrainEnroute() throws LuaException {
GlobalStation station = tile.getStation();
if (station == null)
throw new LuaException("station is not connected to a track");
return station.getNearestTrain() != null;
}
@LuaFunction
public final String getTrainName() throws LuaException {
Train train = getTrainOrThrow();
return train.name.getString();
}
@LuaFunction(mainThread = true)
public final void setTrainName(String name) throws LuaException {
Train train = getTrainOrThrow();
train.name = Components.literal(name);
AllPackets.channel.send(PacketDistributor.ALL.noArg(), new TrainEditPacket.TrainEditReturnPacket(train.id, name, train.icon.getId()));
}
@LuaFunction
public final boolean hasSchedule() throws LuaException {
Train train = getTrainOrThrow();
return train.runtime.getSchedule() != null;
}
@LuaFunction
public final CreateLuaTable getSchedule() throws LuaException {
Train train = getTrainOrThrow();
Schedule schedule = train.runtime.getSchedule();
if (schedule == null)
throw new LuaException("train doesn't have a schedule");
return fromCompoundTag(schedule.write());
}
@LuaFunction(mainThread = true)
public final void setSchedule(IArguments arguments) throws LuaException {
Train train = getTrainOrThrow();
Schedule schedule = Schedule.fromTag(toCompoundTag(new CreateLuaTable(arguments.getTable(0))));
boolean autoSchedule = train.runtime.getSchedule() == null || train.runtime.isAutoSchedule;
train.runtime.setSchedule(schedule, autoSchedule);
}
private @NotNull Train getTrainOrThrow() throws LuaException {
GlobalStation station = tile.getStation();
if (station == null)
throw new LuaException("station is not connected to a track");
Train train = station.getPresentTrain();
if (train == null)
throw new LuaException("there is no train present");
return train;
}
private static @NotNull CreateLuaTable fromCompoundTag(CompoundTag tag) throws LuaException {
return (CreateLuaTable) fromNBTTag(null, tag);
}
private static @NotNull Object fromNBTTag(@Nullable String key, Tag tag) throws LuaException {
byte type = tag.getId();
if (type == Tag.TAG_BYTE && key != null && key.equals("Count"))
return ((NumericTag) tag).getAsByte();
else if (type == Tag.TAG_BYTE)
return ((NumericTag) tag).getAsByte() != 0;
else if (type == Tag.TAG_SHORT || type == Tag.TAG_INT || type == Tag.TAG_LONG)
return ((NumericTag) tag).getAsLong();
else if (type == Tag.TAG_FLOAT || type == Tag.TAG_DOUBLE)
return ((NumericTag) tag).getAsDouble();
else if (type == Tag.TAG_STRING)
return tag.getAsString();
else if (type == Tag.TAG_LIST || type == Tag.TAG_BYTE_ARRAY || type == Tag.TAG_INT_ARRAY || type == Tag.TAG_LONG_ARRAY) {
CreateLuaTable list = new CreateLuaTable();
CollectionTag<?> listTag = (CollectionTag<?>) tag;
for (int i = 0; i < listTag.size(); i++) {
list.put(i + 1, fromNBTTag(null, listTag.get(i)));
}
return list;
} else if (type == Tag.TAG_COMPOUND) {
CreateLuaTable table = new CreateLuaTable();
CompoundTag compoundTag = (CompoundTag) tag;
for (String compoundKey : compoundTag.getAllKeys()) {
table.put(
StringHelper.camelCaseToSnakeCase(compoundKey),
fromNBTTag(compoundKey, compoundTag.get(compoundKey))
);
}
return table;
}
throw new LuaException("unknown tag type " + tag.getType().getName());
}
private static @NotNull CompoundTag toCompoundTag(CreateLuaTable table) throws LuaException {
return (CompoundTag) toNBTTag(null, table.getMap());
}
private static @NotNull Tag toNBTTag(@Nullable String key, Object value) throws LuaException {
if (value instanceof Boolean v)
return ByteTag.valueOf(v);
else if (value instanceof Byte || (key != null && key.equals("count")))
return ByteTag.valueOf(((Number) value).byteValue());
else if (value instanceof Number v) {
// If number is numerical integer
if (v.intValue() == v.doubleValue())
return IntTag.valueOf(v.intValue());
else
return DoubleTag.valueOf(v.doubleValue());
} else if (value instanceof String v)
return StringTag.valueOf(v);
else if (value instanceof Map<?, ?> v && v.containsKey(1.0)) { // List
ListTag list = new ListTag();
for (Object o : v.values()) {
list.add(toNBTTag(null, o));
}
return list;
} else if (value instanceof Map<?, ?> v) { // Table/Map
CompoundTag compound = new CompoundTag();
for (Object objectKey : v.keySet()) {
if (!(objectKey instanceof String compoundKey))
throw new LuaException("table key is not of type string");
compound.put(
// Items serialize their resource location as "id" and not as "Id".
// This check is needed to see if the 'i' should be left lowercase or not.
// Items store "count" in the same compound tag, so we can check for its presence to see if this is a serialized item
compoundKey.equals("id") && v.containsKey("count") ? "id" : StringHelper.snakeCaseToCamelCase(compoundKey),
toNBTTag(compoundKey, v.get(compoundKey))
);
}
return compound;
}
throw new LuaException("unknown object type " + value.getClass().getName());
}
@NotNull
@Override
public String getType() {
return "Create_Station";
}
}