mirror of
				https://github.com/SquidDev-CC/CC-Tweaked
				synced 2025-10-30 13:13:00 +00:00 
			
		
		
		
	remap with yarrnforge
This commit is contained in:
		
							
								
								
									
										145
									
								
								src/main/java/dan200/computercraft/ComputerCraft.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										145
									
								
								src/main/java/dan200/computercraft/ComputerCraft.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,145 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
|  | ||||
| package dan200.computercraft; | ||||
|  | ||||
| import java.util.Collections; | ||||
| import java.util.EnumSet; | ||||
| import java.util.List; | ||||
| import java.util.Objects; | ||||
| import java.util.concurrent.TimeUnit; | ||||
| import java.util.stream.Collectors; | ||||
| import java.util.stream.Stream; | ||||
|  | ||||
| import dan200.computercraft.api.turtle.event.TurtleAction; | ||||
| import dan200.computercraft.core.apis.http.options.Action; | ||||
| import dan200.computercraft.core.apis.http.options.AddressRule; | ||||
| import dan200.computercraft.core.asm.GenericSource; | ||||
| import dan200.computercraft.shared.Config; | ||||
| import dan200.computercraft.shared.Registry; | ||||
| import dan200.computercraft.shared.computer.core.ClientComputerRegistry; | ||||
| import dan200.computercraft.shared.computer.core.ServerComputerRegistry; | ||||
| import dan200.computercraft.shared.peripheral.monitor.MonitorRenderer; | ||||
| import dan200.computercraft.shared.pocket.peripherals.PocketModem; | ||||
| import dan200.computercraft.shared.pocket.peripherals.PocketSpeaker; | ||||
| import dan200.computercraft.shared.turtle.upgrades.TurtleAxe; | ||||
| import dan200.computercraft.shared.turtle.upgrades.TurtleCraftingTable; | ||||
| import dan200.computercraft.shared.turtle.upgrades.TurtleHoe; | ||||
| import dan200.computercraft.shared.turtle.upgrades.TurtleModem; | ||||
| import dan200.computercraft.shared.turtle.upgrades.TurtleShovel; | ||||
| import dan200.computercraft.shared.turtle.upgrades.TurtleSpeaker; | ||||
| import dan200.computercraft.shared.turtle.upgrades.TurtleSword; | ||||
| import dan200.computercraft.shared.turtle.upgrades.TurtleTool; | ||||
| import dan200.computercraft.shared.util.ServiceUtil; | ||||
| import org.apache.logging.log4j.LogManager; | ||||
| import org.apache.logging.log4j.Logger; | ||||
|  | ||||
| import net.fabricmc.api.ModInitializer; | ||||
|  | ||||
| public final class ComputerCraft implements ModInitializer { | ||||
|     public static final String MOD_ID = "computercraft"; | ||||
|  | ||||
|     // Configuration options | ||||
|     public static final String[] DEFAULT_HTTP_ALLOW = new String[] {"*"}; | ||||
|     public static final String[] DEFAULT_HTTP_DENY = new String[] { | ||||
|         "127.0.0.0/8", | ||||
|         "10.0.0.0/8", | ||||
|         "172.16.0.0/12", | ||||
|         "192.168.0.0/16", | ||||
|         "fd00::/8", | ||||
|         }; | ||||
|  | ||||
|     public static int computerSpaceLimit = 1000 * 1000; | ||||
|     public static int floppySpaceLimit = 125 * 1000; | ||||
|     public static int maximumFilesOpen = 128; | ||||
|     public static boolean disableLua51Features = false; | ||||
|     public static String defaultComputerSettings = ""; | ||||
|     public static boolean debugEnable = true; | ||||
|     public static boolean logComputerErrors = true; | ||||
|     public static boolean commandRequireCreative = true; | ||||
|  | ||||
|     public static int computerThreads = 1; | ||||
|     public static long maxMainGlobalTime = TimeUnit.MILLISECONDS.toNanos(10); | ||||
|     public static long maxMainComputerTime = TimeUnit.MILLISECONDS.toNanos(5); | ||||
|  | ||||
|     public static boolean httpEnabled = true; | ||||
|     public static boolean httpWebsocketEnabled = true; | ||||
|     public static List<AddressRule> httpRules = Collections.unmodifiableList(Stream.concat(Stream.of(DEFAULT_HTTP_DENY) | ||||
|                                                                                                  .map(x -> AddressRule.parse(x, Action.DENY.toPartial())) | ||||
|                                                                                                  .filter(Objects::nonNull), | ||||
|                                                                                            Stream.of(DEFAULT_HTTP_ALLOW) | ||||
|                                                                                                  .map(x -> AddressRule.parse(x, Action.ALLOW.toPartial())) | ||||
|                                                                                                  .filter(Objects::nonNull)) | ||||
|                                                                                    .collect(Collectors.toList())); | ||||
|  | ||||
|     public static int httpMaxRequests = 16; | ||||
|     public static int httpMaxWebsockets = 4; | ||||
|  | ||||
|     public static boolean enableCommandBlock = false; | ||||
|     public static int modemRange = 64; | ||||
|     public static int modemHighAltitudeRange = 384; | ||||
|     public static int modemRangeDuringStorm = 64; | ||||
|     public static int modemHighAltitudeRangeDuringStorm = 384; | ||||
|     public static int maxNotesPerTick = 8; | ||||
|     public static MonitorRenderer monitorRenderer = MonitorRenderer.BEST; | ||||
|     public static double monitorDistanceSq = 4096; | ||||
|     public static long monitorBandwidth = 1_000_000; | ||||
|  | ||||
|     public static boolean turtlesNeedFuel = true; | ||||
|     public static int turtleFuelLimit = 20000; | ||||
|     public static int advancedTurtleFuelLimit = 100000; | ||||
|     public static boolean turtlesObeyBlockProtection = true; | ||||
|     public static boolean turtlesCanPush = true; | ||||
|     public static EnumSet<TurtleAction> turtleDisabledActions = EnumSet.noneOf(TurtleAction.class); | ||||
|  | ||||
|     public static boolean genericPeripheral = false; | ||||
|  | ||||
|     public static int computerTermWidth = 51; | ||||
|     public static int computerTermHeight = 19; | ||||
|  | ||||
|     public static final int turtleTermWidth = 39; | ||||
|     public static final int turtleTermHeight = 13; | ||||
|  | ||||
|     public static int pocketTermWidth = 26; | ||||
|     public static int pocketTermHeight = 20; | ||||
|  | ||||
|     public static int monitorWidth = 8; | ||||
|     public static int monitorHeight = 6; | ||||
|  | ||||
|     public static final class TurtleUpgrades { | ||||
|         public static TurtleModem wirelessModemNormal; | ||||
|         public static TurtleModem wirelessModemAdvanced; | ||||
|         public static TurtleSpeaker speaker; | ||||
|  | ||||
|         public static TurtleCraftingTable craftingTable; | ||||
|         public static TurtleSword diamondSword; | ||||
|         public static TurtleShovel diamondShovel; | ||||
|         public static TurtleTool diamondPickaxe; | ||||
|         public static TurtleAxe diamondAxe; | ||||
|         public static TurtleHoe diamondHoe; | ||||
|     } | ||||
|  | ||||
|     public static final class PocketUpgrades { | ||||
|         public static PocketModem wirelessModemNormal; | ||||
|         public static PocketModem wirelessModemAdvanced; | ||||
|         public static PocketSpeaker speaker; | ||||
|     } | ||||
|  | ||||
|     // Registries | ||||
|     public static final ClientComputerRegistry clientComputerRegistry = new ClientComputerRegistry(); | ||||
|     public static final ServerComputerRegistry serverComputerRegistry = new ServerComputerRegistry(); | ||||
|  | ||||
|     // Logging | ||||
|     public static final Logger log = LogManager.getLogger(MOD_ID); | ||||
|  | ||||
|  | ||||
|     @Override | ||||
|     public void onInitialize() { | ||||
|         Config.setup(); | ||||
|         Registry.setup(); | ||||
|         GenericSource.setup(() -> ServiceUtil.loadServicesForge(GenericSource.class)); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										168
									
								
								src/main/java/dan200/computercraft/ComputerCraftAPIImpl.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										168
									
								
								src/main/java/dan200/computercraft/ComputerCraftAPIImpl.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,168 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft; | ||||
|  | ||||
| import dan200.computercraft.api.ComputerCraftAPI.IComputerCraftAPI; | ||||
| import dan200.computercraft.api.filesystem.IMount; | ||||
| import dan200.computercraft.api.filesystem.IWritableMount; | ||||
| import dan200.computercraft.api.lua.ILuaAPIFactory; | ||||
| import dan200.computercraft.api.media.IMediaProvider; | ||||
| import dan200.computercraft.api.network.IPacketNetwork; | ||||
| import dan200.computercraft.api.network.wired.IWiredElement; | ||||
| import dan200.computercraft.api.network.wired.IWiredNode; | ||||
| import dan200.computercraft.api.peripheral.IPeripheralProvider; | ||||
| import dan200.computercraft.api.pocket.IPocketUpgrade; | ||||
| import dan200.computercraft.api.redstone.IBundledRedstoneProvider; | ||||
| import dan200.computercraft.api.turtle.ITurtleUpgrade; | ||||
| import dan200.computercraft.core.apis.ApiFactories; | ||||
| import dan200.computercraft.core.filesystem.FileMount; | ||||
| import dan200.computercraft.core.filesystem.ResourceMount; | ||||
| import dan200.computercraft.shared.*; | ||||
| import dan200.computercraft.shared.peripheral.modem.wireless.WirelessNetwork; | ||||
| import dan200.computercraft.shared.util.IDAssigner; | ||||
| import dan200.computercraft.shared.wired.WiredNode; | ||||
| import net.minecraft.block.entity.BlockEntity; | ||||
| import net.minecraft.resource.ReloadableResourceManager; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraft.util.math.BlockPos; | ||||
| import net.minecraft.util.math.Direction; | ||||
| import net.minecraft.world.BlockView; | ||||
| import net.minecraft.world.World; | ||||
| import net.minecraftforge.common.util.LazyOptional; | ||||
| import net.minecraftforge.fml.ModList; | ||||
| import net.minecraftforge.fml.server.ServerLifecycleHooks; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.io.File; | ||||
| import java.io.IOException; | ||||
| import java.io.InputStream; | ||||
|  | ||||
| import static dan200.computercraft.shared.Capabilities.CAPABILITY_WIRED_ELEMENT; | ||||
|  | ||||
| public final class ComputerCraftAPIImpl implements IComputerCraftAPI | ||||
| { | ||||
|     public static final ComputerCraftAPIImpl INSTANCE = new ComputerCraftAPIImpl(); | ||||
|  | ||||
|     private String version; | ||||
|  | ||||
|     private ComputerCraftAPIImpl() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     public static InputStream getResourceFile( String domain, String subPath ) | ||||
|     { | ||||
|         ReloadableResourceManager manager = (ReloadableResourceManager) ServerLifecycleHooks.getCurrentServer().getDataPackRegistries().getResourceManager(); | ||||
|         try | ||||
|         { | ||||
|             return manager.getResource( new Identifier( domain, subPath ) ).getInputStream(); | ||||
|         } | ||||
|         catch( IOException ignored ) | ||||
|         { | ||||
|             return null; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public String getInstalledVersion() | ||||
|     { | ||||
|         if( version != null ) return version; | ||||
|         return version = ModList.get().getModContainerById( ComputerCraft.MOD_ID ) | ||||
|             .map( x -> x.getModInfo().getVersion().toString() ) | ||||
|             .orElse( "unknown" ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public int createUniqueNumberedSaveDir( @Nonnull World world, @Nonnull String parentSubPath ) | ||||
|     { | ||||
|         return IDAssigner.getNextId( parentSubPath ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public IWritableMount createSaveDirMount( @Nonnull World world, @Nonnull String subPath, long capacity ) | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             return new FileMount( new File( IDAssigner.getDir(), subPath ), capacity ); | ||||
|         } | ||||
|         catch( Exception e ) | ||||
|         { | ||||
|             return null; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public IMount createResourceMount( @Nonnull String domain, @Nonnull String subPath ) | ||||
|     { | ||||
|         ReloadableResourceManager manager = (ReloadableResourceManager) ServerLifecycleHooks.getCurrentServer().getDataPackRegistries().getResourceManager(); | ||||
|         ResourceMount mount = ResourceMount.get( domain, subPath, manager ); | ||||
|         return mount.exists( "" ) ? mount : null; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void registerPeripheralProvider( @Nonnull IPeripheralProvider provider ) | ||||
|     { | ||||
|         Peripherals.register( provider ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void registerTurtleUpgrade( @Nonnull ITurtleUpgrade upgrade ) | ||||
|     { | ||||
|         TurtleUpgrades.register( upgrade ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider ) | ||||
|     { | ||||
|         BundledRedstone.register( provider ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ) | ||||
|     { | ||||
|         return BundledRedstone.getDefaultOutput( world, pos, side ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void registerMediaProvider( @Nonnull IMediaProvider provider ) | ||||
|     { | ||||
|         MediaProviders.register( provider ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void registerPocketUpgrade( @Nonnull IPocketUpgrade upgrade ) | ||||
|     { | ||||
|         PocketUpgrades.register( upgrade ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public IPacketNetwork getWirelessNetwork() | ||||
|     { | ||||
|         return WirelessNetwork.getUniversal(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void registerAPIFactory( @Nonnull ILuaAPIFactory factory ) | ||||
|     { | ||||
|         ApiFactories.register( factory ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public IWiredNode createWiredNodeForElement( @Nonnull IWiredElement element ) | ||||
|     { | ||||
|         return new WiredNode( element ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public LazyOptional<IWiredElement> getWiredElementAt( @Nonnull BlockView world, @Nonnull BlockPos pos, @Nonnull Direction side ) | ||||
|     { | ||||
|         BlockEntity tile = world.getBlockEntity( pos ); | ||||
|         return tile == null ? LazyOptional.empty() : tile.getCapability( CAPABILITY_WIRED_ELEMENT, side ); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										280
									
								
								src/main/java/dan200/computercraft/api/ComputerCraftAPI.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										280
									
								
								src/main/java/dan200/computercraft/api/ComputerCraftAPI.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,280 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api; | ||||
|  | ||||
| import dan200.computercraft.api.filesystem.IMount; | ||||
| import dan200.computercraft.api.filesystem.IWritableMount; | ||||
| import dan200.computercraft.api.lua.ILuaAPIFactory; | ||||
| import dan200.computercraft.api.media.IMedia; | ||||
| import dan200.computercraft.api.media.IMediaProvider; | ||||
| import dan200.computercraft.api.network.IPacketNetwork; | ||||
| import dan200.computercraft.api.network.wired.IWiredElement; | ||||
| import dan200.computercraft.api.network.wired.IWiredNode; | ||||
| import dan200.computercraft.api.peripheral.IComputerAccess; | ||||
| import dan200.computercraft.api.peripheral.IPeripheral; | ||||
| import dan200.computercraft.api.peripheral.IPeripheralProvider; | ||||
| import dan200.computercraft.api.pocket.IPocketUpgrade; | ||||
| import dan200.computercraft.api.redstone.IBundledRedstoneProvider; | ||||
| import dan200.computercraft.api.turtle.ITurtleUpgrade; | ||||
| import net.minecraft.util.math.BlockPos; | ||||
| import net.minecraft.util.math.Direction; | ||||
| import net.minecraft.world.BlockView; | ||||
| import net.minecraft.world.World; | ||||
| import net.minecraftforge.common.util.LazyOptional; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * The static entry point to the ComputerCraft API. | ||||
|  * | ||||
|  * Members in this class must be called after mod_ComputerCraft has been initialised, but may be called before it is | ||||
|  * fully loaded. | ||||
|  */ | ||||
| public final class ComputerCraftAPI | ||||
| { | ||||
|     @Nonnull | ||||
|     public static String getInstalledVersion() | ||||
|     { | ||||
|         return getInstance().getInstalledVersion(); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Deprecated | ||||
|     public static String getAPIVersion() | ||||
|     { | ||||
|         return getInstalledVersion(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Creates a numbered directory in a subfolder of the save directory for a given world, and returns that number. | ||||
|      * | ||||
|      * Use in conjunction with createSaveDirMount() to create a unique place for your peripherals or media items to store files. | ||||
|      * | ||||
|      * @param world         The world for which the save dir should be created. This should be the server side world object. | ||||
|      * @param parentSubPath The folder path within the save directory where the new directory should be created. eg: "computercraft/disk" | ||||
|      * @return The numerical value of the name of the new folder, or -1 if the folder could not be created for some reason. | ||||
|      * | ||||
|      * eg: if createUniqueNumberedSaveDir( world, "computer/disk" ) was called returns 42, then "computer/disk/42" is now | ||||
|      * available for writing. | ||||
|      * @see #createSaveDirMount(World, String, long) | ||||
|      */ | ||||
|     public static int createUniqueNumberedSaveDir( @Nonnull World world, @Nonnull String parentSubPath ) | ||||
|     { | ||||
|         return getInstance().createUniqueNumberedSaveDir( world, parentSubPath ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Creates a file system mount that maps to a subfolder of the save directory for a given world, and returns it. | ||||
|      * | ||||
|      * Use in conjunction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a folder from the | ||||
|      * users save directory onto a computers file system. | ||||
|      * | ||||
|      * @param world    The world for which the save dir can be found. This should be the server side world object. | ||||
|      * @param subPath  The folder path within the save directory that the mount should map to. eg: "computer/disk/42". | ||||
|      *                 Use createUniqueNumberedSaveDir() to create a new numbered folder to use. | ||||
|      * @param capacity The amount of data that can be stored in the directory before it fills up, in bytes. | ||||
|      * @return The mount, or null if it could be created for some reason. Use IComputerAccess.mount() or IComputerAccess.mountWritable() | ||||
|      * to mount this on a Computers' file system. | ||||
|      * @see #createUniqueNumberedSaveDir(World, String) | ||||
|      * @see IComputerAccess#mount(String, IMount) | ||||
|      * @see IComputerAccess#mountWritable(String, IWritableMount) | ||||
|      * @see IMount | ||||
|      * @see IWritableMount | ||||
|      */ | ||||
|     @Nullable | ||||
|     public static IWritableMount createSaveDirMount( @Nonnull World world, @Nonnull String subPath, long capacity ) | ||||
|     { | ||||
|         return getInstance().createSaveDirMount( world, subPath, capacity ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Creates a file system mount to a resource folder, and returns it. | ||||
|      * | ||||
|      * Use in conjunction with {@link IComputerAccess#mount} or {@link IComputerAccess#mountWritable} to mount a | ||||
|      * resource folder onto a computer's file system. | ||||
|      * | ||||
|      * The files in this mount will be a combination of files in all mod jar, and data packs that contain | ||||
|      * resources with the same domain and path. | ||||
|      * | ||||
|      * @param domain  The domain under which to look for resources. eg: "mymod". | ||||
|      * @param subPath The subPath under which to look for resources. eg: "lua/myfiles". | ||||
|      * @return The mount, or {@code null} if it could be created for some reason. | ||||
|      * @see IComputerAccess#mount(String, IMount) | ||||
|      * @see IComputerAccess#mountWritable(String, IWritableMount) | ||||
|      * @see IMount | ||||
|      */ | ||||
|     @Nullable | ||||
|     public static IMount createResourceMount( @Nonnull String domain, @Nonnull String subPath ) | ||||
|     { | ||||
|         return getInstance().createResourceMount( domain, subPath ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Registers a peripheral provider to convert blocks into {@link IPeripheral} implementations. | ||||
|      * | ||||
|      * @param provider The peripheral provider to register. | ||||
|      * @see IPeripheral | ||||
|      * @see IPeripheralProvider | ||||
|      */ | ||||
|     public static void registerPeripheralProvider( @Nonnull IPeripheralProvider provider ) | ||||
|     { | ||||
|         getInstance().registerPeripheralProvider( provider ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Registers a new turtle turtle for use in ComputerCraft. After calling this, | ||||
|      * users should be able to craft Turtles with your new turtle. It is recommended to call | ||||
|      * this during the load() method of your mod. | ||||
|      * | ||||
|      * @param upgrade The turtle upgrade to register. | ||||
|      * @see ITurtleUpgrade | ||||
|      */ | ||||
|     public static void registerTurtleUpgrade( @Nonnull ITurtleUpgrade upgrade ) | ||||
|     { | ||||
|         getInstance().registerTurtleUpgrade( upgrade ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Registers a bundled redstone provider to provide bundled redstone output for blocks. | ||||
|      * | ||||
|      * @param provider The bundled redstone provider to register. | ||||
|      * @see IBundledRedstoneProvider | ||||
|      */ | ||||
|     public static void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider ) | ||||
|     { | ||||
|         getInstance().registerBundledRedstoneProvider( provider ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * If there is a Computer or Turtle at a certain position in the world, get it's bundled redstone output. | ||||
|      * | ||||
|      * @param world The world this block is in. | ||||
|      * @param pos   The position this block is at. | ||||
|      * @param side  The side to extract the bundled redstone output from. | ||||
|      * @return If there is a block capable of emitting bundled redstone at the location, it's signal (0-65535) will be returned. | ||||
|      * If there is no block capable of emitting bundled redstone at the location, -1 will be returned. | ||||
|      * @see IBundledRedstoneProvider | ||||
|      */ | ||||
|     public static int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ) | ||||
|     { | ||||
|         return getInstance().getBundledRedstoneOutput( world, pos, side ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Registers a media provider to provide {@link IMedia} implementations for Items. | ||||
|      * | ||||
|      * @param provider The media provider to register. | ||||
|      * @see IMediaProvider | ||||
|      */ | ||||
|     public static void registerMediaProvider( @Nonnull IMediaProvider provider ) | ||||
|     { | ||||
|         getInstance().registerMediaProvider( provider ); | ||||
|     } | ||||
|  | ||||
|     public static void registerPocketUpgrade( @Nonnull IPocketUpgrade upgrade ) | ||||
|     { | ||||
|         getInstance().registerPocketUpgrade( upgrade ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Attempt to get the game-wide wireless network. | ||||
|      * | ||||
|      * @return The global wireless network, or {@code null} if it could not be fetched. | ||||
|      */ | ||||
|     public static IPacketNetwork getWirelessNetwork() | ||||
|     { | ||||
|         return getInstance().getWirelessNetwork(); | ||||
|     } | ||||
|  | ||||
|     public static void registerAPIFactory( @Nonnull ILuaAPIFactory factory ) | ||||
|     { | ||||
|         getInstance().registerAPIFactory( factory ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Construct a new wired node for a given wired element. | ||||
|      * | ||||
|      * @param element The element to construct it for | ||||
|      * @return The element's node | ||||
|      * @see IWiredElement#getNode() | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static IWiredNode createWiredNodeForElement( @Nonnull IWiredElement element ) | ||||
|     { | ||||
|         return getInstance().createWiredNodeForElement( element ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the wired network element for a block in world. | ||||
|      * | ||||
|      * @param world The world the block exists in | ||||
|      * @param pos   The position the block exists in | ||||
|      * @param side  The side to extract the network element from | ||||
|      * @return The element's node | ||||
|      * @see IWiredElement#getNode() | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static LazyOptional<IWiredElement> getWiredElementAt( @Nonnull BlockView world, @Nonnull BlockPos pos, @Nonnull Direction side ) | ||||
|     { | ||||
|         return getInstance().getWiredElementAt( world, pos, side ); | ||||
|     } | ||||
|  | ||||
|     private static IComputerCraftAPI instance; | ||||
|  | ||||
|     @Nonnull | ||||
|     private static IComputerCraftAPI getInstance() | ||||
|     { | ||||
|         if( instance != null ) return instance; | ||||
|  | ||||
|         try | ||||
|         { | ||||
|             return instance = (IComputerCraftAPI) Class.forName( "dan200.computercraft.ComputerCraftAPIImpl" ) | ||||
|                 .getField( "INSTANCE" ).get( null ); | ||||
|         } | ||||
|         catch( ReflectiveOperationException e ) | ||||
|         { | ||||
|             throw new IllegalStateException( "Cannot find ComputerCraft API", e ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public interface IComputerCraftAPI | ||||
|     { | ||||
|         @Nonnull | ||||
|         String getInstalledVersion(); | ||||
|  | ||||
|         int createUniqueNumberedSaveDir( @Nonnull World world, @Nonnull String parentSubPath ); | ||||
|  | ||||
|         @Nullable | ||||
|         IWritableMount createSaveDirMount( @Nonnull World world, @Nonnull String subPath, long capacity ); | ||||
|  | ||||
|         @Nullable | ||||
|         IMount createResourceMount( @Nonnull String domain, @Nonnull String subPath ); | ||||
|  | ||||
|         void registerPeripheralProvider( @Nonnull IPeripheralProvider provider ); | ||||
|  | ||||
|         void registerTurtleUpgrade( @Nonnull ITurtleUpgrade upgrade ); | ||||
|  | ||||
|         void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider ); | ||||
|  | ||||
|         int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ); | ||||
|  | ||||
|         void registerMediaProvider( @Nonnull IMediaProvider provider ); | ||||
|  | ||||
|         void registerPocketUpgrade( @Nonnull IPocketUpgrade upgrade ); | ||||
|  | ||||
|         @Nonnull | ||||
|         IPacketNetwork getWirelessNetwork(); | ||||
|  | ||||
|         void registerAPIFactory( @Nonnull ILuaAPIFactory factory ); | ||||
|  | ||||
|         @Nonnull | ||||
|         IWiredNode createWiredNodeForElement( @Nonnull IWiredElement element ); | ||||
|  | ||||
|         @Nonnull | ||||
|         LazyOptional<IWiredElement> getWiredElementAt( @Nonnull BlockView world, @Nonnull BlockPos pos, @Nonnull Direction side ); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,60 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.client; | ||||
|  | ||||
| import net.minecraft.client.MinecraftClient; | ||||
| import net.minecraft.client.render.model.BakedModel; | ||||
| import net.minecraft.client.render.model.BakedModelManager; | ||||
| import net.minecraft.client.util.ModelIdentifier; | ||||
| import net.minecraft.client.util.math.AffineTransformation; | ||||
| import net.minecraft.item.ItemStack; | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * A model to render, combined with a transformation matrix to apply. | ||||
|  */ | ||||
| public final class TransformedModel | ||||
| { | ||||
|     private final BakedModel model; | ||||
|     private final AffineTransformation matrix; | ||||
|  | ||||
|     public TransformedModel( @Nonnull BakedModel model, @Nonnull AffineTransformation matrix ) | ||||
|     { | ||||
|         this.model = Objects.requireNonNull( model ); | ||||
|         this.matrix = Objects.requireNonNull( matrix ); | ||||
|     } | ||||
|  | ||||
|     public TransformedModel( @Nonnull BakedModel model ) | ||||
|     { | ||||
|         this.model = Objects.requireNonNull( model ); | ||||
|         this.matrix = AffineTransformation.identity(); | ||||
|     } | ||||
|  | ||||
|     public static TransformedModel of( @Nonnull ModelIdentifier location ) | ||||
|     { | ||||
|         BakedModelManager modelManager = MinecraftClient.getInstance().getBakedModelManager(); | ||||
|         return new TransformedModel( modelManager.getModel( location ) ); | ||||
|     } | ||||
|  | ||||
|     public static TransformedModel of( @Nonnull ItemStack item, @Nonnull AffineTransformation transform ) | ||||
|     { | ||||
|         BakedModel model = MinecraftClient.getInstance().getItemRenderer().getModels().getModel( item ); | ||||
|         return new TransformedModel( model, transform ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     public BakedModel getModel() | ||||
|     { | ||||
|         return model; | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     public AffineTransformation getMatrix() | ||||
|     { | ||||
|         return matrix; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,81 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.filesystem; | ||||
|  | ||||
| import java.nio.file.attribute.BasicFileAttributes; | ||||
| import java.nio.file.attribute.FileTime; | ||||
| import java.time.Instant; | ||||
|  | ||||
| /** | ||||
|  * A simple version of {@link BasicFileAttributes}, which provides what information a {@link IMount} already exposes. | ||||
|  */ | ||||
| final class FileAttributes implements BasicFileAttributes | ||||
| { | ||||
|     private static final FileTime EPOCH = FileTime.from( Instant.EPOCH ); | ||||
|  | ||||
|     private final boolean isDirectory; | ||||
|     private final long size; | ||||
|  | ||||
|     FileAttributes( boolean isDirectory, long size ) | ||||
|     { | ||||
|         this.isDirectory = isDirectory; | ||||
|         this.size = size; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public FileTime lastModifiedTime() | ||||
|     { | ||||
|         return EPOCH; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public FileTime lastAccessTime() | ||||
|     { | ||||
|         return EPOCH; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public FileTime creationTime() | ||||
|     { | ||||
|         return EPOCH; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean isRegularFile() | ||||
|     { | ||||
|         return !isDirectory; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean isDirectory() | ||||
|     { | ||||
|         return isDirectory; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean isSymbolicLink() | ||||
|     { | ||||
|         return false; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean isOther() | ||||
|     { | ||||
|         return false; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public long size() | ||||
|     { | ||||
|         return size; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public Object fileKey() | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,41 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.filesystem; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.io.IOException; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * An {@link IOException} which occurred on a specific file. | ||||
|  * | ||||
|  * This may be thrown from a {@link IMount} or {@link IWritableMount} to give more information about a failure. | ||||
|  */ | ||||
| public class FileOperationException extends IOException | ||||
| { | ||||
|     private static final long serialVersionUID = -8809108200853029849L; | ||||
|  | ||||
|     private final String filename; | ||||
|  | ||||
|     public FileOperationException( @Nullable String filename, @Nonnull String message ) | ||||
|     { | ||||
|         super( Objects.requireNonNull( message, "message cannot be null" ) ); | ||||
|         this.filename = filename; | ||||
|     } | ||||
|  | ||||
|     public FileOperationException( @Nonnull String message ) | ||||
|     { | ||||
|         super( Objects.requireNonNull( message, "message cannot be null" ) ); | ||||
|         this.filename = null; | ||||
|     } | ||||
|  | ||||
|     @Nullable | ||||
|     public String getFilename() | ||||
|     { | ||||
|         return filename; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,43 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.filesystem; | ||||
|  | ||||
| import java.io.IOException; | ||||
|  | ||||
| /** | ||||
|  * Provides a mount of the entire computer's file system. | ||||
|  * | ||||
|  * This exists for use by various APIs - one should not attempt to mount it. | ||||
|  */ | ||||
| public interface IFileSystem extends IWritableMount | ||||
| { | ||||
|     /** | ||||
|      * Combine two paths together, reducing them into a normalised form. | ||||
|      * | ||||
|      * @param path  The main path. | ||||
|      * @param child The path to append. | ||||
|      * @return The combined, normalised path. | ||||
|      */ | ||||
|     String combine( String path, String child ); | ||||
|  | ||||
|     /** | ||||
|      * Copy files from one location to another. | ||||
|      * | ||||
|      * @param from The location to copy from. | ||||
|      * @param to   The location to copy to. This should not exist. | ||||
|      * @throws IOException If the copy failed. | ||||
|      */ | ||||
|     void copy( String from, String to ) throws IOException; | ||||
|  | ||||
|     /** | ||||
|      * Move files from one location to another. | ||||
|      * | ||||
|      * @param from The location to move from. | ||||
|      * @param to   The location to move to. This should not exist. | ||||
|      * @throws IOException If the move failed. | ||||
|      */ | ||||
|     void move( String from, String to ) throws IOException; | ||||
| } | ||||
| @@ -0,0 +1,94 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.filesystem; | ||||
|  | ||||
| import dan200.computercraft.api.ComputerCraftAPI; | ||||
| import dan200.computercraft.api.peripheral.IComputerAccess; | ||||
| import net.minecraft.world.World; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.io.IOException; | ||||
| import java.nio.channels.ReadableByteChannel; | ||||
| import java.nio.file.attribute.BasicFileAttributes; | ||||
| import java.util.List; | ||||
|  | ||||
| /** | ||||
|  * Represents a read only part of a virtual filesystem that can be mounted onto a computer using | ||||
|  * {@link IComputerAccess#mount(String, IMount)}. | ||||
|  * | ||||
|  * Ready made implementations of this interface can be created using | ||||
|  * {@link ComputerCraftAPI#createSaveDirMount(World, String, long)} or | ||||
|  * {@link ComputerCraftAPI#createResourceMount(String, String)}, or you're free to implement it yourselves! | ||||
|  * | ||||
|  * @see ComputerCraftAPI#createSaveDirMount(World, String, long) | ||||
|  * @see ComputerCraftAPI#createResourceMount(String, String) | ||||
|  * @see IComputerAccess#mount(String, IMount) | ||||
|  * @see IWritableMount | ||||
|  */ | ||||
| public interface IMount | ||||
| { | ||||
|     /** | ||||
|      * Returns whether a file with a given path exists or not. | ||||
|      * | ||||
|      * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" | ||||
|      * @return If the file exists. | ||||
|      * @throws IOException If an error occurs when checking the existence of the file. | ||||
|      */ | ||||
|     boolean exists( @Nonnull String path ) throws IOException; | ||||
|  | ||||
|     /** | ||||
|      * Returns whether a file with a given path is a directory or not. | ||||
|      * | ||||
|      * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms". | ||||
|      * @return If the file exists and is a directory | ||||
|      * @throws IOException If an error occurs when checking whether the file is a directory. | ||||
|      */ | ||||
|     boolean isDirectory( @Nonnull String path ) throws IOException; | ||||
|  | ||||
|     /** | ||||
|      * Returns the file names of all the files in a directory. | ||||
|      * | ||||
|      * @param path     A file path in normalised format, relative to the mount location. ie: "programs/myprograms". | ||||
|      * @param contents A list of strings. Add all the file names to this list. | ||||
|      * @throws IOException If the file was not a directory, or could not be listed. | ||||
|      */ | ||||
|     void list( @Nonnull String path, @Nonnull List<String> contents ) throws IOException; | ||||
|  | ||||
|     /** | ||||
|      * Returns the size of a file with a given path, in bytes. | ||||
|      * | ||||
|      * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram". | ||||
|      * @return The size of the file, in bytes. | ||||
|      * @throws IOException If the file does not exist, or its size could not be determined. | ||||
|      */ | ||||
|     long getSize( @Nonnull String path ) throws IOException; | ||||
|  | ||||
|     /** | ||||
|      * Opens a file with a given path, and returns an {@link ReadableByteChannel} representing its contents. | ||||
|      * | ||||
|      * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram". | ||||
|      * @return A channel representing the contents of the file. If the channel implements | ||||
|      * {@link java.nio.channels.SeekableByteChannel}, one will be able to seek to arbitrary positions when using binary | ||||
|      * mode. | ||||
|      * @throws IOException If the file does not exist, or could not be opened. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     ReadableByteChannel openForRead( @Nonnull String path ) throws IOException; | ||||
|  | ||||
|     /** | ||||
|      * Get attributes about the given file. | ||||
|      * | ||||
|      * @param path The path to query. | ||||
|      * @return File attributes for the given file. | ||||
|      * @throws IOException If the file does not exist, or attributes could not be fetched. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     default BasicFileAttributes getAttributes( @Nonnull String path ) throws IOException | ||||
|     { | ||||
|         if( !exists( path ) ) throw new FileOperationException( path, "No such file" ); | ||||
|         return new FileAttributes( isDirectory( path ), getSize( path ) ); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,90 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.filesystem; | ||||
|  | ||||
| import dan200.computercraft.api.ComputerCraftAPI; | ||||
| import dan200.computercraft.api.peripheral.IComputerAccess; | ||||
| import net.minecraft.world.World; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.io.IOException; | ||||
| import java.io.OutputStream; | ||||
| import java.nio.channels.WritableByteChannel; | ||||
| import java.util.OptionalLong; | ||||
|  | ||||
| /** | ||||
|  * Represents a part of a virtual filesystem that can be mounted onto a computer using {@link IComputerAccess#mount(String, IMount)} | ||||
|  * or {@link IComputerAccess#mountWritable(String, IWritableMount)}, that can also be written to. | ||||
|  * | ||||
|  * Ready made implementations of this interface can be created using | ||||
|  * {@link ComputerCraftAPI#createSaveDirMount(World, String, long)}, or you're free to implement it yourselves! | ||||
|  * | ||||
|  * @see ComputerCraftAPI#createSaveDirMount(World, String, long) | ||||
|  * @see IComputerAccess#mount(String, IMount) | ||||
|  * @see IComputerAccess#mountWritable(String, IWritableMount) | ||||
|  * @see IMount | ||||
|  */ | ||||
| public interface IWritableMount extends IMount | ||||
| { | ||||
|     /** | ||||
|      * Creates a directory at a given path inside the virtual file system. | ||||
|      * | ||||
|      * @param path A file path in normalised format, relative to the mount location. ie: "programs/mynewprograms". | ||||
|      * @throws IOException If the directory already exists or could not be created. | ||||
|      */ | ||||
|     void makeDirectory( @Nonnull String path ) throws IOException; | ||||
|  | ||||
|     /** | ||||
|      * Deletes a directory at a given path inside the virtual file system. | ||||
|      * | ||||
|      * @param path A file path in normalised format, relative to the mount location. ie: "programs/myoldprograms". | ||||
|      * @throws IOException If the file does not exist or could not be deleted. | ||||
|      */ | ||||
|     void delete( @Nonnull String path ) throws IOException; | ||||
|  | ||||
|     /** | ||||
|      * Opens a file with a given path, and returns an {@link OutputStream} for writing to it. | ||||
|      * | ||||
|      * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram". | ||||
|      * @return A stream for writing to. If the channel implements {@link java.nio.channels.SeekableByteChannel}, one | ||||
|      * will be able to seek to arbitrary positions when using binary mode. | ||||
|      * @throws IOException If the file could not be opened for writing. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     WritableByteChannel openForWrite( @Nonnull String path ) throws IOException; | ||||
|  | ||||
|     /** | ||||
|      * Opens a file with a given path, and returns an {@link OutputStream} for appending to it. | ||||
|      * | ||||
|      * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram". | ||||
|      * @return A stream for writing to. If the channel implements {@link java.nio.channels.SeekableByteChannel}, one | ||||
|      * will be able to seek to arbitrary positions when using binary mode. | ||||
|      * @throws IOException If the file could not be opened for writing. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     WritableByteChannel openForAppend( @Nonnull String path ) throws IOException; | ||||
|  | ||||
|     /** | ||||
|      * Get the amount of free space on the mount, in bytes. You should decrease this value as the user writes to the | ||||
|      * mount, and write operations should fail once it reaches zero. | ||||
|      * | ||||
|      * @return The amount of free space, in bytes. | ||||
|      * @throws IOException If the remaining space could not be computed. | ||||
|      */ | ||||
|     long getRemainingSpace() throws IOException; | ||||
|  | ||||
|     /** | ||||
|      * Get the capacity of this mount. This should be equal to the size of all files/directories on this mount, minus | ||||
|      * the {@link #getRemainingSpace()}. | ||||
|      * | ||||
|      * @return The capacity of this mount, in bytes. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     default OptionalLong getCapacity() | ||||
|     { | ||||
|         return OptionalLong.empty(); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										407
									
								
								src/main/java/dan200/computercraft/api/lua/IArguments.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										407
									
								
								src/main/java/dan200/computercraft/api/lua/IArguments.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,407 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.nio.ByteBuffer; | ||||
| import java.util.Map; | ||||
| import java.util.Optional; | ||||
|  | ||||
| import static dan200.computercraft.api.lua.LuaValues.checkFinite; | ||||
|  | ||||
| /** | ||||
|  * The arguments passed to a function. | ||||
|  */ | ||||
| public interface IArguments | ||||
| { | ||||
|     /** | ||||
|      * Get the number of arguments passed to this function. | ||||
|      * | ||||
|      * @return The number of passed arguments. | ||||
|      */ | ||||
|     int count(); | ||||
|  | ||||
|     /** | ||||
|      * Get the argument at the specific index. The returned value must obey the following conversion rules: | ||||
|      * | ||||
|      * <ul> | ||||
|      *   <li>Lua values of type "string" will be represented by a {@link String}.</li> | ||||
|      *   <li>Lua values of type "number" will be represented by a {@link Number}.</li> | ||||
|      *   <li>Lua values of type "boolean" will be represented by a {@link Boolean}.</li> | ||||
|      *   <li>Lua values of type "table" will be represented by a {@link Map}.</li> | ||||
|      *   <li>Lua values of any other type will be represented by a {@code null} value.</li> | ||||
|      * </ul> | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value, or {@code null} if not present. | ||||
|      */ | ||||
|     @Nullable | ||||
|     Object get( int index ); | ||||
|  | ||||
|     /** | ||||
|      * Drop a number of arguments. The returned arguments instance will access arguments at position {@code i + count}, | ||||
|      * rather than {@code i}. However, errors will still use the given argument index. | ||||
|      * | ||||
|      * @param count The number of arguments to drop. | ||||
|      * @return The new {@link IArguments} instance. | ||||
|      */ | ||||
|     IArguments drop( int count ); | ||||
|  | ||||
|     default Object[] getAll() | ||||
|     { | ||||
|         Object[] result = new Object[count()]; | ||||
|         for( int i = 0; i < result.length; i++ ) result[i] = get( i ); | ||||
|         return result; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a double. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value. | ||||
|      * @throws LuaException If the value is not a number. | ||||
|      * @see #getFiniteDouble(int) if you require this to be finite (i.e. not infinite or NaN). | ||||
|      */ | ||||
|     default double getDouble( int index ) throws LuaException | ||||
|     { | ||||
|         Object value = get( index ); | ||||
|         if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); | ||||
|         return ((Number) value).doubleValue(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as an integer. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value. | ||||
|      * @throws LuaException If the value is not an integer. | ||||
|      */ | ||||
|     default int getInt( int index ) throws LuaException | ||||
|     { | ||||
|         return (int) getLong( index ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a long. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value. | ||||
|      * @throws LuaException If the value is not a long. | ||||
|      */ | ||||
|     default long getLong( int index ) throws LuaException | ||||
|     { | ||||
|         Object value = get( index ); | ||||
|         if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); | ||||
|         return LuaValues.checkFiniteNum( index, (Number) value ).longValue(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a finite number (not infinite or NaN). | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value. | ||||
|      * @throws LuaException If the value is not finite. | ||||
|      */ | ||||
|     default double getFiniteDouble( int index ) throws LuaException | ||||
|     { | ||||
|         return checkFinite( index, getDouble( index ) ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a boolean. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value. | ||||
|      * @throws LuaException If the value is not a boolean. | ||||
|      */ | ||||
|     default boolean getBoolean( int index ) throws LuaException | ||||
|     { | ||||
|         Object value = get( index ); | ||||
|         if( !(value instanceof Boolean) ) throw LuaValues.badArgumentOf( index, "boolean", value ); | ||||
|         return (Boolean) value; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a string. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value. | ||||
|      * @throws LuaException If the value is not a string. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     default String getString( int index ) throws LuaException | ||||
|     { | ||||
|         Object value = get( index ); | ||||
|         if( !(value instanceof String) ) throw LuaValues.badArgumentOf( index, "string", value ); | ||||
|         return (String) value; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get a string argument as a byte array. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value. This is a <em>read only</em> buffer. | ||||
|      * @throws LuaException If the value is not a string. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     default ByteBuffer getBytes( int index ) throws LuaException | ||||
|     { | ||||
|         return LuaValues.encode( getString( index ) ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get a string argument as an enum value. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @param klass The type of enum to parse. | ||||
|      * @param <T>   The type of enum to parse. | ||||
|      * @return The argument's value. | ||||
|      * @throws LuaException If the value is not a string or not a valid option for this enum. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     default <T extends Enum<T>> T getEnum( int index, Class<T> klass ) throws LuaException | ||||
|     { | ||||
|         return LuaValues.checkEnum( index, klass, getString( index ) ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a table. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value. | ||||
|      * @throws LuaException If the value is not a table. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     default Map<?, ?> getTable( int index ) throws LuaException | ||||
|     { | ||||
|         Object value = get( index ); | ||||
|         if( !(value instanceof Map) ) throw LuaValues.badArgumentOf( index, "table", value ); | ||||
|         return (Map<?, ?>) value; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a double. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value, or {@link Optional#empty()} if not present. | ||||
|      * @throws LuaException If the value is not a number. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     default Optional<Double> optDouble( int index ) throws LuaException | ||||
|     { | ||||
|         Object value = get( index ); | ||||
|         if( value == null ) return Optional.empty(); | ||||
|         if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); | ||||
|         return Optional.of( ((Number) value).doubleValue() ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as an int. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value, or {@link Optional#empty()} if not present. | ||||
|      * @throws LuaException If the value is not a number. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     default Optional<Integer> optInt( int index ) throws LuaException | ||||
|     { | ||||
|         return optLong( index ).map( Long::intValue ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a long. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value, or {@link Optional#empty()} if not present. | ||||
|      * @throws LuaException If the value is not a number. | ||||
|      */ | ||||
|     default Optional<Long> optLong( int index ) throws LuaException | ||||
|     { | ||||
|         Object value = get( index ); | ||||
|         if( value == null ) return Optional.empty(); | ||||
|         if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); | ||||
|         return Optional.of( LuaValues.checkFiniteNum( index, (Number) value ).longValue() ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a finite number (not infinite or NaN). | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value, or {@link Optional#empty()} if not present. | ||||
|      * @throws LuaException If the value is not finite. | ||||
|      */ | ||||
|     default Optional<Double> optFiniteDouble( int index ) throws LuaException | ||||
|     { | ||||
|         Optional<Double> value = optDouble( index ); | ||||
|         if( value.isPresent() ) LuaValues.checkFiniteNum( index, value.get() ); | ||||
|         return value; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a boolean. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value, or {@link Optional#empty()} if not present. | ||||
|      * @throws LuaException If the value is not a boolean. | ||||
|      */ | ||||
|     default Optional<Boolean> optBoolean( int index ) throws LuaException | ||||
|     { | ||||
|         Object value = get( index ); | ||||
|         if( value == null ) return Optional.empty(); | ||||
|         if( !(value instanceof Boolean) ) throw LuaValues.badArgumentOf( index, "boolean", value ); | ||||
|         return Optional.of( (Boolean) value ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a string. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value, or {@link Optional#empty()} if not present. | ||||
|      * @throws LuaException If the value is not a string. | ||||
|      */ | ||||
|     default Optional<String> optString( int index ) throws LuaException | ||||
|     { | ||||
|         Object value = get( index ); | ||||
|         if( value == null ) return Optional.empty(); | ||||
|         if( !(value instanceof String) ) throw LuaValues.badArgumentOf( index, "string", value ); | ||||
|         return Optional.of( (String) value ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get a string argument as a byte array. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value, or {@link Optional#empty()} if not present. This is a <em>read only</em> buffer. | ||||
|      * @throws LuaException If the value is not a string. | ||||
|      */ | ||||
|     default Optional<ByteBuffer> optBytes( int index ) throws LuaException | ||||
|     { | ||||
|         return optString( index ).map( LuaValues::encode ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get a string argument as an enum value. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @param klass The type of enum to parse. | ||||
|      * @param <T>   The type of enum to parse. | ||||
|      * @return The argument's value. | ||||
|      * @throws LuaException If the value is not a string or not a valid option for this enum. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     default <T extends Enum<T>> Optional<T> optEnum( int index, Class<T> klass ) throws LuaException | ||||
|     { | ||||
|         Optional<String> str = optString( index ); | ||||
|         return str.isPresent() ? Optional.of( LuaValues.checkEnum( index, klass, str.get() ) ) : Optional.empty(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a table. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @return The argument's value, or {@link Optional#empty()} if not present. | ||||
|      * @throws LuaException If the value is not a table. | ||||
|      */ | ||||
|     default Optional<Map<?, ?>> optTable( int index ) throws LuaException | ||||
|     { | ||||
|         Object value = get( index ); | ||||
|         if( value == null ) return Optional.empty(); | ||||
|         if( !(value instanceof Map) ) throw LuaValues.badArgumentOf( index, "map", value ); | ||||
|         return Optional.of( (Map<?, ?>) value ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a double. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @param def   The default value, if this argument is not given. | ||||
|      * @return The argument's value, or {@code def} if none was provided. | ||||
|      * @throws LuaException If the value is not a number. | ||||
|      */ | ||||
|     default double optDouble( int index, double def ) throws LuaException | ||||
|     { | ||||
|         return optDouble( index ).orElse( def ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as an int. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @param def   The default value, if this argument is not given. | ||||
|      * @return The argument's value, or {@code def} if none was provided. | ||||
|      * @throws LuaException If the value is not a number. | ||||
|      */ | ||||
|     default int optInt( int index, int def ) throws LuaException | ||||
|     { | ||||
|         return optInt( index ).orElse( def ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a long. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @param def   The default value, if this argument is not given. | ||||
|      * @return The argument's value, or {@code def} if none was provided. | ||||
|      * @throws LuaException If the value is not a number. | ||||
|      */ | ||||
|     default long optLong( int index, long def ) throws LuaException | ||||
|     { | ||||
|         return optLong( index ).orElse( def ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a finite number (not infinite or NaN). | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @param def   The default value, if this argument is not given. | ||||
|      * @return The argument's value, or {@code def} if none was provided. | ||||
|      * @throws LuaException If the value is not finite. | ||||
|      */ | ||||
|     default double optFiniteDouble( int index, double def ) throws LuaException | ||||
|     { | ||||
|         return optFiniteDouble( index ).orElse( def ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a boolean. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @param def   The default value, if this argument is not given. | ||||
|      * @return The argument's value, or {@code def} if none was provided. | ||||
|      * @throws LuaException If the value is not a boolean. | ||||
|      */ | ||||
|     default boolean optBoolean( int index, boolean def ) throws LuaException | ||||
|     { | ||||
|         return optBoolean( index ).orElse( def ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a string. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @param def   The default value, if this argument is not given. | ||||
|      * @return The argument's value, or {@code def} if none was provided. | ||||
|      * @throws LuaException If the value is not a string. | ||||
|      */ | ||||
|     default String optString( int index, String def ) throws LuaException | ||||
|     { | ||||
|         return optString( index ).orElse( def ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get an argument as a table. | ||||
|      * | ||||
|      * @param index The argument number. | ||||
|      * @param def   The default value, if this argument is not given. | ||||
|      * @return The argument's value, or {@code def} if none was provided. | ||||
|      * @throws LuaException If the value is not a table. | ||||
|      */ | ||||
|     default Map<?, ?> optTable( int index, Map<Object, Object> def ) throws LuaException | ||||
|     { | ||||
|         return optTable( index ).orElse( def ); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,34 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import dan200.computercraft.api.filesystem.IFileSystem; | ||||
| import dan200.computercraft.api.peripheral.IComputerAccess; | ||||
|  | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * An interface passed to {@link ILuaAPIFactory} in order to provide additional information | ||||
|  * about a computer. | ||||
|  */ | ||||
| public interface IComputerSystem extends IComputerAccess | ||||
| { | ||||
|     /** | ||||
|      * Get the file system for this computer. | ||||
|      * | ||||
|      * @return The computer's file system, or {@code null} if it is not initialised. | ||||
|      */ | ||||
|     @Nullable | ||||
|     IFileSystem getFileSystem(); | ||||
|  | ||||
|     /** | ||||
|      * Get the label for this computer. | ||||
|      * | ||||
|      * @return This computer's label, or {@code null} if it is not set. | ||||
|      */ | ||||
|     @Nullable | ||||
|     String getLabel(); | ||||
| } | ||||
| @@ -0,0 +1,45 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import dan200.computercraft.api.peripheral.IDynamicPeripheral; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * An interface for representing custom objects returned by peripherals or other Lua objects. | ||||
|  * | ||||
|  * Generally, one does not need to implement this type - it is sufficient to return an object with some methods | ||||
|  * annotated with {@link LuaFunction}. {@link IDynamicLuaObject} is useful when you wish your available methods to | ||||
|  * change at runtime. | ||||
|  */ | ||||
| public interface IDynamicLuaObject | ||||
| { | ||||
|     /** | ||||
|      * Get the names of the methods that this object implements. This should not change over the course of the object's | ||||
|      * lifetime. | ||||
|      * | ||||
|      * @return The method names this object provides. | ||||
|      * @see IDynamicPeripheral#getMethodNames() | ||||
|      */ | ||||
|     @Nonnull | ||||
|     String[] getMethodNames(); | ||||
|  | ||||
|     /** | ||||
|      * Called when a user calls one of the methods that this object implements. | ||||
|      * | ||||
|      * @param context   The context of the currently running lua thread. This can be used to wait for events | ||||
|      *                  or otherwise yield. | ||||
|      * @param method    An integer identifying which method index from {@link #getMethodNames()} the computer wishes | ||||
|      *                  to call. | ||||
|      * @param arguments The arguments for this method. | ||||
|      * @return The result of this function. Either an immediate value ({@link MethodResult#of(Object...)} or an | ||||
|      * instruction to yield. | ||||
|      * @throws LuaException If the function threw an exception. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     MethodResult callMethod( @Nonnull ILuaContext context, int method, @Nonnull IArguments arguments ) throws LuaException; | ||||
| } | ||||
							
								
								
									
										53
									
								
								src/main/java/dan200/computercraft/api/lua/ILuaAPI.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										53
									
								
								src/main/java/dan200/computercraft/api/lua/ILuaAPI.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,53 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import dan200.computercraft.api.ComputerCraftAPI; | ||||
|  | ||||
| /** | ||||
|  * Represents a Lua object which is stored as a global variable on computer startup. This must either provide | ||||
|  * {@link LuaFunction} annotated functions or implement {@link IDynamicLuaObject}. | ||||
|  * | ||||
|  * Before implementing this interface, consider alternative methods of providing methods. It is generally preferred | ||||
|  * to use peripherals to provide functionality to users. | ||||
|  * | ||||
|  * @see ILuaAPIFactory | ||||
|  * @see ComputerCraftAPI#registerAPIFactory(ILuaAPIFactory) | ||||
|  */ | ||||
| public interface ILuaAPI | ||||
| { | ||||
|     /** | ||||
|      * Get the globals this API will be assigned to. This will override any other global, so you should | ||||
|      * | ||||
|      * @return A list of globals this API will be assigned to. | ||||
|      */ | ||||
|     String[] getNames(); | ||||
|  | ||||
|     /** | ||||
|      * Called when the computer is turned on. | ||||
|      * | ||||
|      * One should only interact with the file system. | ||||
|      */ | ||||
|     default void startup() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Called every time the computer is ticked. This can be used to process various. | ||||
|      */ | ||||
|     default void update() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Called when the computer is turned off or unloaded. | ||||
|      * | ||||
|      * This should reset the state of the object, disposing any remaining file handles, or other resources. | ||||
|      */ | ||||
|     default void shutdown() | ||||
|     { | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,30 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import dan200.computercraft.api.ComputerCraftAPI; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * Construct an {@link ILuaAPI} for a specific computer. | ||||
|  * | ||||
|  * @see ILuaAPI | ||||
|  * @see ComputerCraftAPI#registerAPIFactory(ILuaAPIFactory) | ||||
|  */ | ||||
| @FunctionalInterface | ||||
| public interface ILuaAPIFactory | ||||
| { | ||||
|     /** | ||||
|      * Create a new API instance for a given computer. | ||||
|      * | ||||
|      * @param computer The computer this API is for. | ||||
|      * @return The created API, or {@code null} if one should not be injected. | ||||
|      */ | ||||
|     @Nullable | ||||
|     ILuaAPI create( @Nonnull IComputerSystem computer ); | ||||
| } | ||||
							
								
								
									
										27
									
								
								src/main/java/dan200/computercraft/api/lua/ILuaCallback.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										27
									
								
								src/main/java/dan200/computercraft/api/lua/ILuaCallback.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,27 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * A continuation which is called when this coroutine is resumed. | ||||
|  * | ||||
|  * @see MethodResult#yield(Object[], ILuaCallback) | ||||
|  */ | ||||
| public interface ILuaCallback | ||||
| { | ||||
|     /** | ||||
|      * Resume this coroutine. | ||||
|      * | ||||
|      * @param args The result of resuming this coroutine. These will have the same form as described in | ||||
|      *             {@link LuaFunction}. | ||||
|      * @return The result of this continuation. Either the result to return to the callee, or another yield. | ||||
|      * @throws LuaException On an error. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     MethodResult resume( Object[] args ) throws LuaException; | ||||
| } | ||||
							
								
								
									
										30
									
								
								src/main/java/dan200/computercraft/api/lua/ILuaContext.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										30
									
								
								src/main/java/dan200/computercraft/api/lua/ILuaContext.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,30 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * An interface passed to peripherals and {@link IDynamicLuaObject}s by computers or turtles, providing methods | ||||
|  * that allow the peripheral call to interface with the computer. | ||||
|  */ | ||||
| public interface ILuaContext | ||||
| { | ||||
|     /** | ||||
|      * Queue a task to be executed on the main server thread at the beginning of next tick, but do not wait for it to | ||||
|      * complete. This should be used when you need to interact with the world in a thread-safe manner but do not care | ||||
|      * about the result or you wish to run asynchronously. | ||||
|      * | ||||
|      * When the task has finished, it will enqueue a {@code task_completed} event, which takes the task id, a success | ||||
|      * value and the return values, or an error message if it failed. | ||||
|      * | ||||
|      * @param task The task to execute on the main thread. | ||||
|      * @return The "id" of the task. This will be the first argument to the {@code task_completed} event. | ||||
|      * @throws LuaException If the task could not be queued. | ||||
|      * @see LuaFunction#mainThread() To run functions on the main thread and return their results synchronously. | ||||
|      */ | ||||
|     long issueMainThreadTask( @Nonnull ILuaTask task ) throws LuaException; | ||||
| } | ||||
							
								
								
									
										29
									
								
								src/main/java/dan200/computercraft/api/lua/ILuaFunction.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										29
									
								
								src/main/java/dan200/computercraft/api/lua/ILuaFunction.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,29 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * A function, which can be called from Lua. If you need to return a table of functions, it is recommended to use | ||||
|  * an object with {@link LuaFunction} methods, or implement {@link IDynamicLuaObject}. | ||||
|  * | ||||
|  * @see MethodResult#of(Object) | ||||
|  */ | ||||
| @FunctionalInterface | ||||
| public interface ILuaFunction | ||||
| { | ||||
|     /** | ||||
|      * Call this function with a series of arguments. Note, this will <em>always</em> be called on the computer thread, | ||||
|      * and so its implementation must be thread-safe. | ||||
|      * | ||||
|      * @param arguments The arguments for this function | ||||
|      * @return The result of calling this function. | ||||
|      * @throws LuaException Upon Lua errors. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     MethodResult call( @Nonnull IArguments arguments ) throws LuaException; | ||||
| } | ||||
							
								
								
									
										30
									
								
								src/main/java/dan200/computercraft/api/lua/ILuaTask.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										30
									
								
								src/main/java/dan200/computercraft/api/lua/ILuaTask.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,30 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * A task which can be executed via {@link ILuaContext#issueMainThreadTask(ILuaTask)} This will be run on the main | ||||
|  * thread, at the beginning of the | ||||
|  * next tick. | ||||
|  * | ||||
|  * @see ILuaContext#issueMainThreadTask(ILuaTask) | ||||
|  */ | ||||
| @FunctionalInterface | ||||
| public interface ILuaTask | ||||
| { | ||||
|     /** | ||||
|      * Execute this task. | ||||
|      * | ||||
|      * @return The arguments to add to the {@code task_completed} event. | ||||
|      * @throws LuaException If you throw any exception from this function, a lua error will be raised with the | ||||
|      *                      same message as your exception. Use this to throw appropriate errors if the wrong | ||||
|      *                      arguments are supplied to your method. | ||||
|      */ | ||||
|     @Nullable | ||||
|     Object[] execute() throws LuaException; | ||||
| } | ||||
							
								
								
									
										53
									
								
								src/main/java/dan200/computercraft/api/lua/LuaException.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										53
									
								
								src/main/java/dan200/computercraft/api/lua/LuaException.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,53 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * An exception representing an error in Lua, like that raised by the {@code error()} function. | ||||
|  */ | ||||
| public class LuaException extends Exception | ||||
| { | ||||
|     private static final long serialVersionUID = -6136063076818512651L; | ||||
|     private final boolean hasLevel; | ||||
|     private final int level; | ||||
|  | ||||
|     public LuaException( @Nullable String message ) | ||||
|     { | ||||
|         super( message ); | ||||
|         this.hasLevel = false; | ||||
|         this.level = 1; | ||||
|     } | ||||
|  | ||||
|     public LuaException( @Nullable String message, int level ) | ||||
|     { | ||||
|         super( message ); | ||||
|         this.hasLevel = true; | ||||
|         this.level = level; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Whether a level was explicitly specified when constructing. This is used to determine | ||||
|      * | ||||
|      * @return Whether this has an explicit level. | ||||
|      */ | ||||
|     public boolean hasLevel() | ||||
|     { | ||||
|         return hasLevel; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * The level this error is raised at. Level 1 is the function's caller, level 2 is that function's caller, and so | ||||
|      * on. | ||||
|      * | ||||
|      * @return The level to raise the error at. | ||||
|      */ | ||||
|     public int getLevel() | ||||
|     { | ||||
|         return level; | ||||
|     } | ||||
| } | ||||
							
								
								
									
										58
									
								
								src/main/java/dan200/computercraft/api/lua/LuaFunction.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										58
									
								
								src/main/java/dan200/computercraft/api/lua/LuaFunction.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,58 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import dan200.computercraft.api.peripheral.IComputerAccess; | ||||
| import dan200.computercraft.api.peripheral.IPeripheral; | ||||
|  | ||||
| import java.lang.annotation.*; | ||||
| import java.util.Map; | ||||
| import java.util.Optional; | ||||
|  | ||||
| /** | ||||
|  * Used to mark a Java function which is callable from Lua. | ||||
|  * | ||||
|  * Methods annotated with {@link LuaFunction} must be public final instance methods. They can have any number of | ||||
|  * parameters, but they must be of the following types: | ||||
|  * | ||||
|  * <ul> | ||||
|  *   <li>{@link ILuaContext} (and {@link IComputerAccess} if on a {@link IPeripheral})</li> | ||||
|  *   <li>{@link IArguments}: The arguments supplied to this function.</li> | ||||
|  *   <li> | ||||
|  *     Alternatively, one may specify the desired arguments as normal parameters and the argument parsing code will | ||||
|  *     be generated automatically. | ||||
|  * | ||||
|  *     Each parameter must be one of the given types supported by {@link IArguments} (for instance, {@link int} or | ||||
|  *     {@link Map}). Optional values are supported by accepting a parameter of type {@link Optional}. | ||||
|  *   </li> | ||||
|  * </ul> | ||||
|  * | ||||
|  * This function may return {@link MethodResult}. However, if you simply return a value (rather than having to yield), | ||||
|  * you may return {@code void}, a single value (either an object or a primitive like {@code int}) or array of objects. | ||||
|  * These will be treated the same as {@link MethodResult#of()}, {@link MethodResult#of(Object)} and | ||||
|  * {@link MethodResult#of(Object...)}. | ||||
|  */ | ||||
| @Documented | ||||
| @Retention( RetentionPolicy.RUNTIME ) | ||||
| @Target( ElementType.METHOD ) | ||||
| public @interface LuaFunction | ||||
| { | ||||
|     /** | ||||
|      * Explicitly specify the method names of this function. If not given, it uses the name of the annotated method. | ||||
|      * | ||||
|      * @return This function's name(s). | ||||
|      */ | ||||
|     String[] value() default {}; | ||||
|  | ||||
|     /** | ||||
|      * Run this function on the main server thread. This should be specified for any method which interacts with | ||||
|      * Minecraft in a thread-unsafe manner. | ||||
|      * | ||||
|      * @return Whether this functi | ||||
|      * @see ILuaContext#issueMainThreadTask(ILuaTask) | ||||
|      */ | ||||
|     boolean mainThread() default false; | ||||
| } | ||||
							
								
								
									
										152
									
								
								src/main/java/dan200/computercraft/api/lua/LuaValues.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										152
									
								
								src/main/java/dan200/computercraft/api/lua/LuaValues.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,152 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.nio.ByteBuffer; | ||||
| import java.util.Map; | ||||
|  | ||||
| /** | ||||
|  * Various utility functions for operating with Lua values. | ||||
|  * | ||||
|  * @see IArguments | ||||
|  */ | ||||
| public final class LuaValues | ||||
| { | ||||
|     private LuaValues() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Encode a Lua string into a read-only {@link ByteBuffer}. | ||||
|      * | ||||
|      * @param string The string to encode. | ||||
|      * @return The encoded string. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static ByteBuffer encode( @Nonnull String string ) | ||||
|     { | ||||
|         byte[] chars = new byte[string.length()]; | ||||
|         for( int i = 0; i < chars.length; i++ ) | ||||
|         { | ||||
|             char c = string.charAt( i ); | ||||
|             chars[i] = c < 256 ? (byte) c : 63; | ||||
|         } | ||||
|  | ||||
|         return ByteBuffer.wrap( chars ).asReadOnlyBuffer(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns a more detailed representation of this number's type. If this is finite, it will just return "number", | ||||
|      * otherwise it returns whether it is infinite or NaN. | ||||
|      * | ||||
|      * @param value The value to extract the type for. | ||||
|      * @return This value's numeric type. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static String getNumericType( double value ) | ||||
|     { | ||||
|         if( Double.isNaN( value ) ) return "nan"; | ||||
|         if( value == Double.POSITIVE_INFINITY ) return "inf"; | ||||
|         if( value == Double.NEGATIVE_INFINITY ) return "-inf"; | ||||
|         return "number"; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get a string representation of the given value's type. | ||||
|      * | ||||
|      * @param value The value whose type we are trying to compute. | ||||
|      * @return A string representation of the given value's type, in a similar format to that provided by Lua's | ||||
|      * {@code type} function. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static String getType( @Nullable Object value ) | ||||
|     { | ||||
|         if( value == null ) return "nil"; | ||||
|         if( value instanceof String ) return "string"; | ||||
|         if( value instanceof Boolean ) return "boolean"; | ||||
|         if( value instanceof Number ) return "number"; | ||||
|         if( value instanceof Map ) return "table"; | ||||
|         return "userdata"; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Construct a "bad argument" exception, from an expected type and the actual value provided. | ||||
|      * | ||||
|      * @param index    The argument number, starting from 0. | ||||
|      * @param expected The expected type for this argument. | ||||
|      * @param actual   The actual value provided for this argument. | ||||
|      * @return The constructed exception, which should be thrown immediately. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static LuaException badArgumentOf( int index, @Nonnull String expected, @Nullable Object actual ) | ||||
|     { | ||||
|         return badArgument( index, expected, getType( actual ) ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Construct a "bad argument" exception, from an expected and actual type. | ||||
|      * | ||||
|      * @param index    The argument number, starting from 0. | ||||
|      * @param expected The expected type for this argument. | ||||
|      * @param actual   The provided type for this argument. | ||||
|      * @return The constructed exception, which should be thrown immediately. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static LuaException badArgument( int index, @Nonnull String expected, @Nonnull String actual ) | ||||
|     { | ||||
|         return new LuaException( "bad argument #" + (index + 1) + " (" + expected + " expected, got " + actual + ")" ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Ensure a numeric argument is finite (i.e. not infinite or {@link Double#NaN}. | ||||
|      * | ||||
|      * @param index The argument index to check. | ||||
|      * @param value The value to check. | ||||
|      * @return The input {@code value}. | ||||
|      * @throws LuaException If this is not a finite number. | ||||
|      */ | ||||
|     public static Number checkFiniteNum( int index, Number value ) throws LuaException | ||||
|     { | ||||
|         checkFinite( index, value.doubleValue() ); | ||||
|         return value; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Ensure a numeric argument is finite (i.e. not infinite or {@link Double#NaN}. | ||||
|      * | ||||
|      * @param index The argument index to check. | ||||
|      * @param value The value to check. | ||||
|      * @return The input {@code value}. | ||||
|      * @throws LuaException If this is not a finite number. | ||||
|      */ | ||||
|     public static double checkFinite( int index, double value ) throws LuaException | ||||
|     { | ||||
|         if( !Double.isFinite( value ) ) throw badArgument( index, "number", getNumericType( value ) ); | ||||
|         return value; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Ensure a string is a valid enum value. | ||||
|      * | ||||
|      * @param index The argument index to check. | ||||
|      * @param klass The class of the enum instance. | ||||
|      * @param value The value to extract. | ||||
|      * @param <T>   The type of enum we are extracting. | ||||
|      * @return The parsed enum value. | ||||
|      * @throws LuaException If this is not a known enum value. | ||||
|      */ | ||||
|     public static <T extends Enum<T>> T checkEnum( int index, Class<T> klass, String value ) throws LuaException | ||||
|     { | ||||
|         for( T possibility : klass.getEnumConstants() ) | ||||
|         { | ||||
|             if( possibility.name().equalsIgnoreCase( value ) ) return possibility; | ||||
|         } | ||||
|  | ||||
|         throw new LuaException( "bad argument #" + (index + 1) + " (unknown option " + value + ")" ); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										170
									
								
								src/main/java/dan200/computercraft/api/lua/MethodResult.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										170
									
								
								src/main/java/dan200/computercraft/api/lua/MethodResult.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,170 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import dan200.computercraft.api.peripheral.IComputerAccess; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.nio.ByteBuffer; | ||||
| import java.util.Collection; | ||||
| import java.util.Map; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * The result of invoking a Lua method. | ||||
|  * | ||||
|  * Method results either return a value immediately ({@link #of(Object...)} or yield control to the parent coroutine. | ||||
|  * When the current coroutine is resumed, we invoke the provided {@link ILuaCallback#resume(Object[])} callback. | ||||
|  */ | ||||
| public final class MethodResult | ||||
| { | ||||
|     private static final MethodResult empty = new MethodResult( null, null ); | ||||
|  | ||||
|     private final Object[] result; | ||||
|     private final ILuaCallback callback; | ||||
|     private final int adjust; | ||||
|  | ||||
|     private MethodResult( Object[] arguments, ILuaCallback callback ) | ||||
|     { | ||||
|         this.result = arguments; | ||||
|         this.callback = callback; | ||||
|         this.adjust = 0; | ||||
|     } | ||||
|  | ||||
|     private MethodResult( Object[] arguments, ILuaCallback callback, int adjust ) | ||||
|     { | ||||
|         this.result = arguments; | ||||
|         this.callback = callback; | ||||
|         this.adjust = adjust; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Return no values immediately. | ||||
|      * | ||||
|      * @return A method result which returns immediately with no values. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static MethodResult of() | ||||
|     { | ||||
|         return empty; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Return a single value immediately. | ||||
|      * | ||||
|      * Integers, doubles, floats, strings, booleans, {@link Map}, {@link Collection}s, arrays and {@code null} will be | ||||
|      * converted to their corresponding Lua type. {@code byte[]} and {@link ByteBuffer} will be treated as binary | ||||
|      * strings. {@link ILuaFunction} will be treated as a function. | ||||
|      * | ||||
|      * In order to provide a custom object with methods, one may return a {@link IDynamicLuaObject}, or an arbitrary | ||||
|      * class with {@link LuaFunction} annotations. Anything else will be converted to {@code nil}. | ||||
|      * | ||||
|      * @param value The value to return to the calling Lua function. | ||||
|      * @return A method result which returns immediately with the given value. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static MethodResult of( @Nullable Object value ) | ||||
|     { | ||||
|         return new MethodResult( new Object[] { value }, null ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Return any number of values immediately. | ||||
|      * | ||||
|      * @param values The values to return. See {@link #of(Object)} for acceptable values. | ||||
|      * @return A method result which returns immediately with the given values. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static MethodResult of( @Nullable Object... values ) | ||||
|     { | ||||
|         return values == null || values.length == 0 ? empty : new MethodResult( values, null ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Wait for an event to occur on the computer, suspending the thread until it arises. This method is exactly | ||||
|      * equivalent to {@code os.pullEvent()} in lua. | ||||
|      * | ||||
|      * @param filter   A specific event to wait for, or null to wait for any event. | ||||
|      * @param callback The callback to resume with the name of the event that occurred, and any event parameters. | ||||
|      * @return The method result which represents this yield. | ||||
|      * @see IComputerAccess#queueEvent(String, Object[]) | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static MethodResult pullEvent( @Nullable String filter, @Nonnull ILuaCallback callback ) | ||||
|     { | ||||
|         Objects.requireNonNull( callback, "callback cannot be null" ); | ||||
|         return new MethodResult( new Object[] { filter }, results -> { | ||||
|             if( results.length >= 1 && results[0].equals( "terminate" ) ) throw new LuaException( "Terminated", 0 ); | ||||
|             return callback.resume( results ); | ||||
|         } ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * The same as {@link #pullEvent(String, ILuaCallback)}, except "terminated" events are ignored. Only use this if | ||||
|      * you want to prevent program termination, which is not recommended. This method is exactly equivalent to | ||||
|      * {@code os.pullEventRaw()} in Lua. | ||||
|      * | ||||
|      * @param filter   A specific event to wait for, or null to wait for any event. | ||||
|      * @param callback The callback to resume with the name of the event that occurred, and any event parameters. | ||||
|      * @return The method result which represents this yield. | ||||
|      * @see #pullEvent(String, ILuaCallback) | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static MethodResult pullEventRaw( @Nullable String filter, @Nonnull ILuaCallback callback ) | ||||
|     { | ||||
|         Objects.requireNonNull( callback, "callback cannot be null" ); | ||||
|         return new MethodResult( new Object[] { filter }, callback ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Yield the current coroutine with some arguments until it is resumed. This method is exactly equivalent to | ||||
|      * {@code coroutine.yield()} in lua. Use {@code pullEvent()} if you wish to wait for events. | ||||
|      * | ||||
|      * @param arguments An object array containing the arguments to pass to coroutine.yield() | ||||
|      * @param callback  The callback to resume with an array containing the return values from coroutine.yield() | ||||
|      * @return The method result which represents this yield. | ||||
|      * @see #pullEvent(String, ILuaCallback) | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static MethodResult yield( @Nullable Object[] arguments, @Nonnull ILuaCallback callback ) | ||||
|     { | ||||
|         Objects.requireNonNull( callback, "callback cannot be null" ); | ||||
|         return new MethodResult( arguments, callback ); | ||||
|     } | ||||
|  | ||||
|     @Nullable | ||||
|     public Object[] getResult() | ||||
|     { | ||||
|         return result; | ||||
|     } | ||||
|  | ||||
|     @Nullable | ||||
|     public ILuaCallback getCallback() | ||||
|     { | ||||
|         return callback; | ||||
|     } | ||||
|  | ||||
|     public int getErrorAdjust() | ||||
|     { | ||||
|         return adjust; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Increase the Lua error by a specific amount. One should never need to use this function - it largely exists for | ||||
|      * some CC internal code. | ||||
|      * | ||||
|      * @param adjust The amount to increase the level by. | ||||
|      * @return The new {@link MethodResult} with an adjusted error. This has no effect on immediate results. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public MethodResult adjustError( int adjust ) | ||||
|     { | ||||
|         if( adjust < 0 ) throw new IllegalArgumentException( "cannot adjust by a negative amount" ); | ||||
|         if( adjust == 0 || callback == null ) return this; | ||||
|         return new MethodResult( result, callback, this.adjust + adjust ); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,66 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.lua; | ||||
|  | ||||
| import javax.annotation.Nullable; | ||||
| import java.util.Arrays; | ||||
| import java.util.List; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * An implementation of {@link IArguments} which wraps an array of {@link Object}. | ||||
|  */ | ||||
| public final class ObjectArguments implements IArguments | ||||
| { | ||||
|     private static final IArguments EMPTY = new ObjectArguments(); | ||||
|     private final List<Object> args; | ||||
|  | ||||
|     @Deprecated | ||||
|     @SuppressWarnings( "unused" ) | ||||
|     public ObjectArguments( IArguments arguments ) | ||||
|     { | ||||
|         throw new IllegalStateException(); | ||||
|     } | ||||
|  | ||||
|     public ObjectArguments( Object... args ) | ||||
|     { | ||||
|         this.args = Arrays.asList( args ); | ||||
|     } | ||||
|  | ||||
|     public ObjectArguments( List<Object> args ) | ||||
|     { | ||||
|         this.args = Objects.requireNonNull( args ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public int count() | ||||
|     { | ||||
|         return args.size(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public IArguments drop( int count ) | ||||
|     { | ||||
|         if( count < 0 ) throw new IllegalStateException( "count cannot be negative" ); | ||||
|         if( count == 0 ) return this; | ||||
|         if( count >= args.size() ) return EMPTY; | ||||
|  | ||||
|         return new ObjectArguments( args.subList( count, args.size() ) ); | ||||
|     } | ||||
|  | ||||
|     @Nullable | ||||
|     @Override | ||||
|     public Object get( int index ) | ||||
|     { | ||||
|         return index >= args.size() ? null : args.get( index ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public Object[] getAll() | ||||
|     { | ||||
|         return args.toArray(); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										89
									
								
								src/main/java/dan200/computercraft/api/media/IMedia.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										89
									
								
								src/main/java/dan200/computercraft/api/media/IMedia.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,89 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.media; | ||||
|  | ||||
| import dan200.computercraft.api.filesystem.IMount; | ||||
| import net.minecraft.item.Item; | ||||
| import net.minecraft.item.ItemStack; | ||||
| import net.minecraft.sound.SoundEvent; | ||||
| import net.minecraft.world.World; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * Represents an item that can be placed in a disk drive and used by a Computer. | ||||
|  * | ||||
|  * Implement this interface on your {@link Item} class to allow it to be used in the drive. Alternatively, register | ||||
|  * a {@link IMediaProvider}. | ||||
|  */ | ||||
| public interface IMedia | ||||
| { | ||||
|     /** | ||||
|      * Get a string representing the label of this item. Will be called via {@code disk.getLabel()} in lua. | ||||
|      * | ||||
|      * @param stack The {@link ItemStack} to inspect. | ||||
|      * @return The label. ie: "Dan's Programs". | ||||
|      */ | ||||
|     @Nullable | ||||
|     String getLabel( @Nonnull ItemStack stack ); | ||||
|  | ||||
|     /** | ||||
|      * Set a string representing the label of this item. Will be called vi {@code disk.setLabel()} in lua. | ||||
|      * | ||||
|      * @param stack The {@link ItemStack} to modify. | ||||
|      * @param label The string to set the label to. | ||||
|      * @return true if the label was updated, false if the label may not be modified. | ||||
|      */ | ||||
|     default boolean setLabel( @Nonnull ItemStack stack, @Nullable String label ) | ||||
|     { | ||||
|         return false; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * If this disk represents an item with audio (like a record), get the readable name of the audio track. ie: | ||||
|      * "Jonathan Coulton - Still Alive" | ||||
|      * | ||||
|      * @param stack The {@link ItemStack} to modify. | ||||
|      * @return The name, or null if this item does not represent an item with audio. | ||||
|      */ | ||||
|     @Nullable | ||||
|     default String getAudioTitle( @Nonnull ItemStack stack ) | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * If this disk represents an item with audio (like a record), get the resource name of the audio track to play. | ||||
|      * | ||||
|      * @param stack The {@link ItemStack} to modify. | ||||
|      * @return The name, or null if this item does not represent an item with audio. | ||||
|      */ | ||||
|     @Nullable | ||||
|     default SoundEvent getAudio( @Nonnull ItemStack stack ) | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * If this disk represents an item with data (like a floppy disk), get a mount representing it's contents. This will | ||||
|      * be mounted onto the filesystem of the computer while the media is in the disk drive. | ||||
|      * | ||||
|      * @param stack The {@link ItemStack} to modify. | ||||
|      * @param world The world in which the item and disk drive reside. | ||||
|      * @return The mount, or null if this item does not represent an item with data. If the mount returned also | ||||
|      * implements {@link dan200.computercraft.api.filesystem.IWritableMount}, it will mounted using mountWritable() | ||||
|      * @see IMount | ||||
|      * @see dan200.computercraft.api.filesystem.IWritableMount | ||||
|      * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String, long) | ||||
|      * @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(String, String) | ||||
|      */ | ||||
|     @Nullable | ||||
|     default IMount createDataMount( @Nonnull ItemStack stack, @Nonnull World world ) | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,30 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.media; | ||||
|  | ||||
| import net.minecraft.item.ItemStack; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * This interface is used to provide {@link IMedia} implementations for {@link ItemStack}. | ||||
|  * | ||||
|  * @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider) | ||||
|  */ | ||||
| @FunctionalInterface | ||||
| public interface IMediaProvider | ||||
| { | ||||
|     /** | ||||
|      * Produce an IMedia implementation from an ItemStack. | ||||
|      * | ||||
|      * @param stack The stack from which to extract the media information. | ||||
|      * @return An {@link IMedia} implementation, or {@code null} if the item is not something you wish to handle | ||||
|      * @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider) | ||||
|      */ | ||||
|     @Nullable | ||||
|     IMedia getMedia( @Nonnull ItemStack stack ); | ||||
| } | ||||
| @@ -0,0 +1,59 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.network; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * A packet network represents a collection of devices which can send and receive packets. | ||||
|  * | ||||
|  * @see Packet | ||||
|  * @see IPacketReceiver | ||||
|  */ | ||||
| public interface IPacketNetwork | ||||
| { | ||||
|     /** | ||||
|      * Add a receiver to the network. | ||||
|      * | ||||
|      * @param receiver The receiver to register to the network. | ||||
|      */ | ||||
|     void addReceiver( @Nonnull IPacketReceiver receiver ); | ||||
|  | ||||
|     /** | ||||
|      * Remove a receiver from the network. | ||||
|      * | ||||
|      * @param receiver The device to remove from the network. | ||||
|      */ | ||||
|     void removeReceiver( @Nonnull IPacketReceiver receiver ); | ||||
|  | ||||
|     /** | ||||
|      * Determine whether this network is wireless. | ||||
|      * | ||||
|      * @return Whether this network is wireless. | ||||
|      */ | ||||
|     boolean isWireless(); | ||||
|  | ||||
|     /** | ||||
|      * Submit a packet for transmitting across the network. This will route the packet through the network, sending it | ||||
|      * to all receivers within range (or any interdimensional ones). | ||||
|      * | ||||
|      * @param packet The packet to send. | ||||
|      * @param range  The maximum distance this packet will be sent. | ||||
|      * @see #transmitInterdimensional(Packet) | ||||
|      * @see IPacketReceiver#receiveSameDimension(Packet, double) | ||||
|      */ | ||||
|     void transmitSameDimension( @Nonnull Packet packet, double range ); | ||||
|  | ||||
|     /** | ||||
|      * Submit a packet for transmitting across the network. This will route the packet through the network, sending it | ||||
|      * to all receivers across all dimensions. | ||||
|      * | ||||
|      * @param packet The packet to send. | ||||
|      * @see #transmitSameDimension(Packet, double) | ||||
|      * @see IPacketReceiver#receiveDifferentDimension(Packet) | ||||
|      */ | ||||
|     void transmitInterdimensional( @Nonnull Packet packet ); | ||||
| } | ||||
| @@ -0,0 +1,84 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.network; | ||||
|  | ||||
| import net.minecraft.util.math.Vec3d; | ||||
| import net.minecraft.world.World; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * An object on an {@link IPacketNetwork}, capable of receiving packets. | ||||
|  */ | ||||
| public interface IPacketReceiver | ||||
| { | ||||
|     /** | ||||
|      * Get the world in which this packet receiver exists. | ||||
|      * | ||||
|      * @return The receivers's world. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     World getWorld(); | ||||
|  | ||||
|     /** | ||||
|      * Get the position in the world at which this receiver exists. | ||||
|      * | ||||
|      * @return The receiver's position. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     Vec3d getPosition(); | ||||
|  | ||||
|     /** | ||||
|      * Get the maximum distance this receiver can send and receive messages. | ||||
|      * | ||||
|      * When determining whether a receiver can receive a message, the largest distance of the packet and receiver is | ||||
|      * used - ensuring it is within range. If the packet or receiver is inter-dimensional, then the packet will always | ||||
|      * be received. | ||||
|      * | ||||
|      * @return The maximum distance this device can send and receive messages. | ||||
|      * @see #isInterdimensional() | ||||
|      * @see #receiveSameDimension(Packet packet, double) | ||||
|      * @see IPacketNetwork#transmitInterdimensional(Packet) | ||||
|      */ | ||||
|     double getRange(); | ||||
|  | ||||
|     /** | ||||
|      * Determine whether this receiver can receive packets from other dimensions. | ||||
|      * | ||||
|      * A device will receive an inter-dimensional packet if either it or the sending device is inter-dimensional. | ||||
|      * | ||||
|      * @return Whether this receiver receives packets from other dimensions. | ||||
|      * @see #getRange() | ||||
|      * @see #receiveDifferentDimension(Packet) | ||||
|      * @see IPacketNetwork#transmitInterdimensional(Packet) | ||||
|      */ | ||||
|     boolean isInterdimensional(); | ||||
|  | ||||
|     /** | ||||
|      * Receive a network packet from the same dimension. | ||||
|      * | ||||
|      * @param packet   The packet to receive. Generally you should check that you are listening on the given channel and, | ||||
|      *                 if so, queue the appropriate modem event. | ||||
|      * @param distance The distance this packet has travelled from the source. | ||||
|      * @see Packet | ||||
|      * @see #getRange() | ||||
|      * @see IPacketNetwork#transmitSameDimension(Packet, double) | ||||
|      * @see IPacketNetwork#transmitInterdimensional(Packet) | ||||
|      */ | ||||
|     void receiveSameDimension( @Nonnull Packet packet, double distance ); | ||||
|  | ||||
|     /** | ||||
|      * Receive a network packet from a different dimension. | ||||
|      * | ||||
|      * @param packet The packet to receive. Generally you should check that you are listening on the given channel and, | ||||
|      *               if so, queue the appropriate modem event. | ||||
|      * @see Packet | ||||
|      * @see IPacketNetwork#transmitInterdimensional(Packet) | ||||
|      * @see IPacketNetwork#transmitSameDimension(Packet, double) | ||||
|      * @see #isInterdimensional() | ||||
|      */ | ||||
|     void receiveDifferentDimension( @Nonnull Packet packet ); | ||||
| } | ||||
| @@ -0,0 +1,42 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.network; | ||||
|  | ||||
| import net.minecraft.util.math.Vec3d; | ||||
| import net.minecraft.world.World; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * An object on a {@link IPacketNetwork}, capable of sending packets. | ||||
|  */ | ||||
| public interface IPacketSender | ||||
| { | ||||
|     /** | ||||
|      * Get the world in which this packet sender exists. | ||||
|      * | ||||
|      * @return The sender's world. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     World getWorld(); | ||||
|  | ||||
|     /** | ||||
|      * Get the position in the world at which this sender exists. | ||||
|      * | ||||
|      * @return The sender's position. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     Vec3d getPosition(); | ||||
|  | ||||
|     /** | ||||
|      * Get some sort of identification string for this sender. This does not strictly need to be unique, but you | ||||
|      * should be able to extract some identifiable information from it. | ||||
|      * | ||||
|      * @return This device's id. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     String getSenderID(); | ||||
| } | ||||
							
								
								
									
										117
									
								
								src/main/java/dan200/computercraft/api/network/Packet.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										117
									
								
								src/main/java/dan200/computercraft/api/network/Packet.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,117 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.network; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * Represents a packet which may be sent across a {@link IPacketNetwork}. | ||||
|  * | ||||
|  * @see IPacketSender | ||||
|  * @see IPacketNetwork#transmitSameDimension(Packet, double) | ||||
|  * @see IPacketNetwork#transmitInterdimensional(Packet) | ||||
|  * @see IPacketReceiver#receiveDifferentDimension(Packet) | ||||
|  * @see IPacketReceiver#receiveSameDimension(Packet, double) | ||||
|  */ | ||||
| public class Packet | ||||
| { | ||||
|     private final int channel; | ||||
|     private final int replyChannel; | ||||
|     private final Object payload; | ||||
|  | ||||
|     private final IPacketSender sender; | ||||
|  | ||||
|     /** | ||||
|      * Create a new packet, ready for transmitting across the network. | ||||
|      * | ||||
|      * @param channel      The channel to send the packet along. Receiving devices should only process packets from on | ||||
|      *                     channels they are listening to. | ||||
|      * @param replyChannel The channel to reply on. | ||||
|      * @param payload      The contents of this packet. This should be a "valid" Lua object, safe for queuing as an | ||||
|      *                     event or returning from a peripheral call. | ||||
|      * @param sender       The object which sent this packet. | ||||
|      */ | ||||
|     public Packet( int channel, int replyChannel, @Nullable Object payload, @Nonnull IPacketSender sender ) | ||||
|     { | ||||
|         Objects.requireNonNull( sender, "sender cannot be null" ); | ||||
|  | ||||
|         this.channel = channel; | ||||
|         this.replyChannel = replyChannel; | ||||
|         this.payload = payload; | ||||
|         this.sender = sender; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the channel this packet is sent along. Receivers should generally only process packets from on channels they | ||||
|      * are listening to. | ||||
|      * | ||||
|      * @return This packet's channel. | ||||
|      */ | ||||
|     public int getChannel() | ||||
|     { | ||||
|         return channel; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * The channel to reply on. Objects which will reply should send it along this channel. | ||||
|      * | ||||
|      * @return This channel to reply on. | ||||
|      */ | ||||
|     public int getReplyChannel() | ||||
|     { | ||||
|         return replyChannel; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * The actual data of this packet. This should be a "valid" Lua object, safe for queuing as an | ||||
|      * event or returning from a peripheral call. | ||||
|      * | ||||
|      * @return The packet's payload | ||||
|      */ | ||||
|     @Nullable | ||||
|     public Object getPayload() | ||||
|     { | ||||
|         return payload; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * The object which sent this message. | ||||
|      * | ||||
|      * @return The sending object. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public IPacketSender getSender() | ||||
|     { | ||||
|         return sender; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean equals( Object o ) | ||||
|     { | ||||
|         if( this == o ) return true; | ||||
|         if( o == null || getClass() != o.getClass() ) return false; | ||||
|  | ||||
|         Packet packet = (Packet) o; | ||||
|  | ||||
|         if( channel != packet.channel ) return false; | ||||
|         if( replyChannel != packet.replyChannel ) return false; | ||||
|         if( !Objects.equals( payload, packet.payload ) ) return false; | ||||
|         return sender.equals( packet.sender ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public int hashCode() | ||||
|     { | ||||
|         int result; | ||||
|         result = channel; | ||||
|         result = 31 * result + replyChannel; | ||||
|         result = 31 * result + (payload != null ? payload.hashCode() : 0); | ||||
|         result = 31 * result + sender.hashCode(); | ||||
|         return result; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,34 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.network.wired; | ||||
|  | ||||
| import dan200.computercraft.api.ComputerCraftAPI; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * An object which may be part of a wired network. | ||||
|  * | ||||
|  * Elements should construct a node using {@link ComputerCraftAPI#createWiredNodeForElement(IWiredElement)}. This acts | ||||
|  * as a proxy for all network objects. Whilst the node may change networks, an element's node should remain constant | ||||
|  * for its lifespan. | ||||
|  * | ||||
|  * Elements are generally tied to a block or tile entity in world. In such as case, one should provide the | ||||
|  * {@link IWiredElement} capability for the appropriate sides. | ||||
|  */ | ||||
| public interface IWiredElement extends IWiredSender | ||||
| { | ||||
|     /** | ||||
|      * Called when objects on the network change. This may occur when network nodes are added or removed, or when | ||||
|      * peripherals change. | ||||
|      * | ||||
|      * @param change The change which occurred. | ||||
|      * @see IWiredNetworkChange | ||||
|      */ | ||||
|     default void networkChanged( @Nonnull IWiredNetworkChange change ) | ||||
|     { | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,85 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.network.wired; | ||||
|  | ||||
| import dan200.computercraft.api.peripheral.IPeripheral; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.Map; | ||||
|  | ||||
| /** | ||||
|  * A wired network is composed of one of more {@link IWiredNode}s, a set of connections between them, and a series | ||||
|  * of peripherals. | ||||
|  * | ||||
|  * Networks from a connected graph. This means there is some path between all nodes on the network. Further more, if | ||||
|  * there is some path between two nodes then they must be on the same network. {@link IWiredNetwork} will automatically | ||||
|  * handle the merging and splitting of networks (and thus changing of available nodes and peripherals) as connections | ||||
|  * change. | ||||
|  * | ||||
|  * This does mean one can not rely on the network remaining consistent between subsequent operations. Consequently, | ||||
|  * it is generally preferred to use the methods provided by {@link IWiredNode}. | ||||
|  * | ||||
|  * @see IWiredNode#getNetwork() | ||||
|  */ | ||||
| public interface IWiredNetwork | ||||
| { | ||||
|     /** | ||||
|      * Create a connection between two nodes. | ||||
|      * | ||||
|      * This should only be used on the server thread. | ||||
|      * | ||||
|      * @param left  The first node to connect | ||||
|      * @param right The second node to connect | ||||
|      * @return {@code true} if a connection was created or {@code false} if the connection already exists. | ||||
|      * @throws IllegalStateException    If neither node is on the network. | ||||
|      * @throws IllegalArgumentException If {@code left} and {@code right} are equal. | ||||
|      * @see IWiredNode#connectTo(IWiredNode) | ||||
|      * @see IWiredNetwork#connect(IWiredNode, IWiredNode) | ||||
|      */ | ||||
|     boolean connect( @Nonnull IWiredNode left, @Nonnull IWiredNode right ); | ||||
|  | ||||
|     /** | ||||
|      * Destroy a connection between this node and another. | ||||
|      * | ||||
|      * This should only be used on the server thread. | ||||
|      * | ||||
|      * @param left  The first node in the connection. | ||||
|      * @param right The second node in the connection. | ||||
|      * @return {@code true} if a connection was destroyed or {@code false} if no connection exists. | ||||
|      * @throws IllegalArgumentException If either node is not on the network. | ||||
|      * @throws IllegalArgumentException If {@code left} and {@code right} are equal. | ||||
|      * @see IWiredNode#disconnectFrom(IWiredNode) | ||||
|      * @see IWiredNetwork#connect(IWiredNode, IWiredNode) | ||||
|      */ | ||||
|     boolean disconnect( @Nonnull IWiredNode left, @Nonnull IWiredNode right ); | ||||
|  | ||||
|     /** | ||||
|      * Sever all connections this node has, removing it from this network. | ||||
|      * | ||||
|      * This should only be used on the server thread. You should only call this on nodes | ||||
|      * that your network element owns. | ||||
|      * | ||||
|      * @param node The node to remove | ||||
|      * @return Whether this node was removed from the network. One cannot remove a node from a network where it is the | ||||
|      * only element. | ||||
|      * @throws IllegalArgumentException If the node is not in the network. | ||||
|      * @see IWiredNode#remove() | ||||
|      */ | ||||
|     boolean remove( @Nonnull IWiredNode node ); | ||||
|  | ||||
|     /** | ||||
|      * Update the peripherals a node provides. | ||||
|      * | ||||
|      * This should only be used on the server thread. You should only call this on nodes | ||||
|      * that your network element owns. | ||||
|      * | ||||
|      * @param node        The node to attach peripherals for. | ||||
|      * @param peripherals The new peripherals for this node. | ||||
|      * @throws IllegalArgumentException If the node is not in the network. | ||||
|      * @see IWiredNode#updatePeripherals(Map) | ||||
|      */ | ||||
|     void updatePeripherals( @Nonnull IWiredNode node, @Nonnull Map<String, IPeripheral> peripherals ); | ||||
| } | ||||
| @@ -0,0 +1,37 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.network.wired; | ||||
|  | ||||
| import dan200.computercraft.api.peripheral.IPeripheral; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.Map; | ||||
|  | ||||
| /** | ||||
|  * Represents a change to the objects on a wired network. | ||||
|  * | ||||
|  * @see IWiredElement#networkChanged(IWiredNetworkChange) | ||||
|  */ | ||||
| public interface IWiredNetworkChange | ||||
| { | ||||
|     /** | ||||
|      * A set of peripherals which have been removed. Note that there may be entries with the same name | ||||
|      * in the added and removed set, but with a different peripheral. | ||||
|      * | ||||
|      * @return The set of removed peripherals. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     Map<String, IPeripheral> peripheralsRemoved(); | ||||
|  | ||||
|     /** | ||||
|      * A set of peripherals which have been added. Note that there may be entries with the same name | ||||
|      * in the added and removed set, but with a different peripheral. | ||||
|      * | ||||
|      * @return The set of added peripherals. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     Map<String, IPeripheral> peripheralsAdded(); | ||||
| } | ||||
| @@ -0,0 +1,108 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.network.wired; | ||||
|  | ||||
| import dan200.computercraft.api.network.IPacketNetwork; | ||||
| import dan200.computercraft.api.peripheral.IPeripheral; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.Map; | ||||
|  | ||||
| /** | ||||
|  * Wired nodes act as a layer between {@link IWiredElement}s and {@link IWiredNetwork}s. | ||||
|  * | ||||
|  * Firstly, a node acts as a packet network, capable of sending and receiving modem messages to connected nodes. These | ||||
|  * methods may be safely used on any thread. | ||||
|  * | ||||
|  * When sending a packet, the system will attempt to find the shortest path between the two nodes based on their | ||||
|  * element's position. Note that packet senders and receivers can have different locations from their associated | ||||
|  * element: the distance between the two will be added to the total packet's distance. | ||||
|  * | ||||
|  * Wired nodes also provide several convenience methods for interacting with a wired network. These should only ever | ||||
|  * be used on the main server thread. | ||||
|  */ | ||||
| public interface IWiredNode extends IPacketNetwork | ||||
| { | ||||
|     /** | ||||
|      * The associated element for this network node. | ||||
|      * | ||||
|      * @return This node's element. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     IWiredElement getElement(); | ||||
|  | ||||
|     /** | ||||
|      * The network this node is currently connected to. Note that this may change | ||||
|      * after any network operation, so it should not be cached. | ||||
|      * | ||||
|      * This should only be used on the server thread. | ||||
|      * | ||||
|      * @return This node's network. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     IWiredNetwork getNetwork(); | ||||
|  | ||||
|     /** | ||||
|      * Create a connection from this node to another. | ||||
|      * | ||||
|      * This should only be used on the server thread. | ||||
|      * | ||||
|      * @param node The other node to connect to. | ||||
|      * @return {@code true} if a connection was created or {@code false} if the connection already exists. | ||||
|      * @see IWiredNetwork#connect(IWiredNode, IWiredNode) | ||||
|      * @see IWiredNode#disconnectFrom(IWiredNode) | ||||
|      */ | ||||
|     default boolean connectTo( @Nonnull IWiredNode node ) | ||||
|     { | ||||
|         return getNetwork().connect( this, node ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Destroy a connection between this node and another. | ||||
|      * | ||||
|      * This should only be used on the server thread. | ||||
|      * | ||||
|      * @param node The other node to disconnect from. | ||||
|      * @return {@code true} if a connection was destroyed or {@code false} if no connection exists. | ||||
|      * @throws IllegalArgumentException If {@code node} is not on the same network. | ||||
|      * @see IWiredNetwork#disconnect(IWiredNode, IWiredNode) | ||||
|      * @see IWiredNode#connectTo(IWiredNode) | ||||
|      */ | ||||
|     default boolean disconnectFrom( @Nonnull IWiredNode node ) | ||||
|     { | ||||
|         return getNetwork().disconnect( this, node ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Sever all connections this node has, removing it from this network. | ||||
|      * | ||||
|      * This should only be used on the server thread. You should only call this on nodes | ||||
|      * that your network element owns. | ||||
|      * | ||||
|      * @return Whether this node was removed from the network. One cannot remove a node from a network where it is the | ||||
|      * only element. | ||||
|      * @throws IllegalArgumentException If the node is not in the network. | ||||
|      * @see IWiredNetwork#remove(IWiredNode) | ||||
|      */ | ||||
|     default boolean remove() | ||||
|     { | ||||
|         return getNetwork().remove( this ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Mark this node's peripherals as having changed. | ||||
|      * | ||||
|      * This should only be used on the server thread. You should only call this on nodes | ||||
|      * that your network element owns. | ||||
|      * | ||||
|      * @param peripherals The new peripherals for this node. | ||||
|      * @see IWiredNetwork#updatePeripherals(IWiredNode, Map) | ||||
|      */ | ||||
|     default void updatePeripherals( @Nonnull Map<String, IPeripheral> peripherals ) | ||||
|     { | ||||
|         getNetwork().updatePeripherals( this, peripherals ); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,30 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.network.wired; | ||||
|  | ||||
| import dan200.computercraft.api.network.IPacketSender; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * An object on a {@link IWiredNetwork} capable of sending packets. | ||||
|  * | ||||
|  * Unlike a regular {@link IPacketSender}, this must be associated with the node you are attempting to | ||||
|  * to send the packet from. | ||||
|  */ | ||||
| public interface IWiredSender extends IPacketSender | ||||
| { | ||||
|     /** | ||||
|      * The node in the network representing this object. | ||||
|      * | ||||
|      * This should be used as a proxy for the main network. One should send packets | ||||
|      * and register receivers through this object. | ||||
|      * | ||||
|      * @return The node for this element. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     IWiredNode getNode(); | ||||
| } | ||||
| @@ -0,0 +1,208 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.peripheral; | ||||
|  | ||||
| import dan200.computercraft.api.ComputerCraftAPI; | ||||
| import dan200.computercraft.api.filesystem.IMount; | ||||
| import dan200.computercraft.api.filesystem.IWritableMount; | ||||
| import dan200.computercraft.api.lua.ILuaCallback; | ||||
| import dan200.computercraft.api.lua.ILuaContext; | ||||
| import dan200.computercraft.api.lua.ILuaTask; | ||||
| import dan200.computercraft.api.lua.MethodResult; | ||||
| import net.minecraft.world.World; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.util.Map; | ||||
|  | ||||
| /** | ||||
|  * The interface passed to peripherals by computers or turtles, providing methods | ||||
|  * that they can call. This should not be implemented by your classes. Do not interact | ||||
|  * with computers except via this interface. | ||||
|  */ | ||||
| public interface IComputerAccess | ||||
| { | ||||
|     /** | ||||
|      * Mount a mount onto the computer's file system in a read only mode. | ||||
|      * | ||||
|      * @param desiredLocation The location on the computer's file system where you would like the mount to be mounted. | ||||
|      * @param mount           The mount object to mount on the computer. | ||||
|      * @return The location on the computer's file system where you the mount mounted, or {@code null} if there was already a | ||||
|      * file in the desired location. Store this value if you wish to unmount the mount later. | ||||
|      * @throws NotAttachedException If the peripheral has been detached. | ||||
|      * @see ComputerCraftAPI#createSaveDirMount(World, String, long) | ||||
|      * @see ComputerCraftAPI#createResourceMount(String, String) | ||||
|      * @see #mount(String, IMount, String) | ||||
|      * @see #mountWritable(String, IWritableMount) | ||||
|      * @see #unmount(String) | ||||
|      * @see IMount | ||||
|      */ | ||||
|     @Nullable | ||||
|     default String mount( @Nonnull String desiredLocation, @Nonnull IMount mount ) | ||||
|     { | ||||
|         return mount( desiredLocation, mount, getAttachmentName() ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Mount a mount onto the computer's file system in a read only mode. | ||||
|      * | ||||
|      * @param desiredLocation The location on the computer's file system where you would like the mount to be mounted. | ||||
|      * @param mount           The mount object to mount on the computer. | ||||
|      * @param driveName       A custom name to give for this mount location, as returned by {@code fs.getDrive()}. | ||||
|      * @return The location on the computer's file system where you the mount mounted, or {@code null} if there was already a | ||||
|      * file in the desired location. Store this value if you wish to unmount the mount later. | ||||
|      * @throws NotAttachedException If the peripheral has been detached. | ||||
|      * @see ComputerCraftAPI#createSaveDirMount(World, String, long) | ||||
|      * @see ComputerCraftAPI#createResourceMount(String, String) | ||||
|      * @see #mount(String, IMount) | ||||
|      * @see #mountWritable(String, IWritableMount) | ||||
|      * @see #unmount(String) | ||||
|      * @see IMount | ||||
|      */ | ||||
|     @Nullable | ||||
|     String mount( @Nonnull String desiredLocation, @Nonnull IMount mount, @Nonnull String driveName ); | ||||
|  | ||||
|     /** | ||||
|      * Mount a mount onto the computer's file system in a writable mode. | ||||
|      * | ||||
|      * @param desiredLocation The location on the computer's file system where you would like the mount to be mounted. | ||||
|      * @param mount           The mount object to mount on the computer. | ||||
|      * @return The location on the computer's file system where you the mount mounted, or null if there was already a | ||||
|      * file in the desired location. Store this value if you wish to unmount the mount later. | ||||
|      * @throws NotAttachedException If the peripheral has been detached. | ||||
|      * @see ComputerCraftAPI#createSaveDirMount(World, String, long) | ||||
|      * @see ComputerCraftAPI#createResourceMount(String, String) | ||||
|      * @see #mount(String, IMount) | ||||
|      * @see #unmount(String) | ||||
|      * @see IMount | ||||
|      */ | ||||
|     @Nullable | ||||
|     default String mountWritable( @Nonnull String desiredLocation, @Nonnull IWritableMount mount ) | ||||
|     { | ||||
|         return mountWritable( desiredLocation, mount, getAttachmentName() ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Mount a mount onto the computer's file system in a writable mode. | ||||
|      * | ||||
|      * @param desiredLocation The location on the computer's file system where you would like the mount to be mounted. | ||||
|      * @param mount           The mount object to mount on the computer. | ||||
|      * @param driveName       A custom name to give for this mount location, as returned by {@code fs.getDrive()}. | ||||
|      * @return The location on the computer's file system where you the mount mounted, or null if there was already a | ||||
|      * file in the desired location. Store this value if you wish to unmount the mount later. | ||||
|      * @throws NotAttachedException If the peripheral has been detached. | ||||
|      * @see ComputerCraftAPI#createSaveDirMount(World, String, long) | ||||
|      * @see ComputerCraftAPI#createResourceMount(String, String) | ||||
|      * @see #mount(String, IMount) | ||||
|      * @see #unmount(String) | ||||
|      * @see IMount | ||||
|      */ | ||||
|     String mountWritable( @Nonnull String desiredLocation, @Nonnull IWritableMount mount, @Nonnull String driveName ); | ||||
|  | ||||
|     /** | ||||
|      * Unmounts a directory previously mounted onto the computers file system by {@link #mount(String, IMount)} | ||||
|      * or {@link #mountWritable(String, IWritableMount)}. | ||||
|      * | ||||
|      * When a directory is unmounted, it will disappear from the computers file system, and the user will no longer be | ||||
|      * able to access it. All directories mounted by a mount or mountWritable are automatically unmounted when the | ||||
|      * peripheral is attached if they have not been explicitly unmounted. | ||||
|      * | ||||
|      * Note that you cannot unmount another peripheral's mounts. | ||||
|      * | ||||
|      * @param location The desired location in the computers file system of the directory to unmount. | ||||
|      *                 This must be the location of a directory previously mounted by {@link #mount(String, IMount)} or | ||||
|      *                 {@link #mountWritable(String, IWritableMount)}, as indicated by their return value. | ||||
|      * @throws NotAttachedException  If the peripheral has been detached. | ||||
|      * @throws IllegalStateException If the mount does not exist, or was mounted by another peripheral. | ||||
|      * @see #mount(String, IMount) | ||||
|      * @see #mountWritable(String, IWritableMount) | ||||
|      */ | ||||
|     void unmount( @Nullable String location ); | ||||
|  | ||||
|     /** | ||||
|      * Returns the numerical ID of this computer. | ||||
|      * | ||||
|      * This is the same number obtained by calling {@code os.getComputerID()} or running the "id" program from lua, | ||||
|      * and is guaranteed unique. This number will be positive. | ||||
|      * | ||||
|      * @return The identifier. | ||||
|      */ | ||||
|     int getID(); | ||||
|  | ||||
|     /** | ||||
|      * Causes an event to be raised on this computer, which the computer can respond to by calling | ||||
|      * {@code os.pullEvent()}. This can be used to notify the computer when things happen in the world or to | ||||
|      * this peripheral. | ||||
|      * | ||||
|      * @param event     A string identifying the type of event that has occurred, this will be | ||||
|      *                  returned as the first value from {@code os.pullEvent()}. It is recommended that you | ||||
|      *                  you choose a name that is unique, and recognisable as originating from your | ||||
|      *                  peripheral. eg: If your peripheral type is "button", a suitable event would be | ||||
|      *                  "button_pressed". | ||||
|      * @param arguments In addition to a name, you may pass an array of extra arguments to the event, that will | ||||
|      *                  be supplied as extra return values to os.pullEvent(). Objects in the array will be converted | ||||
|      *                  to lua data types in the same fashion as the return values of IPeripheral.callMethod(). | ||||
|      * | ||||
|      *                  You may supply {@code null} to indicate that no arguments are to be supplied. | ||||
|      * @throws NotAttachedException If the peripheral has been detached. | ||||
|      * @see MethodResult#pullEvent(String, ILuaCallback) | ||||
|      */ | ||||
|     void queueEvent( @Nonnull String event, @Nullable Object... arguments ); | ||||
|  | ||||
|     /** | ||||
|      * Get a string, unique to the computer, by which the computer refers to this peripheral. | ||||
|      * For directly attached peripherals this will be "left","right","front","back",etc, but | ||||
|      * for peripherals attached remotely it will be different. It is good practice to supply | ||||
|      * this string when raising events to the computer, so that the computer knows from | ||||
|      * which peripheral the event came. | ||||
|      * | ||||
|      * @return A string unique to the computer, but not globally. | ||||
|      * @throws NotAttachedException If the peripheral has been detached. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     String getAttachmentName(); | ||||
|  | ||||
|     /** | ||||
|      * Get a set of peripherals that this computer access can "see", along with their attachment name. | ||||
|      * | ||||
|      * This may include other peripherals on the wired network or peripherals on other sides of the computer. | ||||
|      * | ||||
|      * @return All reachable peripherals | ||||
|      * @throws NotAttachedException If the peripheral has been detached. | ||||
|      * @see #getAttachmentName() | ||||
|      * @see #getAvailablePeripheral(String) | ||||
|      */ | ||||
|     @Nonnull | ||||
|     Map<String, IPeripheral> getAvailablePeripherals(); | ||||
|  | ||||
|     /** | ||||
|      * Get a reachable peripheral with the given attachment name. This is a equivalent to | ||||
|      * {@link #getAvailablePeripherals()}{@code .get(name)}, though may be more efficient. | ||||
|      * | ||||
|      * @param name The peripheral's attached name | ||||
|      * @return The reachable peripheral, or {@code null} if none can be found. | ||||
|      * @see #getAvailablePeripherals() | ||||
|      */ | ||||
|     @Nullable | ||||
|     IPeripheral getAvailablePeripheral( @Nonnull String name ); | ||||
|  | ||||
|     /** | ||||
|      * Get a {@link IWorkMonitor} for tasks your peripheral might execute on the main (server) thread. | ||||
|      * | ||||
|      * This should be used to ensure your peripheral integrates with ComputerCraft's monitoring and limiting of how much | ||||
|      * server time each computer consumes. You should not need to use this if you use | ||||
|      * {@link ILuaContext#issueMainThreadTask(ILuaTask)} - this is intended for mods with their own system for running | ||||
|      * work on the main thread. | ||||
|      * | ||||
|      * Please note that the returned implementation is <em>not</em> thread-safe, and should only be used from the main | ||||
|      * thread. | ||||
|      * | ||||
|      * @return The work monitor for the main thread, or {@code null} if this computer does not have one. | ||||
|      * @throws NotAttachedException If the peripheral has been detached. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     IWorkMonitor getMainThreadMonitor(); | ||||
| } | ||||
| @@ -0,0 +1,53 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.peripheral; | ||||
|  | ||||
| import dan200.computercraft.api.lua.*; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * A peripheral whose methods are not known at runtime. | ||||
|  * | ||||
|  * This behaves similarly to {@link IDynamicLuaObject}, though also accepting the current {@link IComputerAccess}. | ||||
|  * Generally one may use {@link LuaFunction} instead of implementing this interface. | ||||
|  */ | ||||
| public interface IDynamicPeripheral extends IPeripheral | ||||
| { | ||||
|     /** | ||||
|      * Should return an array of strings that identify the methods that this peripheral exposes to Lua. This will be | ||||
|      * called once before each attachment, and should not change when called multiple times. | ||||
|      * | ||||
|      * @return An array of strings representing method names. | ||||
|      * @see #callMethod | ||||
|      */ | ||||
|     @Nonnull | ||||
|     String[] getMethodNames(); | ||||
|  | ||||
|     /** | ||||
|      * This is called when a lua program on an attached computer calls {@code peripheral.call()} with | ||||
|      * one of the methods exposed by {@link #getMethodNames()}. | ||||
|      * | ||||
|      * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe when interacting | ||||
|      * with Minecraft objects. | ||||
|      * | ||||
|      * @param computer  The interface to the computer that is making the call. Remember that multiple | ||||
|      *                  computers can be attached to a peripheral at once. | ||||
|      * @param context   The context of the currently running lua thread. This can be used to wait for events | ||||
|      *                  or otherwise yield. | ||||
|      * @param method    An integer identifying which of the methods from getMethodNames() the computercraft | ||||
|      *                  wishes to call. The integer indicates the index into the getMethodNames() table | ||||
|      *                  that corresponds to the string passed into peripheral.call() | ||||
|      * @param arguments The arguments for this method. | ||||
|      * @return A {@link MethodResult} containing the values to return or the action to perform. | ||||
|      * @throws LuaException If you throw any exception from this function, a lua error will be raised with the | ||||
|      *                      same message as your exception. Use this to throw appropriate errors if the wrong | ||||
|      *                      arguments are supplied to your method. | ||||
|      * @see #getMethodNames() | ||||
|      */ | ||||
|     @Nonnull | ||||
|     MethodResult callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaContext context, int method, @Nonnull IArguments arguments ) throws LuaException; | ||||
| } | ||||
| @@ -0,0 +1,99 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.peripheral; | ||||
|  | ||||
| import dan200.computercraft.api.lua.LuaFunction; | ||||
| import net.minecraftforge.common.capabilities.Capability; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * The interface that defines a peripheral. | ||||
|  * | ||||
|  * In order to expose a peripheral for your block or tile entity, you may either attach a {@link Capability}, or | ||||
|  * register a {@link IPeripheralProvider}. This <em>cannot</em> be implemented {@link IPeripheral} directly on the tile. | ||||
|  * | ||||
|  * Peripherals should provide a series of methods to the user, either using {@link LuaFunction} or by implementing | ||||
|  * {@link IDynamicPeripheral}. | ||||
|  */ | ||||
| public interface IPeripheral | ||||
| { | ||||
|     /** | ||||
|      * Should return a string that uniquely identifies this type of peripheral. | ||||
|      * This can be queried from lua by calling {@code peripheral.getType()} | ||||
|      * | ||||
|      * @return A string identifying the type of peripheral. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     String getType(); | ||||
|  | ||||
|     /** | ||||
|      * Is called when when a computer is attaching to the peripheral. | ||||
|      * | ||||
|      * This will occur when a peripheral is placed next to an active computer, when a computer is turned on next to a | ||||
|      * peripheral, when a turtle travels into a square next to a peripheral, or when a wired modem adjacent to this | ||||
|      * peripheral is does any of the above. | ||||
|      * | ||||
|      * Between calls to attach and {@link #detach}, the attached computer can make method calls on the peripheral using | ||||
|      * {@code peripheral.call()}. This method can be used to keep track of which computers are attached to the | ||||
|      * peripheral, or to take action when attachment occurs. | ||||
|      * | ||||
|      * Be aware that will be called from both the server thread and ComputerCraft Lua thread, and so must be thread-safe | ||||
|      * and reentrant. | ||||
|      * | ||||
|      * @param computer The interface to the computer that is being attached. Remember that multiple computers can be | ||||
|      *                 attached to a peripheral at once. | ||||
|      * @see #detach | ||||
|      */ | ||||
|     default void attach( @Nonnull IComputerAccess computer ) | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Called when a computer is detaching from the peripheral. | ||||
|      * | ||||
|      * This will occur when a computer shuts down, when the peripheral is removed while attached to computers, when a | ||||
|      * turtle moves away from a block attached to a peripheral, or when a wired modem adjacent to this peripheral is | ||||
|      * detached. | ||||
|      * | ||||
|      * This method can be used to keep track of which computers are attached to the peripheral, or to take action when | ||||
|      * detachment occurs. | ||||
|      * | ||||
|      * Be aware that this will be called from both the server and ComputerCraft Lua thread, and must be thread-safe | ||||
|      * and reentrant. | ||||
|      * | ||||
|      * @param computer The interface to the computer that is being detached. Remember that multiple computers can be | ||||
|      *                 attached to a peripheral at once. | ||||
|      * @see #attach | ||||
|      */ | ||||
|     default void detach( @Nonnull IComputerAccess computer ) | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the object that this peripheral provides methods for. This will generally be the tile entity | ||||
|      * or block, but may be an inventory, entity, etc... | ||||
|      * | ||||
|      * @return The object this peripheral targets | ||||
|      */ | ||||
|     @Nullable | ||||
|     default Object getTarget() | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Determine whether this peripheral is equivalent to another one. | ||||
|      * | ||||
|      * The minimal example should at least check whether they are the same object. However, you may wish to check if | ||||
|      * they point to the same block or tile entity. | ||||
|      * | ||||
|      * @param other The peripheral to compare against. This may be {@code null}. | ||||
|      * @return Whether these peripherals are equivalent. | ||||
|      */ | ||||
|     boolean equals( @Nullable IPeripheral other ); | ||||
| } | ||||
| @@ -0,0 +1,37 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.peripheral; | ||||
|  | ||||
| import net.minecraft.util.math.BlockPos; | ||||
| import net.minecraft.util.math.Direction; | ||||
| import net.minecraft.world.World; | ||||
| import net.minecraftforge.common.util.LazyOptional; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * This interface is used to create peripheral implementations for blocks. | ||||
|  * | ||||
|  * If you have a {@link TileEntity} which acts as a peripheral, you may alternatively expose the {@link IPeripheral} | ||||
|  * capability. | ||||
|  * | ||||
|  * @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider) | ||||
|  */ | ||||
| @FunctionalInterface | ||||
| public interface IPeripheralProvider | ||||
| { | ||||
|     /** | ||||
|      * Produce an peripheral implementation from a block location. | ||||
|      * | ||||
|      * @param world The world the block is in. | ||||
|      * @param pos   The position the block is at. | ||||
|      * @param side  The side to get the peripheral from. | ||||
|      * @return A peripheral, or {@link LazyOptional#empty()} if there is not a peripheral here you'd like to handle. | ||||
|      * @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider) | ||||
|      */ | ||||
|     @Nonnull | ||||
|     LazyOptional<IPeripheral> getPeripheral( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ); | ||||
| } | ||||
| @@ -0,0 +1,77 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.peripheral; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.Objects; | ||||
| import java.util.concurrent.TimeUnit; | ||||
|  | ||||
| /** | ||||
|  * Monitors "work" associated with a computer, keeping track of how much a computer has done, and ensuring every | ||||
|  * computer receives a fair share of any processing time. | ||||
|  * | ||||
|  * This is primarily intended for work done by peripherals on the main thread (such as on a tile entity's tick), but | ||||
|  * could be used for other purposes (such as complex computations done on another thread). | ||||
|  * | ||||
|  * Before running a task, one should call {@link #canWork()} to determine if the computer is currently allowed to | ||||
|  * execute work. If that returns true, you should execute the task and use {@link #trackWork(long, TimeUnit)} to inform | ||||
|  * the monitor how long that task took. | ||||
|  * | ||||
|  * Alternatively, use {@link #runWork(Runnable)} to run and keep track of work. | ||||
|  * | ||||
|  * @see IComputerAccess#getMainThreadMonitor() | ||||
|  */ | ||||
| public interface IWorkMonitor | ||||
| { | ||||
|     /** | ||||
|      * If the owning computer is currently allowed to execute work. | ||||
|      * | ||||
|      * @return If we can execute work right now. | ||||
|      */ | ||||
|     boolean canWork(); | ||||
|  | ||||
|     /** | ||||
|      * If the owning computer is currently allowed to execute work, and has ample time to do so. | ||||
|      * | ||||
|      * This is effectively a more restrictive form of {@link #canWork()}. One should use that in order to determine if | ||||
|      * you may do an initial piece of work, and shouldWork to determine if any additional task may be performed. | ||||
|      * | ||||
|      * @return If we should execute work right now. | ||||
|      */ | ||||
|     boolean shouldWork(); | ||||
|  | ||||
|     /** | ||||
|      * Inform the monitor how long some piece of work took to execute. | ||||
|      * | ||||
|      * @param time The time some task took to run | ||||
|      * @param unit The unit that {@code time} was measured in. | ||||
|      */ | ||||
|     void trackWork( long time, @Nonnull TimeUnit unit ); | ||||
|  | ||||
|     /** | ||||
|      * Run a task if possible, and inform the monitor of how long it took. | ||||
|      * | ||||
|      * @param runnable The task to run. | ||||
|      * @return If the task was actually run (namely, {@link #canWork()} returned {@code true}). | ||||
|      */ | ||||
|     default boolean runWork( @Nonnull Runnable runnable ) | ||||
|     { | ||||
|         Objects.requireNonNull( runnable, "runnable should not be null" ); | ||||
|         if( !canWork() ) return false; | ||||
|  | ||||
|         long start = System.nanoTime(); | ||||
|         try | ||||
|         { | ||||
|             runnable.run(); | ||||
|         } | ||||
|         finally | ||||
|         { | ||||
|             trackWork( System.nanoTime() - start, TimeUnit.NANOSECONDS ); | ||||
|         } | ||||
|  | ||||
|         return true; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,25 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.peripheral; | ||||
|  | ||||
| /** | ||||
|  * Thrown when performing operations on {@link IComputerAccess} when the current peripheral is no longer attached to | ||||
|  * the computer. | ||||
|  */ | ||||
| public class NotAttachedException extends IllegalStateException | ||||
| { | ||||
|     private static final long serialVersionUID = 1221244785535553536L; | ||||
|  | ||||
|     public NotAttachedException() | ||||
|     { | ||||
|         super( "You are not attached to this computer" ); | ||||
|     } | ||||
|  | ||||
|     public NotAttachedException( String s ) | ||||
|     { | ||||
|         super( s ); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,117 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.pocket; | ||||
|  | ||||
| import net.minecraft.item.Item; | ||||
| import net.minecraft.item.ItemConvertible; | ||||
| import net.minecraft.item.ItemStack; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraft.util.Util; | ||||
| import net.minecraftforge.common.util.NonNullSupplier; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.function.Supplier; | ||||
|  | ||||
| /** | ||||
|  * A base class for {@link IPocketUpgrade}s. | ||||
|  * | ||||
|  * One does not have to use this, but it does provide a convenient template. | ||||
|  */ | ||||
| public abstract class AbstractPocketUpgrade implements IPocketUpgrade | ||||
| { | ||||
|     private final Identifier id; | ||||
|     private final String adjective; | ||||
|     private final NonNullSupplier<ItemStack> stack; | ||||
|  | ||||
|     protected AbstractPocketUpgrade( Identifier id, String adjective, NonNullSupplier<ItemStack> stack ) | ||||
|     { | ||||
|         this.id = id; | ||||
|         this.adjective = adjective; | ||||
|         this.stack = stack; | ||||
|     } | ||||
|  | ||||
|     protected AbstractPocketUpgrade( Identifier id, NonNullSupplier<ItemStack> item ) | ||||
|     { | ||||
|         this( id, Util.createTranslationKey( "upgrade", id ) + ".adjective", item ); | ||||
|     } | ||||
|  | ||||
|     protected AbstractPocketUpgrade( Identifier id, String adjective, ItemStack stack ) | ||||
|     { | ||||
|         this( id, adjective, () -> stack ); | ||||
|     } | ||||
|  | ||||
|     protected AbstractPocketUpgrade( Identifier id, ItemStack stack ) | ||||
|     { | ||||
|         this( id, () -> stack ); | ||||
|     } | ||||
|  | ||||
|     protected AbstractPocketUpgrade( Identifier id, String adjective, ItemConvertible item ) | ||||
|     { | ||||
|         this( id, adjective, new CachedStack( () -> item ) ); | ||||
|     } | ||||
|  | ||||
|     protected AbstractPocketUpgrade( Identifier id, ItemConvertible item ) | ||||
|     { | ||||
|         this( id, new CachedStack( () -> item ) ); | ||||
|     } | ||||
|  | ||||
|     protected AbstractPocketUpgrade( Identifier id, String adjective, Supplier<? extends ItemConvertible> item ) | ||||
|     { | ||||
|         this( id, adjective, new CachedStack( item ) ); | ||||
|     } | ||||
|  | ||||
|     protected AbstractPocketUpgrade( Identifier id, Supplier<? extends ItemConvertible> item ) | ||||
|     { | ||||
|         this( id, new CachedStack( item ) ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public final Identifier getUpgradeID() | ||||
|     { | ||||
|         return id; | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public final String getUnlocalisedAdjective() | ||||
|     { | ||||
|         return adjective; | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public final ItemStack getCraftingItem() | ||||
|     { | ||||
|         return stack.get(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Caches the construction of an item stack. | ||||
|      * | ||||
|      * @see dan200.computercraft.api.turtle.AbstractTurtleUpgrade For explanation of this class. | ||||
|      */ | ||||
|     private static final class CachedStack implements NonNullSupplier<ItemStack> | ||||
|     { | ||||
|         private final Supplier<? extends ItemConvertible> provider; | ||||
|         private Item item; | ||||
|         private ItemStack stack; | ||||
|  | ||||
|         CachedStack( Supplier<? extends ItemConvertible> provider ) | ||||
|         { | ||||
|             this.provider = provider; | ||||
|         } | ||||
|  | ||||
|         @Nonnull | ||||
|         @Override | ||||
|         public ItemStack get() | ||||
|         { | ||||
|             Item item = provider.get().asItem(); | ||||
|             if( item == this.item && stack != null ) return stack; | ||||
|             return stack = new ItemStack( this.item = item ); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,97 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.pocket; | ||||
|  | ||||
| import dan200.computercraft.api.peripheral.IPeripheral; | ||||
| import net.minecraft.entity.Entity; | ||||
| import net.minecraft.nbt.CompoundTag; | ||||
| import net.minecraft.util.Identifier; | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.util.Map; | ||||
|  | ||||
| /** | ||||
|  * Wrapper class for pocket computers. | ||||
|  */ | ||||
| public interface IPocketAccess | ||||
| { | ||||
|     /** | ||||
|      * Gets the entity holding this item. | ||||
|      * | ||||
|      * This must be called on the server thread. | ||||
|      * | ||||
|      * @return The holding entity, or {@code null} if none exists. | ||||
|      */ | ||||
|     @Nullable | ||||
|     Entity getEntity(); | ||||
|  | ||||
|     /** | ||||
|      * Get the colour of this pocket computer as a RGB number. | ||||
|      * | ||||
|      * @return The colour this pocket computer is. This will be a RGB colour between {@code 0x000000} and | ||||
|      * {@code 0xFFFFFF} or -1 if it has no colour. | ||||
|      * @see #setColour(int) | ||||
|      */ | ||||
|     int getColour(); | ||||
|  | ||||
|     /** | ||||
|      * Set the colour of the pocket computer to a RGB number. | ||||
|      * | ||||
|      * @param colour The colour this pocket computer should be changed to. This should be a RGB colour between | ||||
|      *               {@code 0x000000} and {@code 0xFFFFFF} or -1 to reset to the default colour. | ||||
|      * @see #getColour() | ||||
|      */ | ||||
|     void setColour( int colour ); | ||||
|  | ||||
|     /** | ||||
|      * Get the colour of this pocket computer's light as a RGB number. | ||||
|      * | ||||
|      * @return The colour this light is. This will be a RGB colour between {@code 0x000000} and {@code 0xFFFFFF} or | ||||
|      * -1 if it has no colour. | ||||
|      * @see #setLight(int) | ||||
|      */ | ||||
|     int getLight(); | ||||
|  | ||||
|     /** | ||||
|      * Set the colour of the pocket computer's light to a RGB number. | ||||
|      * | ||||
|      * @param colour The colour this modem's light will be changed to. This should be a RGB colour between | ||||
|      *               {@code 0x000000} and {@code 0xFFFFFF} or -1 to reset to the default colour. | ||||
|      * @see #getLight() | ||||
|      */ | ||||
|     void setLight( int colour ); | ||||
|  | ||||
|     /** | ||||
|      * Get the upgrade-specific NBT. | ||||
|      * | ||||
|      * This is persisted between computer reboots and chunk loads. | ||||
|      * | ||||
|      * @return The upgrade's NBT. | ||||
|      * @see #updateUpgradeNBTData() | ||||
|      */ | ||||
|     @Nonnull | ||||
|     CompoundTag getUpgradeNBTData(); | ||||
|  | ||||
|     /** | ||||
|      * Mark the upgrade-specific NBT as dirty. | ||||
|      * | ||||
|      * @see #getUpgradeNBTData() | ||||
|      */ | ||||
|     void updateUpgradeNBTData(); | ||||
|  | ||||
|     /** | ||||
|      * Remove the current peripheral and create a new one. You may wish to do this if the methods available change. | ||||
|      */ | ||||
|     void invalidatePeripheral(); | ||||
|  | ||||
|     /** | ||||
|      * Get a list of all upgrades for the pocket computer. | ||||
|      * | ||||
|      * @return A collection of all upgrade names. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     Map<Identifier, IPeripheral> getUpgrades(); | ||||
| } | ||||
| @@ -0,0 +1,104 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.pocket; | ||||
|  | ||||
| import dan200.computercraft.api.ComputerCraftAPI; | ||||
| import dan200.computercraft.api.peripheral.IPeripheral; | ||||
| import dan200.computercraft.api.turtle.ITurtleUpgrade; | ||||
| import net.minecraft.item.ItemStack; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraft.world.World; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * Additional peripherals for pocket computers. | ||||
|  * | ||||
|  * This is similar to {@link ITurtleUpgrade}. | ||||
|  */ | ||||
| public interface IPocketUpgrade | ||||
| { | ||||
|  | ||||
|     /** | ||||
|      * Gets a unique identifier representing this type of turtle upgrade. eg: "computercraft:wireless_modem" or | ||||
|      * "my_mod:my_upgrade". | ||||
|      * | ||||
|      * You should use a unique resource domain to ensure this upgrade is uniquely identified. The upgrade will fail | ||||
|      * registration if an already used ID is specified. | ||||
|      * | ||||
|      * @return The upgrade's id. | ||||
|      * @see IPocketUpgrade#getUpgradeID() | ||||
|      * @see ComputerCraftAPI#registerPocketUpgrade(IPocketUpgrade) | ||||
|      */ | ||||
|     @Nonnull | ||||
|     Identifier getUpgradeID(); | ||||
|  | ||||
|     /** | ||||
|      * Return an unlocalised string to describe the type of pocket computer this upgrade provides. | ||||
|      * | ||||
|      * An example of a built-in adjectives is "Wireless" - this is converted to "Wireless Pocket Computer". | ||||
|      * | ||||
|      * @return The unlocalised adjective. | ||||
|      * @see ITurtleUpgrade#getUnlocalisedAdjective() | ||||
|      */ | ||||
|     @Nonnull | ||||
|     String getUnlocalisedAdjective(); | ||||
|  | ||||
|     /** | ||||
|      * Return an item stack representing the type of item that a pocket computer must be crafted with to create a | ||||
|      * pocket computer which holds this upgrade. This item stack is also used to determine the upgrade given by | ||||
|      * {@code pocket.equip()}/{@code pocket.unequip()}. | ||||
|      * | ||||
|      * Ideally this should be constant over a session. It is recommended that you cache | ||||
|      * the item too, in order to prevent constructing it every time the method is called. | ||||
|      * | ||||
|      * @return The item stack used for crafting. This can be {@link ItemStack#EMPTY} if crafting is disabled. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     ItemStack getCraftingItem(); | ||||
|  | ||||
|     /** | ||||
|      * Creates a peripheral for the pocket computer. | ||||
|      * | ||||
|      * The peripheral created will be stored for the lifetime of the upgrade, will be passed an argument to | ||||
|      * {@link #update(IPocketAccess, IPeripheral)} and will be attached, detached and have methods called in the same | ||||
|      * manner as an ordinary peripheral. | ||||
|      * | ||||
|      * @param access The access object for the pocket item stack. | ||||
|      * @return The newly created peripheral. | ||||
|      * @see #update(IPocketAccess, IPeripheral) | ||||
|      */ | ||||
|     @Nullable | ||||
|     IPeripheral createPeripheral( @Nonnull IPocketAccess access ); | ||||
|  | ||||
|     /** | ||||
|      * Called when the pocket computer item stack updates. | ||||
|      * | ||||
|      * @param access     The access object for the pocket item stack. | ||||
|      * @param peripheral The peripheral for this upgrade. | ||||
|      * @see #createPeripheral(IPocketAccess) | ||||
|      */ | ||||
|     default void update( @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral ) | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Called when the pocket computer is right clicked. | ||||
|      * | ||||
|      * @param world      The world the computer is in. | ||||
|      * @param access     The access object for the pocket item stack. | ||||
|      * @param peripheral The peripheral for this upgrade. | ||||
|      * @return {@code true} to stop the GUI from opening, otherwise false. You should always provide some code path | ||||
|      * which returns {@code false}, such as requiring the player to be sneaking - otherwise they will be unable to | ||||
|      * access the GUI. | ||||
|      * @see #createPeripheral(IPocketAccess) | ||||
|      */ | ||||
|     default boolean onRightClick( @Nonnull World world, @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral ) | ||||
|     { | ||||
|         return false; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,33 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.redstone; | ||||
|  | ||||
| import net.minecraft.util.math.BlockPos; | ||||
| import net.minecraft.util.math.Direction; | ||||
| import net.minecraft.world.World; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * This interface is used to provide bundled redstone output for blocks. | ||||
|  * | ||||
|  * @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider) | ||||
|  */ | ||||
| @FunctionalInterface | ||||
| public interface IBundledRedstoneProvider | ||||
| { | ||||
|     /** | ||||
|      * Produce an bundled redstone output from a block location. | ||||
|      * | ||||
|      * @param world The world this block is in. | ||||
|      * @param pos   The position this block is at. | ||||
|      * @param side  The side to extract the bundled redstone output from. | ||||
|      * @return A number in the range 0-65535 to indicate this block is providing output, or -1 if you do not wish to | ||||
|      * handle this block. | ||||
|      * @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider) | ||||
|      */ | ||||
|     int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ); | ||||
| } | ||||
| @@ -0,0 +1,126 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle; | ||||
|  | ||||
| import net.minecraft.item.Item; | ||||
| import net.minecraft.item.ItemConvertible; | ||||
| import net.minecraft.item.ItemStack; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraft.util.Util; | ||||
| import net.minecraftforge.common.util.NonNullSupplier; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.function.Supplier; | ||||
|  | ||||
| /** | ||||
|  * A base class for {@link ITurtleUpgrade}s. | ||||
|  * | ||||
|  * One does not have to use this, but it does provide a convenient template. | ||||
|  */ | ||||
| public abstract class AbstractTurtleUpgrade implements ITurtleUpgrade | ||||
| { | ||||
|     private final Identifier id; | ||||
|     private final TurtleUpgradeType type; | ||||
|     private final String adjective; | ||||
|     private final NonNullSupplier<ItemStack> stack; | ||||
|  | ||||
|     protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, String adjective, NonNullSupplier<ItemStack> stack ) | ||||
|     { | ||||
|         this.id = id; | ||||
|         this.type = type; | ||||
|         this.adjective = adjective; | ||||
|         this.stack = stack; | ||||
|     } | ||||
|  | ||||
|     protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, NonNullSupplier<ItemStack> stack ) | ||||
|     { | ||||
|         this( id, type, Util.createTranslationKey( "upgrade", id ) + ".adjective", stack ); | ||||
|     } | ||||
|  | ||||
|     protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, String adjective, ItemStack stack ) | ||||
|     { | ||||
|         this( id, type, adjective, () -> stack ); | ||||
|     } | ||||
|  | ||||
|     protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, ItemStack stack ) | ||||
|     { | ||||
|         this( id, type, () -> stack ); | ||||
|     } | ||||
|  | ||||
|     protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, String adjective, ItemConvertible item ) | ||||
|     { | ||||
|         this( id, type, adjective, new CachedStack( () -> item ) ); | ||||
|     } | ||||
|  | ||||
|     protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, ItemConvertible item ) | ||||
|     { | ||||
|         this( id, type, new CachedStack( () -> item ) ); | ||||
|     } | ||||
|  | ||||
|     protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, String adjective, Supplier<? extends ItemConvertible> item ) | ||||
|     { | ||||
|         this( id, type, adjective, new CachedStack( item ) ); | ||||
|     } | ||||
|  | ||||
|     protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, Supplier<? extends ItemConvertible> item ) | ||||
|     { | ||||
|         this( id, type, new CachedStack( item ) ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public final Identifier getUpgradeID() | ||||
|     { | ||||
|         return id; | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public final String getUnlocalisedAdjective() | ||||
|     { | ||||
|         return adjective; | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public final TurtleUpgradeType getType() | ||||
|     { | ||||
|         return type; | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public final ItemStack getCraftingItem() | ||||
|     { | ||||
|         return stack.get(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * A supplier which converts an item into an item stack. | ||||
|      * | ||||
|      * Constructing item stacks is somewhat expensive due to attaching capabilities. We cache it if given a consistent item. | ||||
|      */ | ||||
|     private static final class CachedStack implements NonNullSupplier<ItemStack> | ||||
|     { | ||||
|         private final Supplier<? extends ItemConvertible> provider; | ||||
|         private Item item; | ||||
|         private ItemStack stack; | ||||
|  | ||||
|         CachedStack( Supplier<? extends ItemConvertible> provider ) | ||||
|         { | ||||
|             this.provider = provider; | ||||
|         } | ||||
|  | ||||
|         @Nonnull | ||||
|         @Override | ||||
|         public ItemStack get() | ||||
|         { | ||||
|             Item item = provider.get().asItem(); | ||||
|             if( item == this.item && stack != null ) return stack; | ||||
|             return stack = new ItemStack( this.item = item ); | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										300
									
								
								src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										300
									
								
								src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,300 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle; | ||||
|  | ||||
| import com.mojang.authlib.GameProfile; | ||||
| import dan200.computercraft.api.lua.ILuaCallback; | ||||
| import dan200.computercraft.api.lua.MethodResult; | ||||
| import dan200.computercraft.api.peripheral.IPeripheral; | ||||
| import net.minecraft.inventory.Inventory; | ||||
| import net.minecraft.nbt.CompoundTag; | ||||
| import net.minecraft.util.math.BlockPos; | ||||
| import net.minecraft.util.math.Direction; | ||||
| import net.minecraft.util.math.Vec3d; | ||||
| import net.minecraft.world.World; | ||||
| import net.minecraftforge.items.IItemHandlerModifiable; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * The interface passed to turtle by turtles, providing methods that they can call. | ||||
|  * | ||||
|  * This should not be implemented by your classes. Do not interact with turtles except via this interface and | ||||
|  * {@link ITurtleUpgrade}. | ||||
|  */ | ||||
| public interface ITurtleAccess | ||||
| { | ||||
|     /** | ||||
|      * Returns the world in which the turtle resides. | ||||
|      * | ||||
|      * @return the world in which the turtle resides. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     World getWorld(); | ||||
|  | ||||
|     /** | ||||
|      * Returns a vector containing the integer co-ordinates at which the turtle resides. | ||||
|      * | ||||
|      * @return a vector containing the integer co-ordinates at which the turtle resides. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     BlockPos getPosition(); | ||||
|  | ||||
|     /** | ||||
|      * Attempt to move this turtle to a new position. | ||||
|      * | ||||
|      * This will preserve the turtle's internal state, such as it's inventory, computer and upgrades. It should | ||||
|      * be used before playing a movement animation using {@link #playAnimation(TurtleAnimation)}. | ||||
|      * | ||||
|      * @param world The new world to move it to | ||||
|      * @param pos   The new position to move it to. | ||||
|      * @return Whether the movement was successful. It may fail if the block was not loaded or the block placement | ||||
|      * was cancelled. | ||||
|      * @throws UnsupportedOperationException When attempting to teleport on the client side. | ||||
|      */ | ||||
|     boolean teleportTo( @Nonnull World world, @Nonnull BlockPos pos ); | ||||
|  | ||||
|     /** | ||||
|      * Returns a vector containing the floating point co-ordinates at which the turtle is rendered. | ||||
|      * This will shift when the turtle is moving. | ||||
|      * | ||||
|      * @param f The subframe fraction. | ||||
|      * @return A vector containing the floating point co-ordinates at which the turtle resides. | ||||
|      * @see #getVisualYaw(float) | ||||
|      */ | ||||
|     @Nonnull | ||||
|     Vec3d getVisualPosition( float f ); | ||||
|  | ||||
|     /** | ||||
|      * Returns the yaw the turtle is facing when it is rendered. | ||||
|      * | ||||
|      * @param f The subframe fraction. | ||||
|      * @return The yaw the turtle is facing. | ||||
|      * @see #getVisualPosition(float) | ||||
|      */ | ||||
|     float getVisualYaw( float f ); | ||||
|  | ||||
|     /** | ||||
|      * Returns the world direction the turtle is currently facing. | ||||
|      * | ||||
|      * @return The world direction the turtle is currently facing. | ||||
|      * @see #setDirection(Direction) | ||||
|      */ | ||||
|     @Nonnull | ||||
|     Direction getDirection(); | ||||
|  | ||||
|     /** | ||||
|      * Set the direction the turtle is facing. Note that this will not play a rotation animation, you will also need to | ||||
|      * call {@link #playAnimation(TurtleAnimation)} to do so. | ||||
|      * | ||||
|      * @param dir The new direction to set. This should be on either the x or z axis (so north, south, east or west). | ||||
|      * @see #getDirection() | ||||
|      */ | ||||
|     void setDirection( @Nonnull Direction dir ); | ||||
|  | ||||
|     /** | ||||
|      * Get the currently selected slot in the turtle's inventory. | ||||
|      * | ||||
|      * @return An integer representing the current slot. | ||||
|      * @see #getInventory() | ||||
|      * @see #setSelectedSlot(int) | ||||
|      */ | ||||
|     int getSelectedSlot(); | ||||
|  | ||||
|     /** | ||||
|      * Set the currently selected slot in the turtle's inventory. | ||||
|      * | ||||
|      * @param slot The slot to set. This must be greater or equal to 0 and less than the inventory size. Otherwise no | ||||
|      *             action will be taken. | ||||
|      * @throws UnsupportedOperationException When attempting to change the slot on the client side. | ||||
|      * @see #getInventory() | ||||
|      * @see #getSelectedSlot() | ||||
|      */ | ||||
|     void setSelectedSlot( int slot ); | ||||
|  | ||||
|     /** | ||||
|      * Set the colour of the turtle to a RGB number. | ||||
|      * | ||||
|      * @param colour The colour this turtle should be changed to. This should be a RGB colour between {@code 0x000000} | ||||
|      *               and {@code 0xFFFFFF} or -1 to reset to the default colour. | ||||
|      * @see #getColour() | ||||
|      */ | ||||
|     void setColour( int colour ); | ||||
|  | ||||
|     /** | ||||
|      * Get the colour of this turtle as a RGB number. | ||||
|      * | ||||
|      * @return The colour this turtle is. This will be a RGB colour between {@code 0x000000} and {@code 0xFFFFFF} or | ||||
|      * -1 if it has no colour. | ||||
|      * @see #setColour(int) | ||||
|      */ | ||||
|     int getColour(); | ||||
|  | ||||
|     /** | ||||
|      * Get the player who owns this turtle, namely whoever placed it. | ||||
|      * | ||||
|      * @return This turtle's owner. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     GameProfile getOwningPlayer(); | ||||
|  | ||||
|     /** | ||||
|      * Get the inventory of this turtle. | ||||
|      * | ||||
|      * Note: this inventory should only be accessed and modified on the server thread. | ||||
|      * | ||||
|      * @return This turtle's inventory | ||||
|      * @see #getItemHandler() | ||||
|      */ | ||||
|     @Nonnull | ||||
|     Inventory getInventory(); | ||||
|  | ||||
|     /** | ||||
|      * Get the inventory of this turtle as an {@link IItemHandlerModifiable}. | ||||
|      * | ||||
|      * Note: this inventory should only be accessed and modified on the server thread. | ||||
|      * | ||||
|      * @return This turtle's inventory | ||||
|      * @see #getInventory() | ||||
|      * @see IItemHandlerModifiable | ||||
|      * @see net.minecraftforge.items.CapabilityItemHandler#ITEM_HANDLER_CAPABILITY | ||||
|      */ | ||||
|     @Nonnull | ||||
|     IItemHandlerModifiable getItemHandler(); | ||||
|  | ||||
|     /** | ||||
|      * Determine whether this turtle will require fuel when performing actions. | ||||
|      * | ||||
|      * @return Whether this turtle needs fuel. | ||||
|      * @see #getFuelLevel() | ||||
|      * @see #setFuelLevel(int) | ||||
|      */ | ||||
|     boolean isFuelNeeded(); | ||||
|  | ||||
|     /** | ||||
|      * Get the current fuel level of this turtle. | ||||
|      * | ||||
|      * @return The turtle's current fuel level. | ||||
|      * @see #isFuelNeeded() | ||||
|      * @see #setFuelLevel(int) | ||||
|      */ | ||||
|     int getFuelLevel(); | ||||
|  | ||||
|     /** | ||||
|      * Set the fuel level to a new value. It is generally preferred to use {@link #consumeFuel(int)}} or {@link #addFuel(int)} | ||||
|      * instead. | ||||
|      * | ||||
|      * @param fuel The new amount of fuel. This must be between 0 and the fuel limit. | ||||
|      * @see #getFuelLevel() | ||||
|      * @see #getFuelLimit() | ||||
|      * @see #addFuel(int) | ||||
|      * @see #consumeFuel(int) | ||||
|      */ | ||||
|     void setFuelLevel( int fuel ); | ||||
|  | ||||
|     /** | ||||
|      * Get the maximum amount of fuel a turtle can hold. | ||||
|      * | ||||
|      * @return The turtle's fuel limit. | ||||
|      */ | ||||
|     int getFuelLimit(); | ||||
|  | ||||
|     /** | ||||
|      * Removes some fuel from the turtles fuel supply. Negative numbers can be passed in to INCREASE the fuel level of the turtle. | ||||
|      * | ||||
|      * @param fuel The amount of fuel to consume. | ||||
|      * @return Whether the turtle was able to consume the amount of fuel specified. Will return false if you supply a number | ||||
|      * greater than the current fuel level of the turtle. No fuel will be consumed if {@code false} is returned. | ||||
|      * @throws UnsupportedOperationException When attempting to consume fuel on the client side. | ||||
|      */ | ||||
|     boolean consumeFuel( int fuel ); | ||||
|  | ||||
|     /** | ||||
|      * Increase the turtle's fuel level by the given amount. | ||||
|      * | ||||
|      * @param fuel The amount to refuel with. | ||||
|      * @throws UnsupportedOperationException When attempting to refuel on the client side. | ||||
|      */ | ||||
|     void addFuel( int fuel ); | ||||
|  | ||||
|     /** | ||||
|      * Adds a custom command to the turtles command queue. Unlike peripheral methods, these custom commands will be executed | ||||
|      * on the main thread, so are guaranteed to be able to access Minecraft objects safely, and will be queued up | ||||
|      * with the turtles standard movement and tool commands. An issued command will return an unique integer, which will | ||||
|      * be supplied as a parameter to a "turtle_response" event issued to the turtle after the command has completed. Look at the | ||||
|      * lua source code for "rom/apis/turtle" for how to build a lua wrapper around this functionality. | ||||
|      * | ||||
|      * @param command An object which will execute the custom command when its point in the queue is reached | ||||
|      * @return The objects the command returned when executed. you should probably return these to the player | ||||
|      * unchanged if called from a peripheral method. | ||||
|      * @throws UnsupportedOperationException When attempting to execute a command on the client side. | ||||
|      * @see ITurtleCommand | ||||
|      * @see MethodResult#pullEvent(String, ILuaCallback) | ||||
|      */ | ||||
|     @Nonnull | ||||
|     MethodResult executeCommand( @Nonnull ITurtleCommand command ); | ||||
|  | ||||
|     /** | ||||
|      * Start playing a specific animation. This will prevent other turtle commands from executing until | ||||
|      * it is finished. | ||||
|      * | ||||
|      * @param animation The animation to play. | ||||
|      * @throws UnsupportedOperationException When attempting to execute play an animation on the client side. | ||||
|      * @see TurtleAnimation | ||||
|      */ | ||||
|     void playAnimation( @Nonnull TurtleAnimation animation ); | ||||
|  | ||||
|     /** | ||||
|      * Returns the turtle on the specified side of the turtle, if there is one. | ||||
|      * | ||||
|      * @param side The side to get the upgrade from. | ||||
|      * @return The upgrade on the specified side of the turtle, if there is one. | ||||
|      * @see #setUpgrade(TurtleSide, ITurtleUpgrade) | ||||
|      */ | ||||
|     @Nullable | ||||
|     ITurtleUpgrade getUpgrade( @Nonnull TurtleSide side ); | ||||
|  | ||||
|     /** | ||||
|      * Set the upgrade for a given side, resetting peripherals and clearing upgrade specific data. | ||||
|      * | ||||
|      * @param side    The side to set the upgrade on. | ||||
|      * @param upgrade The upgrade to set, may be {@code null} to clear. | ||||
|      * @see #getUpgrade(TurtleSide) | ||||
|      */ | ||||
|     void setUpgrade( @Nonnull TurtleSide side, @Nullable ITurtleUpgrade upgrade ); | ||||
|  | ||||
|     /** | ||||
|      * Returns the peripheral created by the upgrade on the specified side of the turtle, if there is one. | ||||
|      * | ||||
|      * @param side The side to get the peripheral from. | ||||
|      * @return The peripheral created by the upgrade on the specified side of the turtle, {@code null} if none exists. | ||||
|      */ | ||||
|     @Nullable | ||||
|     IPeripheral getPeripheral( @Nonnull TurtleSide side ); | ||||
|  | ||||
|     /** | ||||
|      * Get an upgrade-specific NBT compound, which can be used to store arbitrary data. | ||||
|      * | ||||
|      * This will be persisted across turtle restarts and chunk loads, as well as being synced to the client. You must | ||||
|      * call {@link #updateUpgradeNBTData(TurtleSide)} after modifying it. | ||||
|      * | ||||
|      * @param side The side to get the upgrade data for. | ||||
|      * @return The upgrade-specific data. | ||||
|      * @see #updateUpgradeNBTData(TurtleSide) | ||||
|      */ | ||||
|     @Nonnull | ||||
|     CompoundTag getUpgradeNBTData( @Nullable TurtleSide side ); | ||||
|  | ||||
|     /** | ||||
|      * Mark the upgrade-specific data as dirty on a specific side. This is required for the data to be synced to the | ||||
|      * client and persisted. | ||||
|      * | ||||
|      * @param side The side to mark dirty. | ||||
|      * @see #updateUpgradeNBTData(TurtleSide) | ||||
|      */ | ||||
|     void updateUpgradeNBTData( @Nonnull TurtleSide side ); | ||||
| } | ||||
| @@ -0,0 +1,33 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * An interface for objects executing custom turtle commands, used with {@link ITurtleAccess#executeCommand(ITurtleCommand)}. | ||||
|  * | ||||
|  * @see ITurtleAccess#executeCommand(ITurtleCommand) | ||||
|  */ | ||||
| @FunctionalInterface | ||||
| public interface ITurtleCommand | ||||
| { | ||||
|     /** | ||||
|      * Will be called by the turtle on the main thread when it is time to execute the custom command. | ||||
|      * | ||||
|      * The handler should either perform the work of the command, and return success, or return | ||||
|      * failure with an error message to indicate the command cannot be executed at this time. | ||||
|      * | ||||
|      * @param turtle Access to the turtle for whom the command was issued. | ||||
|      * @return A result, indicating whether this action succeeded or not. | ||||
|      * @see ITurtleAccess#executeCommand(ITurtleCommand) | ||||
|      * @see TurtleCommandResult#success() | ||||
|      * @see TurtleCommandResult#failure(String) | ||||
|      * @see TurtleCommandResult | ||||
|      */ | ||||
|     @Nonnull | ||||
|     TurtleCommandResult execute( @Nonnull ITurtleAccess turtle ); | ||||
| } | ||||
| @@ -0,0 +1,143 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle; | ||||
|  | ||||
| import dan200.computercraft.api.ComputerCraftAPI; | ||||
| import dan200.computercraft.api.client.TransformedModel; | ||||
| import dan200.computercraft.api.peripheral.IPeripheral; | ||||
| import dan200.computercraft.api.turtle.event.TurtleAttackEvent; | ||||
| import dan200.computercraft.api.turtle.event.TurtleBlockEvent; | ||||
| import net.fabricmc.api.EnvType; | ||||
| import net.fabricmc.api.Environment; | ||||
| import net.minecraft.item.ItemStack; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraft.util.math.Direction; | ||||
| import net.minecraftforge.api.distmarker.Dist; | ||||
| import net.minecraftforge.api.distmarker.OnlyIn; | ||||
| import net.minecraftforge.event.entity.player.AttackEntityEvent; | ||||
| import net.minecraftforge.event.world.BlockEvent; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * The primary interface for defining an update for Turtles. A turtle update | ||||
|  * can either be a new tool, or a new peripheral. | ||||
|  * | ||||
|  * @see ComputerCraftAPI#registerTurtleUpgrade(ITurtleUpgrade) | ||||
|  */ | ||||
| public interface ITurtleUpgrade | ||||
| { | ||||
|     /** | ||||
|      * Gets a unique identifier representing this type of turtle upgrade. eg: "computercraft:wireless_modem" or "my_mod:my_upgrade". | ||||
|      * You should use a unique resource domain to ensure this upgrade is uniquely identified. | ||||
|      * The turtle will fail registration if an already used ID is specified. | ||||
|      * | ||||
|      * @return The unique ID for this upgrade. | ||||
|      * @see ComputerCraftAPI#registerTurtleUpgrade(ITurtleUpgrade) | ||||
|      */ | ||||
|     @Nonnull | ||||
|     Identifier getUpgradeID(); | ||||
|  | ||||
|     /** | ||||
|      * Return an unlocalised string to describe this type of turtle in turtle item names. | ||||
|      * | ||||
|      * Examples of built-in adjectives are "Wireless", "Mining" and "Crafty". | ||||
|      * | ||||
|      * @return The localisation key for this upgrade's adjective. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     String getUnlocalisedAdjective(); | ||||
|  | ||||
|     /** | ||||
|      * Return whether this turtle adds a tool or a peripheral to the turtle. | ||||
|      * | ||||
|      * @return The type of upgrade this is. | ||||
|      * @see TurtleUpgradeType for the differences between them. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     TurtleUpgradeType getType(); | ||||
|  | ||||
|     /** | ||||
|      * Return an item stack representing the type of item that a turtle must be crafted | ||||
|      * with to create a turtle which holds this upgrade. This item stack is also used | ||||
|      * to determine the upgrade given by {@code turtle.equip()} | ||||
|      * | ||||
|      * Ideally this should be constant over a session. It is recommended that you cache | ||||
|      * the item too, in order to prevent constructing it every time the method is called. | ||||
|      * | ||||
|      * @return The item stack to craft with, or {@link ItemStack#EMPTY} if it cannot be crafted. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     ItemStack getCraftingItem(); | ||||
|  | ||||
|     /** | ||||
|      * Will only be called for peripheral upgrades. Creates a peripheral for a turtle being placed using this upgrade. | ||||
|      * | ||||
|      * The peripheral created will be stored for the lifetime of the upgrade and will be passed as an argument to | ||||
|      * {@link #update(ITurtleAccess, TurtleSide)}. It will be attached, detached and have methods called in the same | ||||
|      * manner as a Computer peripheral. | ||||
|      * | ||||
|      * @param turtle Access to the turtle that the peripheral is being created for. | ||||
|      * @param side   Which side of the turtle (left or right) that the upgrade resides on. | ||||
|      * @return The newly created peripheral. You may return {@code null} if this upgrade is a Tool | ||||
|      * and this method is not expected to be called. | ||||
|      */ | ||||
|     @Nullable | ||||
|     default IPeripheral createPeripheral( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side ) | ||||
|     { | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Will only be called for Tool turtle. Called when turtle.dig() or turtle.attack() is called | ||||
|      * by the turtle, and the tool is required to do some work. | ||||
|      * | ||||
|      * Conforming implementations should fire {@link BlockEvent.BreakEvent} and {@link TurtleBlockEvent.Dig} for | ||||
|      * digging, {@link AttackEntityEvent} and {@link TurtleAttackEvent} for attacking. | ||||
|      * | ||||
|      * @param turtle    Access to the turtle that the tool resides on. | ||||
|      * @param side      Which side of the turtle (left or right) the tool resides on. | ||||
|      * @param verb      Which action (dig or attack) the turtle is being called on to perform. | ||||
|      * @param direction Which world direction the action should be performed in, relative to the turtles | ||||
|      *                  position. This will either be up, down, or the direction the turtle is facing, depending on | ||||
|      *                  whether dig, digUp or digDown was called. | ||||
|      * @return Whether the turtle was able to perform the action, and hence whether the {@code turtle.dig()} | ||||
|      * or {@code turtle.attack()} lua method should return true. If true is returned, the tool will perform | ||||
|      * a swinging animation. You may return {@code null} if this turtle is a Peripheral  and this method is not expected | ||||
|      * to be called. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     default TurtleCommandResult useTool( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side, @Nonnull TurtleVerb verb, @Nonnull Direction direction ) | ||||
|     { | ||||
|         return TurtleCommandResult.failure(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Called to obtain the model to be used when rendering a turtle peripheral. | ||||
|      * | ||||
|      * This can be obtained from {@link net.minecraft.client.renderer.ItemModelMesher#getItemModel(ItemStack)}, | ||||
|      * {@link net.minecraft.client.renderer.model.ModelManager#getModel(ModelResourceLocation)} or any other | ||||
|      * source. | ||||
|      * | ||||
|      * @param turtle Access to the turtle that the upgrade resides on. This will be null when getting item models! | ||||
|      * @param side   Which side of the turtle (left or right) the upgrade resides on. | ||||
|      * @return The model that you wish to be used to render your upgrade. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     @Environment(EnvType.CLIENT) | ||||
|     TransformedModel getModel( @Nullable ITurtleAccess turtle, @Nonnull TurtleSide side ); | ||||
|  | ||||
|     /** | ||||
|      * Called once per tick for each turtle which has the upgrade equipped. | ||||
|      * | ||||
|      * @param turtle Access to the turtle that the upgrade resides on. | ||||
|      * @param side   Which side of the turtle (left or right) the upgrade resides on. | ||||
|      */ | ||||
|     default void update( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side ) | ||||
|     { | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,86 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle; | ||||
|  | ||||
| /** | ||||
|  * An animation a turtle will play between executing commands. | ||||
|  * | ||||
|  * Each animation takes 8 ticks to complete unless otherwise specified. | ||||
|  * | ||||
|  * @see ITurtleAccess#playAnimation(TurtleAnimation) | ||||
|  */ | ||||
| public enum TurtleAnimation | ||||
| { | ||||
|     /** | ||||
|      * An animation which does nothing. This takes no time to complete. | ||||
|      * | ||||
|      * @see #WAIT | ||||
|      * @see #SHORT_WAIT | ||||
|      */ | ||||
|     NONE, | ||||
|  | ||||
|     /** | ||||
|      * Make the turtle move forward. Note that the animation starts from the block <em>behind</em> it, and | ||||
|      * moves into this one. | ||||
|      */ | ||||
|     MOVE_FORWARD, | ||||
|  | ||||
|     /** | ||||
|      * Make the turtle move backwards. Note that the animation starts from the block <em>in front</em> it, and | ||||
|      * moves into this one. | ||||
|      */ | ||||
|     MOVE_BACK, | ||||
|  | ||||
|     /** | ||||
|      * Make the turtle move backwards. Note that the animation starts from the block <em>above</em> it, and | ||||
|      * moves into this one. | ||||
|      */ | ||||
|     MOVE_UP, | ||||
|  | ||||
|     /** | ||||
|      * Make the turtle move backwards. Note that the animation starts from the block <em>below</em> it, and | ||||
|      * moves into this one. | ||||
|      */ | ||||
|     MOVE_DOWN, | ||||
|  | ||||
|     /** | ||||
|      * Turn the turtle to the left. Note that the animation starts with the turtle facing <em>right</em>, and | ||||
|      * the turtle turns to face in the current direction. | ||||
|      */ | ||||
|     TURN_LEFT, | ||||
|  | ||||
|     /** | ||||
|      * Turn the turtle to the left. Note that the animation starts with the turtle facing <em>right</em>, and | ||||
|      * the turtle turns to face in the current direction. | ||||
|      */ | ||||
|     TURN_RIGHT, | ||||
|  | ||||
|     /** | ||||
|      * Swing the tool on the left. | ||||
|      */ | ||||
|     SWING_LEFT_TOOL, | ||||
|  | ||||
|     /** | ||||
|      * Swing the tool on the right. | ||||
|      */ | ||||
|     SWING_RIGHT_TOOL, | ||||
|  | ||||
|     /** | ||||
|      * Wait until the animation has finished, performing no movement. | ||||
|      * | ||||
|      * @see #SHORT_WAIT | ||||
|      * @see #NONE | ||||
|      */ | ||||
|     WAIT, | ||||
|  | ||||
|     /** | ||||
|      * Wait until the animation has finished, performing no movement. This takes 4 ticks to complete. | ||||
|      * | ||||
|      * @see #WAIT | ||||
|      * @see #NONE | ||||
|      */ | ||||
|     SHORT_WAIT, | ||||
| } | ||||
| @@ -0,0 +1,112 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * Used to indicate the result of executing a turtle command. | ||||
|  * | ||||
|  * @see ITurtleCommand#execute(ITurtleAccess) | ||||
|  * @see ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, Direction) | ||||
|  */ | ||||
| public final class TurtleCommandResult | ||||
| { | ||||
|     private static final TurtleCommandResult EMPTY_SUCCESS = new TurtleCommandResult( true, null, null ); | ||||
|     private static final TurtleCommandResult EMPTY_FAILURE = new TurtleCommandResult( false, null, null ); | ||||
|  | ||||
|     /** | ||||
|      * Create a successful command result with no result. | ||||
|      * | ||||
|      * @return A successful command result with no values. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static TurtleCommandResult success() | ||||
|     { | ||||
|         return EMPTY_SUCCESS; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Create a successful command result with the given result values. | ||||
|      * | ||||
|      * @param results The results of executing this command. | ||||
|      * @return A successful command result with the given values. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static TurtleCommandResult success( @Nullable Object[] results ) | ||||
|     { | ||||
|         if( results == null || results.length == 0 ) return EMPTY_SUCCESS; | ||||
|         return new TurtleCommandResult( true, null, results ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Create a failed command result with no error message. | ||||
|      * | ||||
|      * @return A failed command result with no message. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static TurtleCommandResult failure() | ||||
|     { | ||||
|         return EMPTY_FAILURE; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Create a failed command result with an error message. | ||||
|      * | ||||
|      * @param errorMessage The error message to provide. | ||||
|      * @return A failed command result with a message. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public static TurtleCommandResult failure( @Nullable String errorMessage ) | ||||
|     { | ||||
|         if( errorMessage == null ) return EMPTY_FAILURE; | ||||
|         return new TurtleCommandResult( false, errorMessage, null ); | ||||
|     } | ||||
|  | ||||
|     private final boolean success; | ||||
|     private final String errorMessage; | ||||
|     private final Object[] results; | ||||
|  | ||||
|     private TurtleCommandResult( boolean success, String errorMessage, Object[] results ) | ||||
|     { | ||||
|         this.success = success; | ||||
|         this.errorMessage = errorMessage; | ||||
|         this.results = results; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Determine whether the command executed successfully. | ||||
|      * | ||||
|      * @return If the command was successful. | ||||
|      */ | ||||
|     public boolean isSuccess() | ||||
|     { | ||||
|         return success; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the error message of this command result. | ||||
|      * | ||||
|      * @return The command's error message, or {@code null} if it was a success. | ||||
|      */ | ||||
|     @Nullable | ||||
|     public String getErrorMessage() | ||||
|     { | ||||
|         return errorMessage; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the resulting values of this command result. | ||||
|      * | ||||
|      * @return The command's result, or {@code null} if it was a failure. | ||||
|      */ | ||||
|     @Nullable | ||||
|     public Object[] getResults() | ||||
|     { | ||||
|         return results; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,22 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle; | ||||
|  | ||||
| /** | ||||
|  * An enum representing the two sides of the turtle that a turtle turtle might reside. | ||||
|  */ | ||||
| public enum TurtleSide | ||||
| { | ||||
|     /** | ||||
|      * The turtle's left side (where the pickaxe usually is on a Wireless Mining Turtle). | ||||
|      */ | ||||
|     LEFT, | ||||
|  | ||||
|     /** | ||||
|      * The turtle's right side (where the modem usually is on a Wireless Mining Turtle). | ||||
|      */ | ||||
|     RIGHT, | ||||
| } | ||||
| @@ -0,0 +1,43 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle; | ||||
|  | ||||
| /** | ||||
|  * An enum representing the different types of turtle that an {@link ITurtleUpgrade} implementation can add to a turtle. | ||||
|  * | ||||
|  * @see ITurtleUpgrade#getType() | ||||
|  */ | ||||
| public enum TurtleUpgradeType | ||||
| { | ||||
|     /** | ||||
|      * A tool is rendered as an item on the side of the turtle, and responds to the {@code turtle.dig()} | ||||
|      * and {@code turtle.attack()} methods (Such as pickaxe or sword on Mining and Melee turtles). | ||||
|      */ | ||||
|     TOOL, | ||||
|  | ||||
|     /** | ||||
|      * A peripheral adds a special peripheral which is attached to the side of the turtle, | ||||
|      * and can be interacted with the {@code peripheral} API (Such as the modem on Wireless Turtles). | ||||
|      */ | ||||
|     PERIPHERAL, | ||||
|  | ||||
|     /** | ||||
|      * An upgrade which provides both a tool and a peripheral. This can be used when you wish | ||||
|      * your upgrade to also provide methods. For example, a pickaxe could provide methods | ||||
|      * determining whether it can break the given block or not. | ||||
|      */ | ||||
|     BOTH; | ||||
|  | ||||
|     public boolean isTool() | ||||
|     { | ||||
|         return this == TOOL || this == BOTH; | ||||
|     } | ||||
|  | ||||
|     public boolean isPeripheral() | ||||
|     { | ||||
|         return this == PERIPHERAL || this == BOTH; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,26 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle; | ||||
|  | ||||
| /** | ||||
|  * An enum representing the different actions that an {@link ITurtleUpgrade} of type Tool may be called on to perform by | ||||
|  * a turtle. | ||||
|  * | ||||
|  * @see ITurtleUpgrade#getType() | ||||
|  * @see ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, Direction) | ||||
|  */ | ||||
| public enum TurtleVerb | ||||
| { | ||||
|     /** | ||||
|      * The turtle called {@code turtle.dig()}, {@code turtle.digUp()} or {@code turtle.digDown()}. | ||||
|      */ | ||||
|     DIG, | ||||
|  | ||||
|     /** | ||||
|      * The turtle called {@code turtle.attack()}, {@code turtle.attackUp()} or {@code turtle.attackDown()}. | ||||
|      */ | ||||
|     ATTACK, | ||||
| } | ||||
| @@ -0,0 +1,83 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle.event; | ||||
|  | ||||
| /** | ||||
|  * A basic action that a turtle may perform, as accessed by the {@code turtle} API. | ||||
|  * | ||||
|  * @see TurtleActionEvent | ||||
|  */ | ||||
| public enum TurtleAction | ||||
| { | ||||
|     /** | ||||
|      * A turtle moves to a new position. | ||||
|      * | ||||
|      * @see TurtleBlockEvent.Move | ||||
|      */ | ||||
|     MOVE, | ||||
|  | ||||
|     /** | ||||
|      * A turtle turns in a specific direction. | ||||
|      */ | ||||
|     TURN, | ||||
|  | ||||
|     /** | ||||
|      * A turtle attempts to dig a block. | ||||
|      * | ||||
|      * @see TurtleBlockEvent.Dig | ||||
|      */ | ||||
|     DIG, | ||||
|  | ||||
|     /** | ||||
|      * A turtle attempts to place a block or item in the world. | ||||
|      * | ||||
|      * @see TurtleBlockEvent.Place | ||||
|      */ | ||||
|     PLACE, | ||||
|  | ||||
|     /** | ||||
|      * A turtle attempts to attack an entity. | ||||
|      * | ||||
|      * @see TurtleActionEvent | ||||
|      */ | ||||
|     ATTACK, | ||||
|  | ||||
|     /** | ||||
|      * Drop an item into an inventory/the world. | ||||
|      * | ||||
|      * @see TurtleInventoryEvent.Drop | ||||
|      */ | ||||
|     DROP, | ||||
|  | ||||
|     /** | ||||
|      * Suck an item from an inventory or the world. | ||||
|      * | ||||
|      * @see TurtleInventoryEvent.Suck | ||||
|      */ | ||||
|     SUCK, | ||||
|  | ||||
|     /** | ||||
|      * Refuel the turtle's fuel levels. | ||||
|      */ | ||||
|     REFUEL, | ||||
|  | ||||
|     /** | ||||
|      * Equip or unequip an item. | ||||
|      */ | ||||
|     EQUIP, | ||||
|  | ||||
|     /** | ||||
|      * Inspect a block in world. | ||||
|      * | ||||
|      * @see TurtleBlockEvent.Inspect | ||||
|      */ | ||||
|     INSPECT, | ||||
|  | ||||
|     /** | ||||
|      * Gather metdata about an item in the turtle's inventory. | ||||
|      */ | ||||
|     INSPECT_ITEM, | ||||
| } | ||||
| @@ -0,0 +1,81 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle.event; | ||||
|  | ||||
| import dan200.computercraft.api.turtle.ITurtleAccess; | ||||
| import dan200.computercraft.api.turtle.TurtleCommandResult; | ||||
| import net.minecraftforge.eventbus.api.Cancelable; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * An event fired when a turtle is performing a known action. | ||||
|  */ | ||||
| @Cancelable | ||||
| public class TurtleActionEvent extends TurtleEvent | ||||
| { | ||||
|     private final TurtleAction action; | ||||
|     private String failureMessage; | ||||
|  | ||||
|     public TurtleActionEvent( @Nonnull ITurtleAccess turtle, @Nonnull TurtleAction action ) | ||||
|     { | ||||
|         super( turtle ); | ||||
|  | ||||
|         Objects.requireNonNull( action, "action cannot be null" ); | ||||
|         this.action = action; | ||||
|     } | ||||
|  | ||||
|     public TurtleAction getAction() | ||||
|     { | ||||
|         return action; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Sets the cancellation state of this action. | ||||
|      * | ||||
|      * If {@code cancel} is {@code true}, this action will not be carried out. | ||||
|      * | ||||
|      * @param cancel The new canceled value. | ||||
|      * @see TurtleCommandResult#failure() | ||||
|      * @deprecated Use {@link #setCanceled(boolean, String)} instead. | ||||
|      */ | ||||
|     @Override | ||||
|     @Deprecated | ||||
|     public void setCanceled( boolean cancel ) | ||||
|     { | ||||
|         setCanceled( cancel, null ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Set the cancellation state of this action, setting a failure message if required. | ||||
|      * | ||||
|      * If {@code cancel} is {@code true}, this action will not be carried out. | ||||
|      * | ||||
|      * @param cancel         The new canceled value. | ||||
|      * @param failureMessage The message to return to the user explaining the failure. | ||||
|      * @see TurtleCommandResult#failure(String) | ||||
|      */ | ||||
|     public void setCanceled( boolean cancel, @Nullable String failureMessage ) | ||||
|     { | ||||
|         super.setCanceled( cancel ); | ||||
|         this.failureMessage = cancel ? failureMessage : null; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the message with which this will fail. | ||||
|      * | ||||
|      * @return The failure message. | ||||
|      * @see TurtleCommandResult#failure() | ||||
|      * @see #setCanceled(boolean, String) | ||||
|      */ | ||||
|     @Nullable | ||||
|     public String getFailureMessage() | ||||
|     { | ||||
|         return failureMessage; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,78 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle.event; | ||||
|  | ||||
| import dan200.computercraft.api.turtle.ITurtleAccess; | ||||
| import dan200.computercraft.api.turtle.ITurtleUpgrade; | ||||
| import dan200.computercraft.api.turtle.TurtleSide; | ||||
| import dan200.computercraft.api.turtle.TurtleVerb; | ||||
| import net.minecraft.entity.Entity; | ||||
| import net.minecraftforge.common.util.FakePlayer; | ||||
| import net.minecraftforge.event.entity.player.AttackEntityEvent; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * Fired when a turtle attempts to attack an entity. | ||||
|  * | ||||
|  * This must be fired by {@link ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, Direction)}, | ||||
|  * as the base {@code turtle.attack()} command does not fire it. | ||||
|  * | ||||
|  * Note that such commands should also fire {@link AttackEntityEvent}, so you do not need to listen to both. | ||||
|  * | ||||
|  * @see TurtleAction#ATTACK | ||||
|  */ | ||||
| public class TurtleAttackEvent extends TurtlePlayerEvent | ||||
| { | ||||
|     private final Entity target; | ||||
|     private final ITurtleUpgrade upgrade; | ||||
|     private final TurtleSide side; | ||||
|  | ||||
|     public TurtleAttackEvent( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull Entity target, @Nonnull ITurtleUpgrade upgrade, @Nonnull TurtleSide side ) | ||||
|     { | ||||
|         super( turtle, TurtleAction.ATTACK, player ); | ||||
|         Objects.requireNonNull( target, "target cannot be null" ); | ||||
|         Objects.requireNonNull( upgrade, "upgrade cannot be null" ); | ||||
|         Objects.requireNonNull( side, "side cannot be null" ); | ||||
|         this.target = target; | ||||
|         this.upgrade = upgrade; | ||||
|         this.side = side; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the entity being attacked by this turtle. | ||||
|      * | ||||
|      * @return The entity being attacked. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public Entity getTarget() | ||||
|     { | ||||
|         return target; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the upgrade responsible for attacking. | ||||
|      * | ||||
|      * @return The upgrade responsible for attacking. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public ITurtleUpgrade getUpgrade() | ||||
|     { | ||||
|         return upgrade; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the side the attacking upgrade is on. | ||||
|      * | ||||
|      * @return The upgrade's side. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public TurtleSide getSide() | ||||
|     { | ||||
|         return side; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,232 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle.event; | ||||
|  | ||||
| import dan200.computercraft.api.lua.MethodResult; | ||||
| import dan200.computercraft.api.turtle.ITurtleAccess; | ||||
| import dan200.computercraft.api.turtle.ITurtleUpgrade; | ||||
| import dan200.computercraft.api.turtle.TurtleSide; | ||||
| import dan200.computercraft.api.turtle.TurtleVerb; | ||||
| import net.minecraft.block.BlockState; | ||||
| import net.minecraft.item.ItemStack; | ||||
| import net.minecraft.util.math.BlockPos; | ||||
| import net.minecraft.world.World; | ||||
| import net.minecraftforge.common.util.FakePlayer; | ||||
| import net.minecraftforge.event.world.BlockEvent; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.Map; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * A general event for when a turtle interacts with a block or region. | ||||
|  * | ||||
|  * You should generally listen to one of the sub-events instead, cancelling them where | ||||
|  * appropriate. | ||||
|  * | ||||
|  * Note that you are not guaranteed to receive this event, if it has been cancelled by other | ||||
|  * mechanisms, such as block protection systems. | ||||
|  * | ||||
|  * Be aware that some events (such as {@link TurtleInventoryEvent}) do not necessarily interact | ||||
|  * with a block, simply objects within that block space. | ||||
|  */ | ||||
| public abstract class TurtleBlockEvent extends TurtlePlayerEvent | ||||
| { | ||||
|     private final World world; | ||||
|     private final BlockPos pos; | ||||
|  | ||||
|     protected TurtleBlockEvent( @Nonnull ITurtleAccess turtle, @Nonnull TurtleAction action, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos ) | ||||
|     { | ||||
|         super( turtle, action, player ); | ||||
|  | ||||
|         Objects.requireNonNull( world, "world cannot be null" ); | ||||
|         Objects.requireNonNull( pos, "pos cannot be null" ); | ||||
|         this.world = world; | ||||
|         this.pos = pos; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the world the turtle is interacting in. | ||||
|      * | ||||
|      * @return The world the turtle is interacting in. | ||||
|      */ | ||||
|     public World getWorld() | ||||
|     { | ||||
|         return world; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the position the turtle is interacting with. Note that this is different | ||||
|      * to {@link ITurtleAccess#getPosition()}. | ||||
|      * | ||||
|      * @return The position the turtle is interacting with. | ||||
|      */ | ||||
|     public BlockPos getPos() | ||||
|     { | ||||
|         return pos; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Fired when a turtle attempts to dig a block. | ||||
|      * | ||||
|      * This must be fired by {@link ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, Direction)}, | ||||
|      * as the base {@code turtle.dig()} command does not fire it. | ||||
|      * | ||||
|      * Note that such commands should also fire {@link BlockEvent.BreakEvent}, so you do not need to listen to both. | ||||
|      * | ||||
|      * @see TurtleAction#DIG | ||||
|      */ | ||||
|     public static class Dig extends TurtleBlockEvent | ||||
|     { | ||||
|         private final BlockState block; | ||||
|         private final ITurtleUpgrade upgrade; | ||||
|         private final TurtleSide side; | ||||
|  | ||||
|         public Dig( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull BlockState block, @Nonnull ITurtleUpgrade upgrade, @Nonnull TurtleSide side ) | ||||
|         { | ||||
|             super( turtle, TurtleAction.DIG, player, world, pos ); | ||||
|  | ||||
|             Objects.requireNonNull( block, "block cannot be null" ); | ||||
|             Objects.requireNonNull( upgrade, "upgrade cannot be null" ); | ||||
|             Objects.requireNonNull( side, "side cannot be null" ); | ||||
|             this.block = block; | ||||
|             this.upgrade = upgrade; | ||||
|             this.side = side; | ||||
|         } | ||||
|  | ||||
|         /** | ||||
|          * Get the block which is about to be broken. | ||||
|          * | ||||
|          * @return The block which is going to be broken. | ||||
|          */ | ||||
|         @Nonnull | ||||
|         public BlockState getBlock() | ||||
|         { | ||||
|             return block; | ||||
|         } | ||||
|  | ||||
|         /** | ||||
|          * Get the upgrade doing the digging. | ||||
|          * | ||||
|          * @return The upgrade doing the digging. | ||||
|          */ | ||||
|         @Nonnull | ||||
|         public ITurtleUpgrade getUpgrade() | ||||
|         { | ||||
|             return upgrade; | ||||
|         } | ||||
|  | ||||
|         /** | ||||
|          * Get the side the upgrade doing the digging is on. | ||||
|          * | ||||
|          * @return The upgrade's side. | ||||
|          */ | ||||
|         @Nonnull | ||||
|         public TurtleSide getSide() | ||||
|         { | ||||
|             return side; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Fired when a turtle attempts to move into a block. | ||||
|      * | ||||
|      * @see TurtleAction#MOVE | ||||
|      */ | ||||
|     public static class Move extends TurtleBlockEvent | ||||
|     { | ||||
|         public Move( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos ) | ||||
|         { | ||||
|             super( turtle, TurtleAction.MOVE, player, world, pos ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Fired when a turtle attempts to place a block in the world. | ||||
|      * | ||||
|      * @see TurtleAction#PLACE | ||||
|      */ | ||||
|     public static class Place extends TurtleBlockEvent | ||||
|     { | ||||
|         private final ItemStack stack; | ||||
|  | ||||
|         public Place( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull ItemStack stack ) | ||||
|         { | ||||
|             super( turtle, TurtleAction.PLACE, player, world, pos ); | ||||
|  | ||||
|             Objects.requireNonNull( stack, "stack cannot be null" ); | ||||
|             this.stack = stack; | ||||
|         } | ||||
|  | ||||
|         /** | ||||
|          * Get the item stack that will be placed. This should not be modified. | ||||
|          * | ||||
|          * @return The item stack to be placed. | ||||
|          */ | ||||
|         @Nonnull | ||||
|         public ItemStack getStack() | ||||
|         { | ||||
|             return stack; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Fired when a turtle gathers data on a block in world. | ||||
|      * | ||||
|      * You may prevent blocks being inspected, or add additional information to the result. | ||||
|      * | ||||
|      * @see TurtleAction#INSPECT | ||||
|      */ | ||||
|     public static class Inspect extends TurtleBlockEvent | ||||
|     { | ||||
|         private final BlockState state; | ||||
|         private final Map<String, Object> data; | ||||
|  | ||||
|         public Inspect( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nonnull Map<String, Object> data ) | ||||
|         { | ||||
|             super( turtle, TurtleAction.INSPECT, player, world, pos ); | ||||
|  | ||||
|             Objects.requireNonNull( state, "state cannot be null" ); | ||||
|             Objects.requireNonNull( data, "data cannot be null" ); | ||||
|             this.data = data; | ||||
|             this.state = state; | ||||
|         } | ||||
|  | ||||
|         /** | ||||
|          * Get the block state which is being inspected. | ||||
|          * | ||||
|          * @return The inspected block state. | ||||
|          */ | ||||
|         @Nonnull | ||||
|         public BlockState getState() | ||||
|         { | ||||
|             return state; | ||||
|         } | ||||
|  | ||||
|         /** | ||||
|          * Get the "inspection data" from this block, which will be returned to the user. | ||||
|          * | ||||
|          * @return This block's inspection data. | ||||
|          */ | ||||
|         @Nonnull | ||||
|         public Map<String, Object> getData() | ||||
|         { | ||||
|             return data; | ||||
|         } | ||||
|  | ||||
|         /** | ||||
|          * Add new information to the inspection result. Note this will override fields with the same name. | ||||
|          * | ||||
|          * @param newData The data to add. Note all values should be convertible to Lua (see | ||||
|          *                {@link MethodResult#of(Object)}). | ||||
|          */ | ||||
|         public void addData( @Nonnull Map<String, ?> newData ) | ||||
|         { | ||||
|             Objects.requireNonNull( newData, "newData cannot be null" ); | ||||
|             data.putAll( newData ); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,42 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle.event; | ||||
|  | ||||
| import dan200.computercraft.api.turtle.ITurtleAccess; | ||||
| import net.minecraftforge.eventbus.api.Event; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * A base class for all events concerning a turtle. This will only ever constructed and fired on the server side, | ||||
|  * so sever specific methods on {@link ITurtleAccess} are safe to use. | ||||
|  * | ||||
|  * You should generally not need to subscribe to this event, preferring one of the more specific classes. | ||||
|  * | ||||
|  * @see TurtleActionEvent | ||||
|  */ | ||||
| public abstract class TurtleEvent extends Event | ||||
| { | ||||
|     private final ITurtleAccess turtle; | ||||
|  | ||||
|     protected TurtleEvent( @Nonnull ITurtleAccess turtle ) | ||||
|     { | ||||
|         Objects.requireNonNull( turtle, "turtle cannot be null" ); | ||||
|         this.turtle = turtle; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the turtle which is performing this action. | ||||
|      * | ||||
|      * @return The access for this turtle. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public ITurtleAccess getTurtle() | ||||
|     { | ||||
|         return turtle; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,91 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle.event; | ||||
|  | ||||
| import dan200.computercraft.api.lua.MethodResult; | ||||
| import dan200.computercraft.api.turtle.ITurtleAccess; | ||||
| import net.minecraft.item.ItemStack; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.Map; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * Fired when a turtle gathers data on an item in its inventory. | ||||
|  * | ||||
|  * You may prevent items being inspected, or add additional information to the result. Be aware that this may be fired | ||||
|  * on the computer thread, and so any operations on it must be thread safe. | ||||
|  * | ||||
|  * @see TurtleAction#INSPECT_ITEM | ||||
|  */ | ||||
| public class TurtleInspectItemEvent extends TurtleActionEvent | ||||
| { | ||||
|     private final ItemStack stack; | ||||
|     private final Map<String, Object> data; | ||||
|     private final boolean mainThread; | ||||
|  | ||||
|     @Deprecated | ||||
|     public TurtleInspectItemEvent( @Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack, @Nonnull Map<String, Object> data ) | ||||
|     { | ||||
|         this( turtle, stack, data, false ); | ||||
|     } | ||||
|  | ||||
|     public TurtleInspectItemEvent( @Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack, @Nonnull Map<String, Object> data, boolean mainThread ) | ||||
|     { | ||||
|         super( turtle, TurtleAction.INSPECT_ITEM ); | ||||
|  | ||||
|         Objects.requireNonNull( stack, "stack cannot be null" ); | ||||
|         Objects.requireNonNull( data, "data cannot be null" ); | ||||
|         this.stack = stack; | ||||
|         this.data = data; | ||||
|         this.mainThread = mainThread; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * The item which is currently being inspected. | ||||
|      * | ||||
|      * @return The item stack which is being inspected. This should <b>not</b> be modified. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public ItemStack getStack() | ||||
|     { | ||||
|         return stack; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the "inspection data" from this item, which will be returned to the user. | ||||
|      * | ||||
|      * @return This items's inspection data. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public Map<String, Object> getData() | ||||
|     { | ||||
|         return data; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * If this event is being fired on the server thread. When true, information which relies on server state may be | ||||
|      * exposed. | ||||
|      * | ||||
|      * @return If this is run on the main thread. | ||||
|      */ | ||||
|     public boolean onMainThread() | ||||
|     { | ||||
|         return mainThread; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Add new information to the inspection result. Note this will override fields with the same name. | ||||
|      * | ||||
|      * @param newData The data to add. Note all values should be convertible to Lua (see | ||||
|      *                {@link MethodResult#of(Object)}). | ||||
|      */ | ||||
|     public void addData( @Nonnull Map<String, ?> newData ) | ||||
|     { | ||||
|         Objects.requireNonNull( newData, "newData cannot be null" ); | ||||
|         data.putAll( newData ); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,84 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle.event; | ||||
|  | ||||
| import dan200.computercraft.api.turtle.ITurtleAccess; | ||||
| import net.minecraft.item.ItemStack; | ||||
| import net.minecraft.util.math.BlockPos; | ||||
| import net.minecraft.world.World; | ||||
| import net.minecraftforge.common.util.FakePlayer; | ||||
| import net.minecraftforge.items.IItemHandler; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * Fired when a turtle attempts to interact with an inventory. | ||||
|  */ | ||||
| public abstract class TurtleInventoryEvent extends TurtleBlockEvent | ||||
| { | ||||
|     private final IItemHandler handler; | ||||
|  | ||||
|     protected TurtleInventoryEvent( @Nonnull ITurtleAccess turtle, @Nonnull TurtleAction action, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nullable IItemHandler handler ) | ||||
|     { | ||||
|         super( turtle, action, player, world, pos ); | ||||
|         this.handler = handler; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the inventory being interacted with. | ||||
|      * | ||||
|      * @return The inventory being interacted with, {@code null} if the item will be dropped to/sucked from the world. | ||||
|      */ | ||||
|     @Nullable | ||||
|     public IItemHandler getItemHandler() | ||||
|     { | ||||
|         return handler; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Fired when a turtle attempts to suck from an inventory. | ||||
|      * | ||||
|      * @see TurtleAction#SUCK | ||||
|      */ | ||||
|     public static class Suck extends TurtleInventoryEvent | ||||
|     { | ||||
|         public Suck( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nullable IItemHandler handler ) | ||||
|         { | ||||
|             super( turtle, TurtleAction.SUCK, player, world, pos, handler ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Fired when a turtle attempts to drop an item into an inventory. | ||||
|      * | ||||
|      * @see TurtleAction#DROP | ||||
|      */ | ||||
|     public static class Drop extends TurtleInventoryEvent | ||||
|     { | ||||
|         private final ItemStack stack; | ||||
|  | ||||
|         public Drop( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nullable IItemHandler handler, @Nonnull ItemStack stack ) | ||||
|         { | ||||
|             super( turtle, TurtleAction.DROP, player, world, pos, handler ); | ||||
|  | ||||
|             Objects.requireNonNull( stack, "stack cannot be null" ); | ||||
|             this.stack = stack; | ||||
|         } | ||||
|  | ||||
|         /** | ||||
|          * The item which will be inserted into the inventory/dropped on the ground. | ||||
|          * | ||||
|          * @return The item stack which will be dropped. This should <b>not</b> be modified. | ||||
|          */ | ||||
|         @Nonnull | ||||
|         public ItemStack getStack() | ||||
|         { | ||||
|             return stack; | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,43 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle.event; | ||||
|  | ||||
| import dan200.computercraft.api.turtle.ITurtleAccess; | ||||
| import net.minecraftforge.common.util.FakePlayer; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * An action done by a turtle which is normally done by a player. | ||||
|  * | ||||
|  * {@link #getPlayer()} may be used to modify the player's attributes or perform permission checks. | ||||
|  */ | ||||
| public abstract class TurtlePlayerEvent extends TurtleActionEvent | ||||
| { | ||||
|     private final FakePlayer player; | ||||
|  | ||||
|     protected TurtlePlayerEvent( @Nonnull ITurtleAccess turtle, @Nonnull TurtleAction action, @Nonnull FakePlayer player ) | ||||
|     { | ||||
|         super( turtle, action ); | ||||
|  | ||||
|         Objects.requireNonNull( player, "player cannot be null" ); | ||||
|         this.player = player; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * A fake player, representing this turtle. | ||||
|      * | ||||
|      * This may be used for triggering permission checks. | ||||
|      * | ||||
|      * @return A {@link FakePlayer} representing this turtle. | ||||
|      */ | ||||
|     @Nonnull | ||||
|     public FakePlayer getPlayer() | ||||
|     { | ||||
|         return player; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,90 @@ | ||||
| /* | ||||
|  * This file is part of the public ComputerCraft API - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. This API may be redistributed unmodified and in full only. | ||||
|  * For help using the API, and posting your mods, visit the forums at computercraft.info. | ||||
|  */ | ||||
| package dan200.computercraft.api.turtle.event; | ||||
|  | ||||
| import dan200.computercraft.api.turtle.ITurtleAccess; | ||||
| import net.minecraft.item.ItemStack; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.util.Objects; | ||||
|  | ||||
| /** | ||||
|  * Fired when a turtle attempts to refuel from an item. | ||||
|  * | ||||
|  * One may use {@link #setCanceled(boolean, String)} to prevent refueling from this specific item. Additionally, you | ||||
|  * may use {@link #setHandler(Handler)} to register a custom fuel provider. | ||||
|  */ | ||||
| public class TurtleRefuelEvent extends TurtleActionEvent | ||||
| { | ||||
|     private final ItemStack stack; | ||||
|     private Handler handler; | ||||
|  | ||||
|     public TurtleRefuelEvent( @Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack ) | ||||
|     { | ||||
|         super( turtle, TurtleAction.REFUEL ); | ||||
|  | ||||
|         Objects.requireNonNull( turtle, "turtle cannot be null" ); | ||||
|         this.stack = stack; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the stack we are attempting to refuel from. | ||||
|      * | ||||
|      * Do not modify the returned stack - all modifications should be done within the {@link Handler}. | ||||
|      * | ||||
|      * @return The stack to refuel from. | ||||
|      */ | ||||
|     public ItemStack getStack() | ||||
|     { | ||||
|         return stack; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the refuel handler for this stack. | ||||
|      * | ||||
|      * @return The refuel handler, or {@code null} if none has currently been set. | ||||
|      * @see #setHandler(Handler) | ||||
|      */ | ||||
|     @Nullable | ||||
|     public Handler getHandler() | ||||
|     { | ||||
|         return handler; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Set the refuel handler for this stack. | ||||
|      * | ||||
|      * You should call this if you can actually refuel from this item, and ideally only if there are no existing | ||||
|      * handlers. | ||||
|      * | ||||
|      * @param handler The new refuel handler. | ||||
|      * @see #getHandler() | ||||
|      */ | ||||
|     public void setHandler( @Nullable Handler handler ) | ||||
|     { | ||||
|         this.handler = handler; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Handles refuelling a turtle from a specific item. | ||||
|      */ | ||||
|     @FunctionalInterface | ||||
|     public interface Handler | ||||
|     { | ||||
|         /** | ||||
|          * Refuel a turtle using an item. | ||||
|          * | ||||
|          * @param turtle The turtle to refuel. | ||||
|          * @param stack  The stack to refuel with. | ||||
|          * @param slot   The slot the stack resides within. This may be used to modify the inventory afterwards. | ||||
|          * @param limit  The maximum number of refuel operations to perform. This will often correspond to the number of | ||||
|          *               items to consume. | ||||
|          * @return The amount of fuel gained. | ||||
|          */ | ||||
|         int refuel( @Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack, int slot, int limit ); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										151
									
								
								src/main/java/dan200/computercraft/client/ClientRegistry.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										151
									
								
								src/main/java/dan200/computercraft/client/ClientRegistry.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,151 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client; | ||||
|  | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import dan200.computercraft.client.render.TurtleModelLoader; | ||||
| import dan200.computercraft.shared.Registry; | ||||
| import dan200.computercraft.shared.common.IColouredItem; | ||||
| import dan200.computercraft.shared.media.items.ItemDisk; | ||||
| import dan200.computercraft.shared.media.items.ItemTreasureDisk; | ||||
| import dan200.computercraft.shared.pocket.items.ItemPocketComputer; | ||||
| import dan200.computercraft.shared.util.Colour; | ||||
| import net.minecraft.client.render.model.BakedModel; | ||||
| import net.minecraft.client.render.model.UnbakedModel; | ||||
| import net.minecraft.client.util.ModelIdentifier; | ||||
| import net.minecraft.screen.PlayerScreenHandler; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraftforge.api.distmarker.Dist; | ||||
| import net.minecraftforge.client.event.ColorHandlerEvent; | ||||
| import net.minecraftforge.client.event.ModelBakeEvent; | ||||
| import net.minecraftforge.client.event.ModelRegistryEvent; | ||||
| import net.minecraftforge.client.event.TextureStitchEvent; | ||||
| import net.minecraftforge.client.model.ModelLoader; | ||||
| import net.minecraftforge.client.model.ModelLoaderRegistry; | ||||
| import net.minecraftforge.client.model.SimpleModelTransform; | ||||
| import net.minecraftforge.eventbus.api.SubscribeEvent; | ||||
| import net.minecraftforge.fml.common.Mod; | ||||
|  | ||||
| import java.util.HashSet; | ||||
| import java.util.Map; | ||||
|  | ||||
| /** | ||||
|  * Registers textures and models for items. | ||||
|  */ | ||||
| @Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD ) | ||||
| public final class ClientRegistry | ||||
| { | ||||
|     private static final String[] EXTRA_MODELS = new String[] { | ||||
|         "turtle_modem_normal_off_left", | ||||
|         "turtle_modem_normal_on_left", | ||||
|         "turtle_modem_normal_off_right", | ||||
|         "turtle_modem_normal_on_right", | ||||
|  | ||||
|         "turtle_modem_advanced_off_left", | ||||
|         "turtle_modem_advanced_on_left", | ||||
|         "turtle_modem_advanced_off_right", | ||||
|         "turtle_modem_advanced_on_right", | ||||
|         "turtle_crafting_table_left", | ||||
|         "turtle_crafting_table_right", | ||||
|  | ||||
|         "turtle_speaker_upgrade_left", | ||||
|         "turtle_speaker_upgrade_right", | ||||
|  | ||||
|         "turtle_colour", | ||||
|         "turtle_elf_overlay", | ||||
|     }; | ||||
|  | ||||
|     private static final String[] EXTRA_TEXTURES = new String[] { | ||||
|         // TODO: Gather these automatically from the model. Sadly the model loader isn't available | ||||
|         //  when stitching textures. | ||||
|         "block/turtle_colour", | ||||
|         "block/turtle_elf_overlay", | ||||
|         "block/turtle_crafty_face", | ||||
|         "block/turtle_speaker_face", | ||||
|     }; | ||||
|  | ||||
|     private ClientRegistry() {} | ||||
|  | ||||
|     @SubscribeEvent | ||||
|     public static void registerModels( ModelRegistryEvent event ) | ||||
|     { | ||||
|         ModelLoaderRegistry.registerLoader( new Identifier( ComputerCraft.MOD_ID, "turtle" ), TurtleModelLoader.INSTANCE ); | ||||
|     } | ||||
|  | ||||
|     @SubscribeEvent | ||||
|     public static void onTextureStitchEvent( TextureStitchEvent.Pre event ) | ||||
|     { | ||||
|         if( !event.getMap().getId().equals( PlayerScreenHandler.BLOCK_ATLAS_TEXTURE ) ) return; | ||||
|  | ||||
|         for( String extra : EXTRA_TEXTURES ) | ||||
|         { | ||||
|             event.addSprite( new Identifier( ComputerCraft.MOD_ID, extra ) ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @SubscribeEvent | ||||
|     public static void onModelBakeEvent( ModelBakeEvent event ) | ||||
|     { | ||||
|         // Load all extra models | ||||
|         ModelLoader loader = event.getModelLoader(); | ||||
|         Map<Identifier, BakedModel> registry = event.getModelRegistry(); | ||||
|  | ||||
|         for( String modelName : EXTRA_MODELS ) | ||||
|         { | ||||
|             Identifier location = new Identifier( ComputerCraft.MOD_ID, "item/" + modelName ); | ||||
|             UnbakedModel model = loader.getOrLoadModel( location ); | ||||
|             model.getTextureDependencies( loader::getOrLoadModel, new HashSet<>() ); | ||||
|  | ||||
|             BakedModel baked = model.bake( loader, ModelLoader.defaultTextureGetter(), SimpleModelTransform.IDENTITY, location ); | ||||
|             if( baked != null ) | ||||
|             { | ||||
|                 registry.put( new ModelIdentifier( new Identifier( ComputerCraft.MOD_ID, modelName ), "inventory" ), baked ); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @SubscribeEvent | ||||
|     public static void onItemColours( ColorHandlerEvent.Item event ) | ||||
|     { | ||||
|         if( Registry.ModItems.DISK == null || Registry.ModBlocks.TURTLE_NORMAL == null ) | ||||
|         { | ||||
|             ComputerCraft.log.warn( "Block/item registration has failed. Skipping registration of item colours." ); | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         event.getItemColors().register( | ||||
|             ( stack, layer ) -> layer == 1 ? ((ItemDisk) stack.getItem()).getColour( stack ) : 0xFFFFFF, | ||||
|             Registry.ModItems.DISK.get() | ||||
|         ); | ||||
|  | ||||
|         event.getItemColors().register( | ||||
|             ( stack, layer ) -> layer == 1 ? ItemTreasureDisk.getColour( stack ) : 0xFFFFFF, | ||||
|             Registry.ModItems.TREASURE_DISK.get() | ||||
|         ); | ||||
|  | ||||
|         event.getItemColors().register( ( stack, layer ) -> { | ||||
|             switch( layer ) | ||||
|             { | ||||
|                 case 0: | ||||
|                 default: | ||||
|                     return 0xFFFFFF; | ||||
|                 case 1: // Frame colour | ||||
|                     return IColouredItem.getColourBasic( stack ); | ||||
|                 case 2: // Light colour | ||||
|                 { | ||||
|                     int light = ItemPocketComputer.getLightState( stack ); | ||||
|                     return light == -1 ? Colour.BLACK.getHex() : light; | ||||
|                 } | ||||
|             } | ||||
|         }, Registry.ModItems.POCKET_COMPUTER_NORMAL.get(), Registry.ModItems.POCKET_COMPUTER_ADVANCED.get() ); | ||||
|  | ||||
|         // Setup turtle colours | ||||
|         event.getItemColors().register( | ||||
|             ( stack, tintIndex ) -> tintIndex == 0 ? ((IColouredItem) stack.getItem()).getColour( stack ) : 0xFFFFFF, | ||||
|             Registry.ModBlocks.TURTLE_NORMAL.get(), Registry.ModBlocks.TURTLE_ADVANCED.get() | ||||
|         ); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,87 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client; | ||||
|  | ||||
| import dan200.computercraft.shared.command.text.ChatHelpers; | ||||
| import dan200.computercraft.shared.command.text.TableBuilder; | ||||
| import dan200.computercraft.shared.command.text.TableFormatter; | ||||
| import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; | ||||
| import net.minecraft.client.MinecraftClient; | ||||
| import net.minecraft.client.font.TextRenderer; | ||||
| import net.minecraft.client.gui.hud.ChatHud; | ||||
| import net.minecraft.text.Text; | ||||
| import net.minecraft.util.Formatting; | ||||
| import net.minecraft.util.math.MathHelper; | ||||
| import org.apache.commons.lang3.StringUtils; | ||||
|  | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| public class ClientTableFormatter implements TableFormatter | ||||
| { | ||||
|     public static final ClientTableFormatter INSTANCE = new ClientTableFormatter(); | ||||
|  | ||||
|     private static Int2IntOpenHashMap lastHeights = new Int2IntOpenHashMap(); | ||||
|  | ||||
|     private static TextRenderer renderer() | ||||
|     { | ||||
|         return MinecraftClient.getInstance().textRenderer; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     @Nullable | ||||
|     public Text getPadding( Text component, int width ) | ||||
|     { | ||||
|         int extraWidth = width - getWidth( component ); | ||||
|         if( extraWidth <= 0 ) return null; | ||||
|  | ||||
|         TextRenderer renderer = renderer(); | ||||
|  | ||||
|         float spaceWidth = renderer.getWidth( " " ); | ||||
|         int spaces = MathHelper.floor( extraWidth / spaceWidth ); | ||||
|         int extra = extraWidth - (int) (spaces * spaceWidth); | ||||
|  | ||||
|         return ChatHelpers.coloured( StringUtils.repeat( ' ', spaces ) + StringUtils.repeat( (char) 712, extra ), Formatting.GRAY ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public int getColumnPadding() | ||||
|     { | ||||
|         return 3; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public int getWidth( Text component ) | ||||
|     { | ||||
|         return renderer().getWidth( component ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void writeLine( int id, Text component ) | ||||
|     { | ||||
|         MinecraftClient mc = MinecraftClient.getInstance(); | ||||
|         ChatHud chat = mc.inGameHud.getChatHud(); | ||||
|  | ||||
|         // TODO: Trim the text if it goes over the allowed length | ||||
|         // int maxWidth = MathHelper.floor( chat.getChatWidth() / chat.getScale() ); | ||||
|         // List<ITextProperties> list = RenderComponentsUtil.func_238505_a_( component, maxWidth, mc.fontRenderer ); | ||||
|         // if( !list.isEmpty() ) chat.printChatMessageWithOptionalDeletion( list.get( 0 ), id ); | ||||
|         chat.addMessage( component, id ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public int display( TableBuilder table ) | ||||
|     { | ||||
|         ChatHud chat = MinecraftClient.getInstance().inGameHud.getChatHud(); | ||||
|  | ||||
|         int lastHeight = lastHeights.get( table.getId() ); | ||||
|  | ||||
|         int height = TableFormatter.super.display( table ); | ||||
|         lastHeights.put( table.getId(), height ); | ||||
|  | ||||
|         for( int i = height; i < lastHeight; i++ ) chat.removeMessage( i + table.getId() ); | ||||
|         return height; | ||||
|     } | ||||
| } | ||||
							
								
								
									
										45
									
								
								src/main/java/dan200/computercraft/client/FrameInfo.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										45
									
								
								src/main/java/dan200/computercraft/client/FrameInfo.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,45 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client; | ||||
|  | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import net.minecraftforge.api.distmarker.Dist; | ||||
| import net.minecraftforge.event.TickEvent; | ||||
| import net.minecraftforge.eventbus.api.SubscribeEvent; | ||||
| import net.minecraftforge.fml.common.Mod; | ||||
|  | ||||
| @Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT ) | ||||
| public final class FrameInfo | ||||
| { | ||||
|     private static int tick; | ||||
|     private static long renderFrame; | ||||
|  | ||||
|     private FrameInfo() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     public static boolean getGlobalCursorBlink() | ||||
|     { | ||||
|         return (tick / 8) % 2 == 0; | ||||
|     } | ||||
|  | ||||
|     public static long getRenderFrame() | ||||
|     { | ||||
|         return renderFrame; | ||||
|     } | ||||
|  | ||||
|     @SubscribeEvent | ||||
|     public static void onTick( TickEvent.ClientTickEvent event ) | ||||
|     { | ||||
|         if( event.phase == TickEvent.Phase.START ) tick++; | ||||
|     } | ||||
|  | ||||
|     @SubscribeEvent | ||||
|     public static void onRenderTick( TickEvent.RenderTickEvent event ) | ||||
|     { | ||||
|         if( event.phase == TickEvent.Phase.START ) renderFrame++; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,349 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.gui; | ||||
|  | ||||
| import com.mojang.blaze3d.systems.RenderSystem; | ||||
| import dan200.computercraft.client.FrameInfo; | ||||
| import dan200.computercraft.core.terminal.Terminal; | ||||
| import dan200.computercraft.core.terminal.TextBuffer; | ||||
| import dan200.computercraft.shared.util.Colour; | ||||
| import dan200.computercraft.shared.util.Palette; | ||||
| import org.lwjgl.opengl.GL11; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import net.minecraft.client.MinecraftClient; | ||||
| import net.minecraft.client.render.RenderLayer; | ||||
| import net.minecraft.client.render.RenderPhase; | ||||
| import net.minecraft.client.render.VertexConsumer; | ||||
| import net.minecraft.client.render.VertexConsumerProvider; | ||||
| import net.minecraft.client.render.VertexFormat; | ||||
| import net.minecraft.client.render.VertexFormats; | ||||
| import net.minecraft.client.util.math.AffineTransformation; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraft.util.math.Matrix4f; | ||||
|  | ||||
| public final class FixedWidthFontRenderer | ||||
| { | ||||
|     private static final Matrix4f IDENTITY = AffineTransformation.identity().getMatrix(); | ||||
|  | ||||
|     private static final Identifier FONT = new Identifier( "computercraft", "textures/gui/term_font.png" ); | ||||
|  | ||||
|     public static final int FONT_HEIGHT = 9; | ||||
|     public static final int FONT_WIDTH = 6; | ||||
|     public static final float WIDTH = 256.0f; | ||||
|  | ||||
|     public static final float BACKGROUND_START = (WIDTH - 6.0f) / WIDTH; | ||||
|     public static final float BACKGROUND_END = (WIDTH - 4.0f) / WIDTH; | ||||
|  | ||||
|     public static final RenderLayer TYPE = Type.MAIN; | ||||
|  | ||||
|     private FixedWidthFontRenderer() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     public static float toGreyscale( double[] rgb ) | ||||
|     { | ||||
|         return (float) ((rgb[0] + rgb[1] + rgb[2]) / 3); | ||||
|     } | ||||
|  | ||||
|     public static int getColour( char c, Colour def ) | ||||
|     { | ||||
|         return 15 - Terminal.getColour( c, def ); | ||||
|     } | ||||
|  | ||||
|     private static void drawChar( Matrix4f transform, VertexConsumer buffer, float x, float y, int index, float r, float g, float b ) | ||||
|     { | ||||
|         // Short circuit to avoid the common case - the texture should be blank here after all. | ||||
|         if( index == '\0' || index == ' ' ) return; | ||||
|  | ||||
|         int column = index % 16; | ||||
|         int row = index / 16; | ||||
|  | ||||
|         int xStart = 1 + column * (FONT_WIDTH + 2); | ||||
|         int yStart = 1 + row * (FONT_HEIGHT + 2); | ||||
|  | ||||
|         buffer.vertex( transform, x, y, 0f ).color( r, g, b, 1.0f ).texture( xStart / WIDTH, yStart / WIDTH ).next(); | ||||
|         buffer.vertex( transform, x, y + FONT_HEIGHT, 0f ).color( r, g, b, 1.0f ).texture( xStart / WIDTH, (yStart + FONT_HEIGHT) / WIDTH ).next(); | ||||
|         buffer.vertex( transform, x + FONT_WIDTH, y, 0f ).color( r, g, b, 1.0f ).texture( (xStart + FONT_WIDTH) / WIDTH, yStart / WIDTH ).next(); | ||||
|         buffer.vertex( transform, x + FONT_WIDTH, y, 0f ).color( r, g, b, 1.0f ).texture( (xStart + FONT_WIDTH) / WIDTH, yStart / WIDTH ).next(); | ||||
|         buffer.vertex( transform, x, y + FONT_HEIGHT, 0f ).color( r, g, b, 1.0f ).texture( xStart / WIDTH, (yStart + FONT_HEIGHT) / WIDTH ).next(); | ||||
|         buffer.vertex( transform, x + FONT_WIDTH, y + FONT_HEIGHT, 0f ).color( r, g, b, 1.0f ).texture( (xStart + FONT_WIDTH) / WIDTH, (yStart + FONT_HEIGHT) / WIDTH ).next(); | ||||
|     } | ||||
|  | ||||
|     private static void drawQuad( Matrix4f transform, VertexConsumer buffer, float x, float y, float width, float height, float r, float g, float b ) | ||||
|     { | ||||
|         buffer.vertex( transform, x, y, 0 ).color( r, g, b, 1.0f ).texture( BACKGROUND_START, BACKGROUND_START ).next(); | ||||
|         buffer.vertex( transform, x, y + height, 0 ).color( r, g, b, 1.0f ).texture( BACKGROUND_START, BACKGROUND_END ).next(); | ||||
|         buffer.vertex( transform, x + width, y, 0 ).color( r, g, b, 1.0f ).texture( BACKGROUND_END, BACKGROUND_START ).next(); | ||||
|         buffer.vertex( transform, x + width, y, 0 ).color( r, g, b, 1.0f ).texture( BACKGROUND_END, BACKGROUND_START ).next(); | ||||
|         buffer.vertex( transform, x, y + height, 0 ).color( r, g, b, 1.0f ).texture( BACKGROUND_START, BACKGROUND_END ).next(); | ||||
|         buffer.vertex( transform, x + width, y + height, 0 ).color( r, g, b, 1.0f ).texture( BACKGROUND_END, BACKGROUND_END ).next(); | ||||
|     } | ||||
|  | ||||
|     private static void drawQuad( Matrix4f transform, VertexConsumer buffer, float x, float y, float width, float height, Palette palette, boolean greyscale, char colourIndex ) | ||||
|     { | ||||
|         double[] colour = palette.getColour( getColour( colourIndex, Colour.BLACK ) ); | ||||
|         float r, g, b; | ||||
|         if( greyscale ) | ||||
|         { | ||||
|             r = g = b = toGreyscale( colour ); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             r = (float) colour[0]; | ||||
|             g = (float) colour[1]; | ||||
|             b = (float) colour[2]; | ||||
|         } | ||||
|  | ||||
|         drawQuad( transform, buffer, x, y, width, height, r, g, b ); | ||||
|     } | ||||
|  | ||||
|     private static void drawBackground( | ||||
|         @Nonnull Matrix4f transform, @Nonnull VertexConsumer renderer, float x, float y, | ||||
|         @Nonnull TextBuffer backgroundColour, @Nonnull Palette palette, boolean greyscale, | ||||
|         float leftMarginSize, float rightMarginSize, float height | ||||
|     ) | ||||
|     { | ||||
|         if( leftMarginSize > 0 ) | ||||
|         { | ||||
|             drawQuad( transform, renderer, x - leftMarginSize, y, leftMarginSize, height, palette, greyscale, backgroundColour.charAt( 0 ) ); | ||||
|         } | ||||
|  | ||||
|         if( rightMarginSize > 0 ) | ||||
|         { | ||||
|             drawQuad( transform, renderer, x + backgroundColour.length() * FONT_WIDTH, y, rightMarginSize, height, palette, greyscale, backgroundColour.charAt( backgroundColour.length() - 1 ) ); | ||||
|         } | ||||
|  | ||||
|         // Batch together runs of identical background cells. | ||||
|         int blockStart = 0; | ||||
|         char blockColour = '\0'; | ||||
|         for( int i = 0; i < backgroundColour.length(); i++ ) | ||||
|         { | ||||
|             char colourIndex = backgroundColour.charAt( i ); | ||||
|             if( colourIndex == blockColour ) continue; | ||||
|  | ||||
|             if( blockColour != '\0' ) | ||||
|             { | ||||
|                 drawQuad( transform, renderer, x + blockStart * FONT_WIDTH, y, FONT_WIDTH * (i - blockStart), height, palette, greyscale, blockColour ); | ||||
|             } | ||||
|  | ||||
|             blockColour = colourIndex; | ||||
|             blockStart = i; | ||||
|         } | ||||
|  | ||||
|         if( blockColour != '\0' ) | ||||
|         { | ||||
|             drawQuad( transform, renderer, x + blockStart * FONT_WIDTH, y, FONT_WIDTH * (backgroundColour.length() - blockStart), height, palette, greyscale, blockColour ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static void drawString( | ||||
|         @Nonnull Matrix4f transform, @Nonnull VertexConsumer renderer, float x, float y, | ||||
|         @Nonnull TextBuffer text, @Nonnull TextBuffer textColour, @Nullable TextBuffer backgroundColour, | ||||
|         @Nonnull Palette palette, boolean greyscale, float leftMarginSize, float rightMarginSize | ||||
|     ) | ||||
|     { | ||||
|         if( backgroundColour != null ) | ||||
|         { | ||||
|             drawBackground( transform, renderer, x, y, backgroundColour, palette, greyscale, leftMarginSize, rightMarginSize, FONT_HEIGHT ); | ||||
|         } | ||||
|  | ||||
|         for( int i = 0; i < text.length(); i++ ) | ||||
|         { | ||||
|             double[] colour = palette.getColour( getColour( textColour.charAt( i ), Colour.BLACK ) ); | ||||
|             float r, g, b; | ||||
|             if( greyscale ) | ||||
|             { | ||||
|                 r = g = b = toGreyscale( colour ); | ||||
|             } | ||||
|             else | ||||
|             { | ||||
|                 r = (float) colour[0]; | ||||
|                 g = (float) colour[1]; | ||||
|                 b = (float) colour[2]; | ||||
|             } | ||||
|  | ||||
|             // Draw char | ||||
|             int index = text.charAt( i ); | ||||
|             if( index > 255 ) index = '?'; | ||||
|             drawChar( transform, renderer, x + i * FONT_WIDTH, y, index, r, g, b ); | ||||
|         } | ||||
|  | ||||
|     } | ||||
|  | ||||
|     public static void drawString( | ||||
|         float x, float y, @Nonnull TextBuffer text, @Nonnull TextBuffer textColour, @Nullable TextBuffer backgroundColour, | ||||
|         @Nonnull Palette palette, boolean greyscale, float leftMarginSize, float rightMarginSize | ||||
|     ) | ||||
|     { | ||||
|         bindFont(); | ||||
|  | ||||
|         VertexConsumerProvider.Immediate renderer = MinecraftClient.getInstance().getBufferBuilders().getEntityVertexConsumers(); | ||||
|         drawString( IDENTITY, ((VertexConsumerProvider) renderer).getBuffer( TYPE ), x, y, text, textColour, backgroundColour, palette, greyscale, leftMarginSize, rightMarginSize ); | ||||
|         renderer.draw(); | ||||
|     } | ||||
|  | ||||
|     public static void drawTerminalWithoutCursor( | ||||
|         @Nonnull Matrix4f transform, @Nonnull VertexConsumer buffer, float x, float y, | ||||
|         @Nonnull Terminal terminal, boolean greyscale, | ||||
|         float topMarginSize, float bottomMarginSize, float leftMarginSize, float rightMarginSize | ||||
|     ) | ||||
|     { | ||||
|         Palette palette = terminal.getPalette(); | ||||
|         int height = terminal.getHeight(); | ||||
|  | ||||
|         // Top and bottom margins | ||||
|         drawBackground( | ||||
|             transform, buffer, x, y - topMarginSize, | ||||
|             terminal.getBackgroundColourLine( 0 ), palette, greyscale, | ||||
|             leftMarginSize, rightMarginSize, topMarginSize | ||||
|         ); | ||||
|  | ||||
|         drawBackground( | ||||
|             transform, buffer, x, y + height * FONT_HEIGHT, | ||||
|             terminal.getBackgroundColourLine( height - 1 ), palette, greyscale, | ||||
|             leftMarginSize, rightMarginSize, bottomMarginSize | ||||
|         ); | ||||
|  | ||||
|         // The main text | ||||
|         for( int i = 0; i < height; i++ ) | ||||
|         { | ||||
|             drawString( | ||||
|                 transform, buffer, x, y + FixedWidthFontRenderer.FONT_HEIGHT * i, | ||||
|                 terminal.getLine( i ), terminal.getTextColourLine( i ), terminal.getBackgroundColourLine( i ), | ||||
|                 palette, greyscale, leftMarginSize, rightMarginSize | ||||
|             ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static void drawCursor( | ||||
|         @Nonnull Matrix4f transform, @Nonnull VertexConsumer buffer, float x, float y, | ||||
|         @Nonnull Terminal terminal, boolean greyscale | ||||
|     ) | ||||
|     { | ||||
|         Palette palette = terminal.getPalette(); | ||||
|         int width = terminal.getWidth(); | ||||
|         int height = terminal.getHeight(); | ||||
|  | ||||
|         int cursorX = terminal.getCursorX(); | ||||
|         int cursorY = terminal.getCursorY(); | ||||
|         if( terminal.getCursorBlink() && cursorX >= 0 && cursorX < width && cursorY >= 0 && cursorY < height && FrameInfo.getGlobalCursorBlink() ) | ||||
|         { | ||||
|             double[] colour = palette.getColour( 15 - terminal.getTextColour() ); | ||||
|             float r, g, b; | ||||
|             if( greyscale ) | ||||
|             { | ||||
|                 r = g = b = toGreyscale( colour ); | ||||
|             } | ||||
|             else | ||||
|             { | ||||
|                 r = (float) colour[0]; | ||||
|                 g = (float) colour[1]; | ||||
|                 b = (float) colour[2]; | ||||
|             } | ||||
|  | ||||
|             drawChar( transform, buffer, x + cursorX * FONT_WIDTH, y + cursorY * FONT_HEIGHT, '_', r, g, b ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static void drawTerminal( | ||||
|         @Nonnull Matrix4f transform, @Nonnull VertexConsumer buffer, float x, float y, | ||||
|         @Nonnull Terminal terminal, boolean greyscale, | ||||
|         float topMarginSize, float bottomMarginSize, float leftMarginSize, float rightMarginSize | ||||
|     ) | ||||
|     { | ||||
|         drawTerminalWithoutCursor( transform, buffer, x, y, terminal, greyscale, topMarginSize, bottomMarginSize, leftMarginSize, rightMarginSize ); | ||||
|         drawCursor( transform, buffer, x, y, terminal, greyscale ); | ||||
|     } | ||||
|  | ||||
|     public static void drawTerminal( | ||||
|         @Nonnull Matrix4f transform, float x, float y, @Nonnull Terminal terminal, boolean greyscale, | ||||
|         float topMarginSize, float bottomMarginSize, float leftMarginSize, float rightMarginSize | ||||
|     ) | ||||
|     { | ||||
|         bindFont(); | ||||
|  | ||||
|         VertexConsumerProvider.Immediate renderer = MinecraftClient.getInstance().getBufferBuilders().getEntityVertexConsumers(); | ||||
|         VertexConsumer buffer = renderer.getBuffer( TYPE ); | ||||
|         drawTerminal( transform, buffer, x, y, terminal, greyscale, topMarginSize, bottomMarginSize, leftMarginSize, rightMarginSize ); | ||||
|         renderer.draw( TYPE ); | ||||
|     } | ||||
|  | ||||
|     public static void drawTerminal( | ||||
|         float x, float y, @Nonnull Terminal terminal, boolean greyscale, | ||||
|         float topMarginSize, float bottomMarginSize, float leftMarginSize, float rightMarginSize | ||||
|     ) | ||||
|     { | ||||
|         drawTerminal( IDENTITY, x, y, terminal, greyscale, topMarginSize, bottomMarginSize, leftMarginSize, rightMarginSize ); | ||||
|     } | ||||
|  | ||||
|     public static void drawEmptyTerminal( @Nonnull Matrix4f transform, @Nonnull VertexConsumerProvider renderer, float x, float y, float width, float height ) | ||||
|     { | ||||
|         Colour colour = Colour.BLACK; | ||||
|         drawQuad( transform, renderer.getBuffer( TYPE ), x, y, width, height, colour.getR(), colour.getG(), colour.getB() ); | ||||
|     } | ||||
|  | ||||
|     public static void drawEmptyTerminal( @Nonnull Matrix4f transform, float x, float y, float width, float height ) | ||||
|     { | ||||
|         bindFont(); | ||||
|  | ||||
|         VertexConsumerProvider.Immediate renderer = MinecraftClient.getInstance().getBufferBuilders().getEntityVertexConsumers(); | ||||
|         drawEmptyTerminal( transform, renderer, x, y, width, height ); | ||||
|         renderer.draw(); | ||||
|     } | ||||
|  | ||||
|     public static void drawEmptyTerminal( float x, float y, float width, float height ) | ||||
|     { | ||||
|         drawEmptyTerminal( IDENTITY, x, y, width, height ); | ||||
|     } | ||||
|  | ||||
|     public static void drawBlocker( @Nonnull Matrix4f transform, @Nonnull VertexConsumerProvider renderer, float x, float y, float width, float height ) | ||||
|     { | ||||
|         Colour colour = Colour.BLACK; | ||||
|         drawQuad( transform, renderer.getBuffer( Type.BLOCKER ), x, y, width, height, colour.getR(), colour.getG(), colour.getB() ); | ||||
|     } | ||||
|  | ||||
|     private static void bindFont() | ||||
|     { | ||||
|         MinecraftClient.getInstance().getTextureManager().bindTexture( FONT ); | ||||
|         RenderSystem.texParameter( GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP ); | ||||
|     } | ||||
|  | ||||
|     private static final class Type extends RenderPhase | ||||
|     { | ||||
|         private static final int GL_MODE = GL11.GL_TRIANGLES; | ||||
|  | ||||
|         private static final VertexFormat FORMAT = VertexFormats.POSITION_COLOR_TEXTURE; | ||||
|  | ||||
|         static final RenderLayer MAIN = RenderLayer.of( | ||||
|             "terminal_font", FORMAT, GL_MODE, 1024, | ||||
|             false, false, // useDelegate, needsSorting | ||||
|             RenderLayer.MultiPhaseParameters.builder() | ||||
|                 .texture( new RenderPhase.Texture( FONT, false, false ) ) // blur, minimap | ||||
|                 .alpha( ONE_TENTH_ALPHA ) | ||||
|                 .lightmap( DISABLE_LIGHTMAP ) | ||||
|                 .writeMaskState( COLOR_MASK ) | ||||
|                 .build( false ) | ||||
|         ); | ||||
|  | ||||
|         static final RenderLayer BLOCKER = RenderLayer.of( | ||||
|             "terminal_blocker", FORMAT, GL_MODE, 256, | ||||
|             false, false, // useDelegate, needsSorting | ||||
|             RenderLayer.MultiPhaseParameters.builder() | ||||
|                 .texture( new RenderPhase.Texture( FONT, false, false ) ) // blur, minimap | ||||
|                 .alpha( ONE_TENTH_ALPHA ) | ||||
|                 .writeMaskState( DEPTH_MASK ) | ||||
|                 .lightmap( DISABLE_LIGHTMAP ) | ||||
|                 .build( false ) | ||||
|         ); | ||||
|  | ||||
|         private Type( String name, Runnable setup, Runnable destroy ) | ||||
|         { | ||||
|             super( name, setup, destroy ); | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										159
									
								
								src/main/java/dan200/computercraft/client/gui/GuiComputer.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										159
									
								
								src/main/java/dan200/computercraft/client/gui/GuiComputer.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,159 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.gui; | ||||
|  | ||||
| import com.mojang.blaze3d.systems.RenderSystem; | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import dan200.computercraft.client.gui.widgets.WidgetTerminal; | ||||
| import dan200.computercraft.client.gui.widgets.WidgetWrapper; | ||||
| import dan200.computercraft.client.render.ComputerBorderRenderer; | ||||
| import dan200.computercraft.shared.computer.core.ClientComputer; | ||||
| import dan200.computercraft.shared.computer.core.ComputerFamily; | ||||
| import dan200.computercraft.shared.computer.inventory.ContainerComputer; | ||||
| import dan200.computercraft.shared.computer.inventory.ContainerComputerBase; | ||||
| import dan200.computercraft.shared.computer.inventory.ContainerViewComputer; | ||||
| import dan200.computercraft.shared.pocket.inventory.ContainerPocketComputer; | ||||
| import net.minecraft.client.gui.screen.ingame.HandledScreen; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.entity.player.PlayerInventory; | ||||
| import net.minecraft.text.Text; | ||||
| import org.lwjgl.glfw.GLFW; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| import static dan200.computercraft.client.render.ComputerBorderRenderer.BORDER; | ||||
| import static dan200.computercraft.client.render.ComputerBorderRenderer.MARGIN; | ||||
|  | ||||
| public final class GuiComputer<T extends ContainerComputerBase> extends HandledScreen<T> | ||||
| { | ||||
|     private final ComputerFamily family; | ||||
|     private final ClientComputer computer; | ||||
|     private final int termWidth; | ||||
|     private final int termHeight; | ||||
|  | ||||
|     private WidgetTerminal terminal; | ||||
|     private WidgetWrapper terminalWrapper; | ||||
|  | ||||
|     private GuiComputer( | ||||
|         T container, PlayerInventory player, Text title, int termWidth, int termHeight | ||||
|     ) | ||||
|     { | ||||
|         super( container, player, title ); | ||||
|         family = container.getFamily(); | ||||
|         computer = (ClientComputer) container.getComputer(); | ||||
|         this.termWidth = termWidth; | ||||
|         this.termHeight = termHeight; | ||||
|         terminal = null; | ||||
|     } | ||||
|  | ||||
|     public static GuiComputer<ContainerComputer> create( ContainerComputer container, PlayerInventory inventory, Text component ) | ||||
|     { | ||||
|         return new GuiComputer<>( | ||||
|             container, inventory, component, | ||||
|             ComputerCraft.computerTermWidth, ComputerCraft.computerTermHeight | ||||
|         ); | ||||
|     } | ||||
|  | ||||
|     public static GuiComputer<ContainerPocketComputer> createPocket( ContainerPocketComputer container, PlayerInventory inventory, Text component ) | ||||
|     { | ||||
|         return new GuiComputer<>( | ||||
|             container, inventory, component, | ||||
|             ComputerCraft.pocketTermWidth, ComputerCraft.pocketTermHeight | ||||
|         ); | ||||
|     } | ||||
|  | ||||
|     public static GuiComputer<ContainerViewComputer> createView( ContainerViewComputer container, PlayerInventory inventory, Text component ) | ||||
|     { | ||||
|         return new GuiComputer<>( | ||||
|             container, inventory, component, | ||||
|             container.getWidth(), container.getHeight() | ||||
|         ); | ||||
|     } | ||||
|  | ||||
|  | ||||
|     @Override | ||||
|     protected void init() | ||||
|     { | ||||
|         client.keyboard.setRepeatEvents( true ); | ||||
|  | ||||
|         int termPxWidth = termWidth * FixedWidthFontRenderer.FONT_WIDTH; | ||||
|         int termPxHeight = termHeight * FixedWidthFontRenderer.FONT_HEIGHT; | ||||
|  | ||||
|         backgroundWidth = termPxWidth + MARGIN * 2 + BORDER * 2; | ||||
|         backgroundHeight = termPxHeight + MARGIN * 2 + BORDER * 2; | ||||
|  | ||||
|         super.init(); | ||||
|  | ||||
|         terminal = new WidgetTerminal( client, () -> computer, termWidth, termHeight, MARGIN, MARGIN, MARGIN, MARGIN ); | ||||
|         terminalWrapper = new WidgetWrapper( terminal, MARGIN + BORDER + x, MARGIN + BORDER + y, termPxWidth, termPxHeight ); | ||||
|  | ||||
|         children.add( terminalWrapper ); | ||||
|         setFocused( terminalWrapper ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void removed() | ||||
|     { | ||||
|         super.removed(); | ||||
|         children.remove( terminal ); | ||||
|         terminal = null; | ||||
|         client.keyboard.setRepeatEvents( false ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void tick() | ||||
|     { | ||||
|         super.tick(); | ||||
|         terminal.update(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean keyPressed( int key, int scancode, int modifiers ) | ||||
|     { | ||||
|         // Forward the tab key to the terminal, rather than moving between controls. | ||||
|         if( key == GLFW.GLFW_KEY_TAB && getFocused() != null && getFocused() == terminalWrapper ) | ||||
|         { | ||||
|             return getFocused().keyPressed( key, scancode, modifiers ); | ||||
|         } | ||||
|  | ||||
|         return super.keyPressed( key, scancode, modifiers ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void drawBackground( @Nonnull MatrixStack stack, float partialTicks, int mouseX, int mouseY ) | ||||
|     { | ||||
|         // Draw terminal | ||||
|         terminal.draw( terminalWrapper.getX(), terminalWrapper.getY() ); | ||||
|  | ||||
|         // Draw a border around the terminal | ||||
|         RenderSystem.color4f( 1, 1, 1, 1 ); | ||||
|         client.getTextureManager().bindTexture( ComputerBorderRenderer.getTexture( family ) ); | ||||
|         ComputerBorderRenderer.render( | ||||
|             terminalWrapper.getX() - MARGIN, terminalWrapper.getY() - MARGIN, getZOffset(), | ||||
|             terminalWrapper.getWidth() + MARGIN * 2, terminalWrapper.getHeight() + MARGIN * 2 | ||||
|         ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void render( @Nonnull MatrixStack stack, int mouseX, int mouseY, float partialTicks ) | ||||
|     { | ||||
|         super.render( stack, mouseX, mouseY, partialTicks ); | ||||
|         drawMouseoverTooltip( stack, mouseX, mouseY ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean mouseDragged( double x, double y, int button, double deltaX, double deltaY ) | ||||
|     { | ||||
|         return (getFocused() != null && getFocused().mouseDragged( x, y, button, deltaX, deltaY )) | ||||
|             || super.mouseDragged( x, y, button, deltaX, deltaY ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     protected void drawForeground( @Nonnull MatrixStack transform, int mouseX, int mouseY ) | ||||
|     { | ||||
|         // Skip rendering labels. | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,41 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.gui; | ||||
|  | ||||
| import com.mojang.blaze3d.systems.RenderSystem; | ||||
| import dan200.computercraft.shared.peripheral.diskdrive.ContainerDiskDrive; | ||||
| import net.minecraft.client.gui.screen.ingame.HandledScreen; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.entity.player.PlayerInventory; | ||||
| import net.minecraft.text.Text; | ||||
| import net.minecraft.util.Identifier; | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| public class GuiDiskDrive extends HandledScreen<ContainerDiskDrive> | ||||
| { | ||||
|     private static final Identifier BACKGROUND = new Identifier( "computercraft", "textures/gui/disk_drive.png" ); | ||||
|  | ||||
|     public GuiDiskDrive( ContainerDiskDrive container, PlayerInventory player, Text title ) | ||||
|     { | ||||
|         super( container, player, title ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     protected void drawBackground( @Nonnull MatrixStack transform, float partialTicks, int mouseX, int mouseY ) | ||||
|     { | ||||
|         RenderSystem.color4f( 1.0F, 1.0F, 1.0F, 1.0F ); | ||||
|         client.getTextureManager().bindTexture( BACKGROUND ); | ||||
|         drawTexture( transform, x, y, 0, 0, backgroundWidth, backgroundHeight ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void render( @Nonnull MatrixStack transform, int mouseX, int mouseY, float partialTicks ) | ||||
|     { | ||||
|         renderBackground( transform ); | ||||
|         super.render( transform, mouseX, mouseY, partialTicks ); | ||||
|         drawMouseoverTooltip( transform, mouseX, mouseY ); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,51 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.gui; | ||||
|  | ||||
| import com.mojang.blaze3d.systems.RenderSystem; | ||||
| import dan200.computercraft.shared.peripheral.printer.ContainerPrinter; | ||||
| import net.minecraft.client.gui.screen.ingame.HandledScreen; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.entity.player.PlayerInventory; | ||||
| import net.minecraft.text.Text; | ||||
| import net.minecraft.util.Identifier; | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| public class GuiPrinter extends HandledScreen<ContainerPrinter> | ||||
| { | ||||
|     private static final Identifier BACKGROUND = new Identifier( "computercraft", "textures/gui/printer.png" ); | ||||
|  | ||||
|     public GuiPrinter( ContainerPrinter container, PlayerInventory player, Text title ) | ||||
|     { | ||||
|         super( container, player, title ); | ||||
|     } | ||||
|  | ||||
|     /*@Override | ||||
|     protected void drawGuiContainerForegroundLayer( int mouseX, int mouseY ) | ||||
|     { | ||||
|         String title = getTitle().getFormattedText(); | ||||
|         font.drawString( title, (xSize - font.getStringWidth( title )) / 2.0f, 6, 0x404040 ); | ||||
|         font.drawString( I18n.format( "container.inventory" ), 8, ySize - 96 + 2, 0x404040 ); | ||||
|     }*/ | ||||
|  | ||||
|     @Override | ||||
|     protected void drawBackground( @Nonnull MatrixStack transform, float partialTicks, int mouseX, int mouseY ) | ||||
|     { | ||||
|         RenderSystem.color4f( 1.0F, 1.0F, 1.0F, 1.0F ); | ||||
|         client.getTextureManager().bindTexture( BACKGROUND ); | ||||
|         drawTexture( transform, x, y, 0, 0, backgroundWidth, backgroundHeight ); | ||||
|  | ||||
|         if( getScreenHandler().isPrinting() ) drawTexture( transform, x + 34, y + 21, 176, 0, 25, 45 ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void render( @Nonnull MatrixStack stack, int mouseX, int mouseY, float partialTicks ) | ||||
|     { | ||||
|         renderBackground( stack ); | ||||
|         super.render( stack, mouseX, mouseY, partialTicks ); | ||||
|         drawMouseoverTooltip( stack, mouseX, mouseY ); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										123
									
								
								src/main/java/dan200/computercraft/client/gui/GuiPrintout.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										123
									
								
								src/main/java/dan200/computercraft/client/gui/GuiPrintout.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,123 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.gui; | ||||
|  | ||||
| import com.mojang.blaze3d.systems.RenderSystem; | ||||
| import dan200.computercraft.core.terminal.TextBuffer; | ||||
| import dan200.computercraft.shared.common.ContainerHeldItem; | ||||
| import dan200.computercraft.shared.media.items.ItemPrintout; | ||||
| import net.minecraft.client.MinecraftClient; | ||||
| import net.minecraft.client.gui.screen.ingame.HandledScreen; | ||||
| import net.minecraft.client.render.VertexConsumerProvider; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.entity.player.PlayerInventory; | ||||
| import net.minecraft.text.Text; | ||||
| import net.minecraft.util.math.Matrix4f; | ||||
| import org.lwjgl.glfw.GLFW; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| import static dan200.computercraft.client.render.PrintoutRenderer.*; | ||||
|  | ||||
| public class GuiPrintout extends HandledScreen<ContainerHeldItem> | ||||
| { | ||||
|     private final boolean m_book; | ||||
|     private final int m_pages; | ||||
|     private final TextBuffer[] m_text; | ||||
|     private final TextBuffer[] m_colours; | ||||
|     private int m_page; | ||||
|  | ||||
|     public GuiPrintout( ContainerHeldItem container, PlayerInventory player, Text title ) | ||||
|     { | ||||
|         super( container, player, title ); | ||||
|  | ||||
|         backgroundHeight = Y_SIZE; | ||||
|  | ||||
|         String[] text = ItemPrintout.getText( container.getStack() ); | ||||
|         m_text = new TextBuffer[text.length]; | ||||
|         for( int i = 0; i < m_text.length; i++ ) m_text[i] = new TextBuffer( text[i] ); | ||||
|  | ||||
|         String[] colours = ItemPrintout.getColours( container.getStack() ); | ||||
|         m_colours = new TextBuffer[colours.length]; | ||||
|         for( int i = 0; i < m_colours.length; i++ ) m_colours[i] = new TextBuffer( colours[i] ); | ||||
|  | ||||
|         m_page = 0; | ||||
|         m_pages = Math.max( m_text.length / ItemPrintout.LINES_PER_PAGE, 1 ); | ||||
|         m_book = ((ItemPrintout) container.getStack().getItem()).getType() == ItemPrintout.Type.BOOK; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean keyPressed( int key, int scancode, int modifiers ) | ||||
|     { | ||||
|         if( super.keyPressed( key, scancode, modifiers ) ) return true; | ||||
|  | ||||
|         if( key == GLFW.GLFW_KEY_RIGHT ) | ||||
|         { | ||||
|             if( m_page < m_pages - 1 ) m_page++; | ||||
|             return true; | ||||
|         } | ||||
|  | ||||
|         if( key == GLFW.GLFW_KEY_LEFT ) | ||||
|         { | ||||
|             if( m_page > 0 ) m_page--; | ||||
|             return true; | ||||
|         } | ||||
|  | ||||
|         return false; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean mouseScrolled( double x, double y, double delta ) | ||||
|     { | ||||
|         if( super.mouseScrolled( x, y, delta ) ) return true; | ||||
|         if( delta < 0 ) | ||||
|         { | ||||
|             // Scroll up goes to the next page | ||||
|             if( m_page < m_pages - 1 ) m_page++; | ||||
|             return true; | ||||
|         } | ||||
|  | ||||
|         if( delta > 0 ) | ||||
|         { | ||||
|             // Scroll down goes to the previous page | ||||
|             if( m_page > 0 ) m_page--; | ||||
|             return true; | ||||
|         } | ||||
|  | ||||
|         return false; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     protected void drawBackground( @Nonnull MatrixStack transform, float partialTicks, int mouseX, int mouseY ) | ||||
|     { | ||||
|         // Draw the printout | ||||
|         RenderSystem.color4f( 1.0f, 1.0f, 1.0f, 1.0f ); | ||||
|         RenderSystem.enableDepthTest(); | ||||
|  | ||||
|         VertexConsumerProvider.Immediate renderer = MinecraftClient.getInstance().getBufferBuilders().getEntityVertexConsumers(); | ||||
|         Matrix4f matrix = transform.peek().getModel(); | ||||
|         drawBorder( matrix, renderer, x, y, getZOffset(), m_page, m_pages, m_book ); | ||||
|         drawText( matrix, renderer, x + X_TEXT_MARGIN, y + Y_TEXT_MARGIN, ItemPrintout.LINES_PER_PAGE * m_page, m_text, m_colours ); | ||||
|         renderer.draw(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void render( @Nonnull MatrixStack stack, int mouseX, int mouseY, float partialTicks ) | ||||
|     { | ||||
|         // We must take the background further back in order to not overlap with our printed pages. | ||||
|         setZOffset( getZOffset() - 1 ); | ||||
|         renderBackground( stack ); | ||||
|         setZOffset( getZOffset() + 1 ); | ||||
|  | ||||
|         super.render( stack, mouseX, mouseY, partialTicks ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     protected void drawForeground( @Nonnull MatrixStack transform, int mouseX, int mouseY ) | ||||
|     { | ||||
|         // Skip rendering labels. | ||||
|     } | ||||
| } | ||||
							
								
								
									
										144
									
								
								src/main/java/dan200/computercraft/client/gui/GuiTurtle.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										144
									
								
								src/main/java/dan200/computercraft/client/gui/GuiTurtle.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,144 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.gui; | ||||
|  | ||||
| import com.mojang.blaze3d.systems.RenderSystem; | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import dan200.computercraft.client.gui.widgets.WidgetTerminal; | ||||
| import dan200.computercraft.client.gui.widgets.WidgetWrapper; | ||||
| import dan200.computercraft.shared.computer.core.ClientComputer; | ||||
| import dan200.computercraft.shared.computer.core.ComputerFamily; | ||||
| import dan200.computercraft.shared.turtle.inventory.ContainerTurtle; | ||||
| import net.minecraft.client.gui.screen.ingame.HandledScreen; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.entity.player.PlayerInventory; | ||||
| import net.minecraft.text.Text; | ||||
| import net.minecraft.util.Identifier; | ||||
| import org.lwjgl.glfw.GLFW; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| public class GuiTurtle extends HandledScreen<ContainerTurtle> | ||||
| { | ||||
|     private static final Identifier BACKGROUND_NORMAL = new Identifier( "computercraft", "textures/gui/turtle_normal.png" ); | ||||
|     private static final Identifier BACKGROUND_ADVANCED = new Identifier( "computercraft", "textures/gui/turtle_advanced.png" ); | ||||
|  | ||||
|     private ContainerTurtle m_container; | ||||
|  | ||||
|     private final ComputerFamily m_family; | ||||
|     private final ClientComputer m_computer; | ||||
|  | ||||
|     private WidgetTerminal terminal; | ||||
|     private WidgetWrapper terminalWrapper; | ||||
|  | ||||
|     public GuiTurtle( ContainerTurtle container, PlayerInventory player, Text title ) | ||||
|     { | ||||
|         super( container, player, title ); | ||||
|  | ||||
|         m_container = container; | ||||
|         m_family = container.getFamily(); | ||||
|         m_computer = (ClientComputer) container.getComputer(); | ||||
|  | ||||
|         backgroundWidth = 254; | ||||
|         backgroundHeight = 217; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     protected void init() | ||||
|     { | ||||
|         super.init(); | ||||
|         client.keyboard.setRepeatEvents( true ); | ||||
|  | ||||
|         int termPxWidth = ComputerCraft.turtleTermWidth * FixedWidthFontRenderer.FONT_WIDTH; | ||||
|         int termPxHeight = ComputerCraft.turtleTermHeight * FixedWidthFontRenderer.FONT_HEIGHT; | ||||
|  | ||||
|         terminal = new WidgetTerminal( | ||||
|             client, () -> m_computer, | ||||
|             ComputerCraft.turtleTermWidth, | ||||
|             ComputerCraft.turtleTermHeight, | ||||
|             2, 2, 2, 2 | ||||
|         ); | ||||
|         terminalWrapper = new WidgetWrapper( terminal, 2 + 8 + x, 2 + 8 + y, termPxWidth, termPxHeight ); | ||||
|  | ||||
|         children.add( terminalWrapper ); | ||||
|         setFocused( terminalWrapper ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void removed() | ||||
|     { | ||||
|         super.removed(); | ||||
|         children.remove( terminal ); | ||||
|         terminal = null; | ||||
|         client.keyboard.setRepeatEvents( false ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void tick() | ||||
|     { | ||||
|         super.tick(); | ||||
|         terminal.update(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean keyPressed( int key, int scancode, int modifiers ) | ||||
|     { | ||||
|         // Forward the tab key to the terminal, rather than moving between controls. | ||||
|         if( key == GLFW.GLFW_KEY_TAB && getFocused() != null && getFocused() == terminalWrapper ) | ||||
|         { | ||||
|             return getFocused().keyPressed( key, scancode, modifiers ); | ||||
|         } | ||||
|  | ||||
|         return super.keyPressed( key, scancode, modifiers ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     protected void drawBackground( @Nonnull MatrixStack transform, float partialTicks, int mouseX, int mouseY ) | ||||
|     { | ||||
|         // Draw term | ||||
|         Identifier texture = m_family == ComputerFamily.ADVANCED ? BACKGROUND_ADVANCED : BACKGROUND_NORMAL; | ||||
|         terminal.draw( terminalWrapper.getX(), terminalWrapper.getY() ); | ||||
|  | ||||
|         // Draw border/inventory | ||||
|         RenderSystem.color4f( 1.0F, 1.0F, 1.0F, 1.0F ); | ||||
|         client.getTextureManager().bindTexture( texture ); | ||||
|         drawTexture( transform, x, y, 0, 0, backgroundWidth, backgroundHeight ); | ||||
|  | ||||
|         // Draw selection slot | ||||
|         int slot = m_container.getSelectedSlot(); | ||||
|         if( slot >= 0 ) | ||||
|         { | ||||
|             int slotX = slot % 4; | ||||
|             int slotY = slot / 4; | ||||
|             drawTexture( transform, | ||||
|                 x + ContainerTurtle.TURTLE_START_X - 2 + slotX * 18, | ||||
|                 y + ContainerTurtle.PLAYER_START_Y - 2 + slotY * 18, | ||||
|                 0, 217, 24, 24 | ||||
|             ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void render( @Nonnull MatrixStack stack, int mouseX, int mouseY, float partialTicks ) | ||||
|     { | ||||
|         renderBackground( stack ); | ||||
|         super.render( stack, mouseX, mouseY, partialTicks ); | ||||
|         drawMouseoverTooltip( stack, mouseX, mouseY ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean mouseDragged( double x, double y, int button, double deltaX, double deltaY ) | ||||
|     { | ||||
|         return (getFocused() != null && getFocused().mouseDragged( x, y, button, deltaX, deltaY )) | ||||
|             || super.mouseDragged( x, y, button, deltaX, deltaY ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     protected void drawForeground( @Nonnull MatrixStack transform, int mouseX, int mouseY ) | ||||
|     { | ||||
|         // Skip rendering labels. | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,354 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.gui.widgets; | ||||
|  | ||||
| import dan200.computercraft.client.gui.FixedWidthFontRenderer; | ||||
| import dan200.computercraft.core.terminal.Terminal; | ||||
| import dan200.computercraft.shared.computer.core.ClientComputer; | ||||
| import dan200.computercraft.shared.computer.core.IComputer; | ||||
| import org.lwjgl.glfw.GLFW; | ||||
|  | ||||
| import java.util.BitSet; | ||||
| import java.util.function.Supplier; | ||||
| import net.minecraft.SharedConstants; | ||||
| import net.minecraft.client.MinecraftClient; | ||||
| import net.minecraft.client.gui.Element; | ||||
|  | ||||
| import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT; | ||||
| import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_WIDTH; | ||||
|  | ||||
| public class WidgetTerminal implements Element | ||||
| { | ||||
|     private static final float TERMINATE_TIME = 0.5f; | ||||
|  | ||||
|     private final MinecraftClient client; | ||||
|  | ||||
|     private boolean focused; | ||||
|  | ||||
|     private final Supplier<ClientComputer> computer; | ||||
|     private final int termWidth; | ||||
|     private final int termHeight; | ||||
|  | ||||
|     private float terminateTimer = -1; | ||||
|     private float rebootTimer = -1; | ||||
|     private float shutdownTimer = -1; | ||||
|  | ||||
|     private int lastMouseButton = -1; | ||||
|     private int lastMouseX = -1; | ||||
|     private int lastMouseY = -1; | ||||
|  | ||||
|     private final int leftMargin; | ||||
|     private final int rightMargin; | ||||
|     private final int topMargin; | ||||
|     private final int bottomMargin; | ||||
|  | ||||
|     private final BitSet keysDown = new BitSet( 256 ); | ||||
|  | ||||
|     public WidgetTerminal( MinecraftClient client, Supplier<ClientComputer> computer, int termWidth, int termHeight, int leftMargin, int rightMargin, int topMargin, int bottomMargin ) | ||||
|     { | ||||
|         this.client = client; | ||||
|         this.computer = computer; | ||||
|         this.termWidth = termWidth; | ||||
|         this.termHeight = termHeight; | ||||
|         this.leftMargin = leftMargin; | ||||
|         this.rightMargin = rightMargin; | ||||
|         this.topMargin = topMargin; | ||||
|         this.bottomMargin = bottomMargin; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean charTyped( char ch, int modifiers ) | ||||
|     { | ||||
|         if( ch >= 32 && ch <= 126 || ch >= 160 && ch <= 255 ) // printable chars in byte range | ||||
|         { | ||||
|             // Queue the "char" event | ||||
|             queueEvent( "char", Character.toString( ch ) ); | ||||
|         } | ||||
|  | ||||
|         return true; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean keyPressed( int key, int scancode, int modifiers ) | ||||
|     { | ||||
|         if( key == GLFW.GLFW_KEY_ESCAPE ) return false; | ||||
|         if( (modifiers & GLFW.GLFW_MOD_CONTROL) != 0 ) | ||||
|         { | ||||
|             switch( key ) | ||||
|             { | ||||
|                 case GLFW.GLFW_KEY_T: | ||||
|                     if( terminateTimer < 0 ) terminateTimer = 0; | ||||
|                     return true; | ||||
|                 case GLFW.GLFW_KEY_S: | ||||
|                     if( shutdownTimer < 0 ) shutdownTimer = 0; | ||||
|                     return true; | ||||
|                 case GLFW.GLFW_KEY_R: | ||||
|                     if( rebootTimer < 0 ) rebootTimer = 0; | ||||
|                     return true; | ||||
|  | ||||
|                 case GLFW.GLFW_KEY_V: | ||||
|                     // Ctrl+V for paste | ||||
|                     String clipboard = client.keyboard.getClipboard(); | ||||
|                     if( clipboard != null ) | ||||
|                     { | ||||
|                         // Clip to the first occurrence of \r or \n | ||||
|                         int newLineIndex1 = clipboard.indexOf( "\r" ); | ||||
|                         int newLineIndex2 = clipboard.indexOf( "\n" ); | ||||
|                         if( newLineIndex1 >= 0 && newLineIndex2 >= 0 ) | ||||
|                         { | ||||
|                             clipboard = clipboard.substring( 0, Math.min( newLineIndex1, newLineIndex2 ) ); | ||||
|                         } | ||||
|                         else if( newLineIndex1 >= 0 ) | ||||
|                         { | ||||
|                             clipboard = clipboard.substring( 0, newLineIndex1 ); | ||||
|                         } | ||||
|                         else if( newLineIndex2 >= 0 ) | ||||
|                         { | ||||
|                             clipboard = clipboard.substring( 0, newLineIndex2 ); | ||||
|                         } | ||||
|  | ||||
|                         // Filter the string | ||||
|                         clipboard = SharedConstants.stripInvalidChars( clipboard ); | ||||
|                         if( !clipboard.isEmpty() ) | ||||
|                         { | ||||
|                             // Clip to 512 characters and queue the event | ||||
|                             if( clipboard.length() > 512 ) clipboard = clipboard.substring( 0, 512 ); | ||||
|                             queueEvent( "paste", clipboard ); | ||||
|                         } | ||||
|  | ||||
|                         return true; | ||||
|                     } | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         if( key >= 0 && terminateTimer < 0 && rebootTimer < 0 && shutdownTimer < 0 ) | ||||
|         { | ||||
|             // Queue the "key" event and add to the down set | ||||
|             boolean repeat = keysDown.get( key ); | ||||
|             keysDown.set( key ); | ||||
|             IComputer computer = this.computer.get(); | ||||
|             if( computer != null ) computer.keyDown( key, repeat ); | ||||
|         } | ||||
|  | ||||
|         return true; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean keyReleased( int key, int scancode, int modifiers ) | ||||
|     { | ||||
|         // Queue the "key_up" event and remove from the down set | ||||
|         if( key >= 0 && keysDown.get( key ) ) | ||||
|         { | ||||
|             keysDown.set( key, false ); | ||||
|             IComputer computer = this.computer.get(); | ||||
|             if( computer != null ) computer.keyUp( key ); | ||||
|         } | ||||
|  | ||||
|         switch( key ) | ||||
|         { | ||||
|             case GLFW.GLFW_KEY_T: | ||||
|                 terminateTimer = -1; | ||||
|                 break; | ||||
|             case GLFW.GLFW_KEY_R: | ||||
|                 rebootTimer = -1; | ||||
|                 break; | ||||
|             case GLFW.GLFW_KEY_S: | ||||
|                 shutdownTimer = -1; | ||||
|                 break; | ||||
|             case GLFW.GLFW_KEY_LEFT_CONTROL: | ||||
|             case GLFW.GLFW_KEY_RIGHT_CONTROL: | ||||
|                 terminateTimer = rebootTimer = shutdownTimer = -1; | ||||
|                 break; | ||||
|         } | ||||
|  | ||||
|         return true; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean mouseClicked( double mouseX, double mouseY, int button ) | ||||
|     { | ||||
|         ClientComputer computer = this.computer.get(); | ||||
|         if( computer == null || !computer.isColour() || button < 0 || button > 2 ) return false; | ||||
|  | ||||
|         Terminal term = computer.getTerminal(); | ||||
|         if( term != null ) | ||||
|         { | ||||
|             int charX = (int) (mouseX / FONT_WIDTH); | ||||
|             int charY = (int) (mouseY / FONT_HEIGHT); | ||||
|             charX = Math.min( Math.max( charX, 0 ), term.getWidth() - 1 ); | ||||
|             charY = Math.min( Math.max( charY, 0 ), term.getHeight() - 1 ); | ||||
|  | ||||
|             computer.mouseClick( button + 1, charX + 1, charY + 1 ); | ||||
|  | ||||
|             lastMouseButton = button; | ||||
|             lastMouseX = charX; | ||||
|             lastMouseY = charY; | ||||
|         } | ||||
|  | ||||
|         return true; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean mouseReleased( double mouseX, double mouseY, int button ) | ||||
|     { | ||||
|         ClientComputer computer = this.computer.get(); | ||||
|         if( computer == null || !computer.isColour() || button < 0 || button > 2 ) return false; | ||||
|  | ||||
|         Terminal term = computer.getTerminal(); | ||||
|         if( term != null ) | ||||
|         { | ||||
|             int charX = (int) (mouseX / FONT_WIDTH); | ||||
|             int charY = (int) (mouseY / FONT_HEIGHT); | ||||
|             charX = Math.min( Math.max( charX, 0 ), term.getWidth() - 1 ); | ||||
|             charY = Math.min( Math.max( charY, 0 ), term.getHeight() - 1 ); | ||||
|  | ||||
|             if( lastMouseButton == button ) | ||||
|             { | ||||
|                 computer.mouseUp( lastMouseButton + 1, charX + 1, charY + 1 ); | ||||
|                 lastMouseButton = -1; | ||||
|             } | ||||
|  | ||||
|             lastMouseX = charX; | ||||
|             lastMouseY = charY; | ||||
|         } | ||||
|  | ||||
|         return false; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean mouseDragged( double mouseX, double mouseY, int button, double v2, double v3 ) | ||||
|     { | ||||
|         ClientComputer computer = this.computer.get(); | ||||
|         if( computer == null || !computer.isColour() || button < 0 || button > 2 ) return false; | ||||
|  | ||||
|         Terminal term = computer.getTerminal(); | ||||
|         if( term != null ) | ||||
|         { | ||||
|             int charX = (int) (mouseX / FONT_WIDTH); | ||||
|             int charY = (int) (mouseY / FONT_HEIGHT); | ||||
|             charX = Math.min( Math.max( charX, 0 ), term.getWidth() - 1 ); | ||||
|             charY = Math.min( Math.max( charY, 0 ), term.getHeight() - 1 ); | ||||
|  | ||||
|             if( button == lastMouseButton && (charX != lastMouseX || charY != lastMouseY) ) | ||||
|             { | ||||
|                 computer.mouseDrag( button + 1, charX + 1, charY + 1 ); | ||||
|                 lastMouseX = charX; | ||||
|                 lastMouseY = charY; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         return false; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean mouseScrolled( double mouseX, double mouseY, double delta ) | ||||
|     { | ||||
|         ClientComputer computer = this.computer.get(); | ||||
|         if( computer == null || !computer.isColour() || delta == 0 ) return false; | ||||
|  | ||||
|         Terminal term = computer.getTerminal(); | ||||
|         if( term != null ) | ||||
|         { | ||||
|             int charX = (int) (mouseX / FONT_WIDTH); | ||||
|             int charY = (int) (mouseY / FONT_HEIGHT); | ||||
|             charX = Math.min( Math.max( charX, 0 ), term.getWidth() - 1 ); | ||||
|             charY = Math.min( Math.max( charY, 0 ), term.getHeight() - 1 ); | ||||
|  | ||||
|             computer.mouseScroll( delta < 0 ? 1 : -1, charX + 1, charY + 1 ); | ||||
|  | ||||
|             lastMouseX = charX; | ||||
|             lastMouseY = charY; | ||||
|         } | ||||
|  | ||||
|         return true; | ||||
|     } | ||||
|  | ||||
|     public void update() | ||||
|     { | ||||
|         if( terminateTimer >= 0 && terminateTimer < TERMINATE_TIME && (terminateTimer += 0.05f) > TERMINATE_TIME ) | ||||
|         { | ||||
|             queueEvent( "terminate" ); | ||||
|         } | ||||
|  | ||||
|         if( shutdownTimer >= 0 && shutdownTimer < TERMINATE_TIME && (shutdownTimer += 0.05f) > TERMINATE_TIME ) | ||||
|         { | ||||
|             ClientComputer computer = this.computer.get(); | ||||
|             if( computer != null ) computer.shutdown(); | ||||
|         } | ||||
|  | ||||
|         if( rebootTimer >= 0 && rebootTimer < TERMINATE_TIME && (rebootTimer += 0.05f) > TERMINATE_TIME ) | ||||
|         { | ||||
|             ClientComputer computer = this.computer.get(); | ||||
|             if( computer != null ) computer.reboot(); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean changeFocus( boolean reversed ) | ||||
|     { | ||||
|         if( focused ) | ||||
|         { | ||||
|             // When blurring, we should make all keys go up | ||||
|             for( int key = 0; key < keysDown.size(); key++ ) | ||||
|             { | ||||
|                 if( keysDown.get( key ) ) queueEvent( "key_up", key ); | ||||
|             } | ||||
|             keysDown.clear(); | ||||
|  | ||||
|             // When blurring, we should make the last mouse button go up | ||||
|             if( lastMouseButton > 0 ) | ||||
|             { | ||||
|                 IComputer computer = this.computer.get(); | ||||
|                 if( computer != null ) computer.mouseUp( lastMouseButton + 1, lastMouseX + 1, lastMouseY + 1 ); | ||||
|                 lastMouseButton = -1; | ||||
|             } | ||||
|  | ||||
|             shutdownTimer = terminateTimer = rebootTimer = -1; | ||||
|         } | ||||
|         focused = !focused; | ||||
|         return true; | ||||
|     } | ||||
|  | ||||
|     public void draw( int originX, int originY ) | ||||
|     { | ||||
|         synchronized( computer ) | ||||
|         { | ||||
|             // Draw the screen contents | ||||
|             ClientComputer computer = this.computer.get(); | ||||
|             Terminal terminal = computer != null ? computer.getTerminal() : null; | ||||
|             if( terminal != null ) | ||||
|             { | ||||
|                 FixedWidthFontRenderer.drawTerminal( originX, originY, terminal, !computer.isColour(), topMargin, bottomMargin, leftMargin, rightMargin ); | ||||
|             } | ||||
|             else | ||||
|             { | ||||
|                 FixedWidthFontRenderer.drawEmptyTerminal( | ||||
|                     originX - leftMargin, originY - rightMargin, | ||||
|                     termWidth * FONT_WIDTH + leftMargin + rightMargin, | ||||
|                     termHeight * FONT_HEIGHT + topMargin + bottomMargin | ||||
|                 ); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     private void queueEvent( String event ) | ||||
|     { | ||||
|         ClientComputer computer = this.computer.get(); | ||||
|         if( computer != null ) computer.queueEvent( event ); | ||||
|     } | ||||
|  | ||||
|     private void queueEvent( String event, Object... args ) | ||||
|     { | ||||
|         ClientComputer computer = this.computer.get(); | ||||
|         if( computer != null ) computer.queueEvent( event, args ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean isMouseOver( double x, double y ) | ||||
|     { | ||||
|         return true; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,105 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.gui.widgets; | ||||
|  | ||||
| import net.minecraft.client.gui.Element; | ||||
|  | ||||
| public class WidgetWrapper implements Element | ||||
| { | ||||
|     private final Element listener; | ||||
|     private final int x; | ||||
|     private final int y; | ||||
|     private final int width; | ||||
|     private final int height; | ||||
|  | ||||
|     public WidgetWrapper( Element listener, int x, int y, int width, int height ) | ||||
|     { | ||||
|         this.listener = listener; | ||||
|         this.x = x; | ||||
|         this.y = y; | ||||
|         this.width = width; | ||||
|         this.height = height; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean changeFocus( boolean b ) | ||||
|     { | ||||
|         return listener.changeFocus( b ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean mouseClicked( double x, double y, int button ) | ||||
|     { | ||||
|         double dx = x - this.x, dy = y - this.y; | ||||
|         return dx >= 0 && dx < width && dy >= 0 && dy < height && listener.mouseClicked( dx, dy, button ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean mouseReleased( double x, double y, int button ) | ||||
|     { | ||||
|         double dx = x - this.x, dy = y - this.y; | ||||
|         return dx >= 0 && dx < width && dy >= 0 && dy < height && listener.mouseReleased( dx, dy, button ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean mouseDragged( double x, double y, int button, double deltaX, double deltaY ) | ||||
|     { | ||||
|         double dx = x - this.x, dy = y - this.y; | ||||
|         return dx >= 0 && dx < width && dy >= 0 && dy < height && listener.mouseDragged( dx, dy, button, deltaX, deltaY ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean mouseScrolled( double x, double y, double delta ) | ||||
|     { | ||||
|         double dx = x - this.x, dy = y - this.y; | ||||
|         return dx >= 0 && dx < width && dy >= 0 && dy < height && listener.mouseScrolled( dx, dy, delta ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean keyPressed( int key, int scancode, int modifiers ) | ||||
|     { | ||||
|         return listener.keyPressed( key, scancode, modifiers ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean keyReleased( int key, int scancode, int modifiers ) | ||||
|     { | ||||
|         return listener.keyReleased( key, scancode, modifiers ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean charTyped( char character, int modifiers ) | ||||
|     { | ||||
|         return listener.charTyped( character, modifiers ); | ||||
|     } | ||||
|  | ||||
|     public int getX() | ||||
|     { | ||||
|         return x; | ||||
|     } | ||||
|  | ||||
|     public int getY() | ||||
|     { | ||||
|         return y; | ||||
|     } | ||||
|  | ||||
|     public int getWidth() | ||||
|     { | ||||
|         return width; | ||||
|     } | ||||
|  | ||||
|     public int getHeight() | ||||
|     { | ||||
|         return height; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean isMouseOver( double x, double y ) | ||||
|     { | ||||
|         double dx = x - this.x, dy = y - this.y; | ||||
|         return dx >= 0 && dx < width && dy >= 0 && dy < height; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,109 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.proxy; | ||||
|  | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import dan200.computercraft.client.gui.*; | ||||
| import dan200.computercraft.client.render.TileEntityMonitorRenderer; | ||||
| import dan200.computercraft.client.render.TileEntityTurtleRenderer; | ||||
| import dan200.computercraft.client.render.TurtlePlayerRenderer; | ||||
| import dan200.computercraft.shared.Registry; | ||||
| import dan200.computercraft.shared.common.IColouredItem; | ||||
| import dan200.computercraft.shared.computer.inventory.ContainerComputer; | ||||
| import dan200.computercraft.shared.computer.inventory.ContainerViewComputer; | ||||
| import dan200.computercraft.shared.peripheral.monitor.ClientMonitor; | ||||
| import dan200.computercraft.shared.pocket.inventory.ContainerPocketComputer; | ||||
| import dan200.computercraft.shared.pocket.items.ItemPocketComputer; | ||||
| import net.minecraft.client.gui.screen.ingame.HandledScreens; | ||||
| import net.minecraft.client.item.ModelPredicateProvider; | ||||
| import net.minecraft.client.item.ModelPredicateProviderRegistry; | ||||
| import net.minecraft.client.render.RenderLayer; | ||||
| import net.minecraft.client.render.RenderLayers; | ||||
| import net.minecraft.item.Item; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraftforge.api.distmarker.Dist; | ||||
| import net.minecraftforge.event.world.WorldEvent; | ||||
| import net.minecraftforge.eventbus.api.SubscribeEvent; | ||||
| import net.minecraftforge.fml.client.registry.ClientRegistry; | ||||
| import net.minecraftforge.fml.client.registry.RenderingRegistry; | ||||
| import net.minecraftforge.fml.common.Mod; | ||||
| import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; | ||||
|  | ||||
| import java.util.function.Supplier; | ||||
|  | ||||
| @Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD ) | ||||
| public final class ComputerCraftProxyClient | ||||
| { | ||||
|     @SubscribeEvent | ||||
|     public static void setupClient( FMLClientSetupEvent event ) | ||||
|     { | ||||
|         registerContainers(); | ||||
|  | ||||
|         // While turtles themselves are not transparent, their upgrades may be. | ||||
|         RenderLayers.setRenderLayer( Registry.ModBlocks.TURTLE_NORMAL.get(), RenderLayer.getTranslucent() ); | ||||
|         RenderLayers.setRenderLayer( Registry.ModBlocks.TURTLE_ADVANCED.get(), RenderLayer.getTranslucent() ); | ||||
|  | ||||
|         // Monitors' textures have transparent fronts and so count as cutouts. | ||||
|         RenderLayers.setRenderLayer( Registry.ModBlocks.MONITOR_NORMAL.get(), RenderLayer.getCutout() ); | ||||
|         RenderLayers.setRenderLayer( Registry.ModBlocks.MONITOR_ADVANCED.get(), RenderLayer.getCutout() ); | ||||
|  | ||||
|         // Setup TESRs | ||||
|         ClientRegistry.bindTileEntityRenderer( Registry.ModTiles.MONITOR_NORMAL.get(), TileEntityMonitorRenderer::new ); | ||||
|         ClientRegistry.bindTileEntityRenderer( Registry.ModTiles.MONITOR_ADVANCED.get(), TileEntityMonitorRenderer::new ); | ||||
|         ClientRegistry.bindTileEntityRenderer( Registry.ModTiles.TURTLE_NORMAL.get(), TileEntityTurtleRenderer::new ); | ||||
|         ClientRegistry.bindTileEntityRenderer( Registry.ModTiles.TURTLE_ADVANCED.get(), TileEntityTurtleRenderer::new ); | ||||
|         // TODO: ClientRegistry.bindTileEntityRenderer( TileCable.FACTORY, x -> new TileEntityCableRenderer() ); | ||||
|  | ||||
|         RenderingRegistry.registerEntityRenderingHandler( Registry.ModEntities.TURTLE_PLAYER.get(), TurtlePlayerRenderer::new ); | ||||
|  | ||||
|         registerItemProperty( "state", | ||||
|             ( stack, world, player ) -> ItemPocketComputer.getState( stack ).ordinal(), | ||||
|             Registry.ModItems.POCKET_COMPUTER_NORMAL, Registry.ModItems.POCKET_COMPUTER_ADVANCED | ||||
|         ); | ||||
|         registerItemProperty( "state", | ||||
|             ( stack, world, player ) -> IColouredItem.getColourBasic( stack ) != -1 ? 1 : 0, | ||||
|             Registry.ModItems.POCKET_COMPUTER_NORMAL, Registry.ModItems.POCKET_COMPUTER_ADVANCED | ||||
|         ); | ||||
|     } | ||||
|  | ||||
|     @SafeVarargs | ||||
|     private static void registerItemProperty( String name, ModelPredicateProvider getter, Supplier<? extends Item>... items ) | ||||
|     { | ||||
|         Identifier id = new Identifier( ComputerCraft.MOD_ID, name ); | ||||
|         for( Supplier<? extends Item> item : items ) | ||||
|         { | ||||
|             ModelPredicateProviderRegistry.register( item.get(), id, getter ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     private static void registerContainers() | ||||
|     { | ||||
|         // My IDE doesn't think so, but we do actually need these generics. | ||||
|  | ||||
|         HandledScreens.<ContainerComputer, GuiComputer<ContainerComputer>>register( Registry.ModContainers.COMPUTER.get(), GuiComputer::create ); | ||||
|         HandledScreens.<ContainerPocketComputer, GuiComputer<ContainerPocketComputer>>register( Registry.ModContainers.POCKET_COMPUTER.get(), GuiComputer::createPocket ); | ||||
|         HandledScreens.register( Registry.ModContainers.TURTLE.get(), GuiTurtle::new ); | ||||
|  | ||||
|         HandledScreens.register( Registry.ModContainers.PRINTER.get(), GuiPrinter::new ); | ||||
|         HandledScreens.register( Registry.ModContainers.DISK_DRIVE.get(), GuiDiskDrive::new ); | ||||
|         HandledScreens.register( Registry.ModContainers.PRINTOUT.get(), GuiPrintout::new ); | ||||
|  | ||||
|         HandledScreens.<ContainerViewComputer, GuiComputer<ContainerViewComputer>>register( Registry.ModContainers.VIEW_COMPUTER.get(), GuiComputer::createView ); | ||||
|     } | ||||
|  | ||||
|     @Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT ) | ||||
|     public static final class ForgeHandlers | ||||
|     { | ||||
|         @SubscribeEvent | ||||
|         public static void onWorldUnload( WorldEvent.Unload event ) | ||||
|         { | ||||
|             if( event.getWorld().isClient() ) | ||||
|             { | ||||
|                 ClientMonitor.destroyAll(); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,78 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import dan200.computercraft.shared.Registry; | ||||
| import dan200.computercraft.shared.peripheral.modem.wired.BlockCable; | ||||
| import dan200.computercraft.shared.peripheral.modem.wired.CableShapes; | ||||
| import dan200.computercraft.shared.util.WorldUtil; | ||||
| import net.minecraft.block.BlockState; | ||||
| import net.minecraft.client.render.Camera; | ||||
| import net.minecraft.client.render.RenderLayer; | ||||
| import net.minecraft.client.render.VertexConsumer; | ||||
| import net.minecraft.entity.Entity; | ||||
| import net.minecraft.util.hit.BlockHitResult; | ||||
| import net.minecraft.util.math.BlockPos; | ||||
| import net.minecraft.util.math.Matrix4f; | ||||
| import net.minecraft.util.math.Vec3d; | ||||
| import net.minecraft.util.shape.VoxelShape; | ||||
| import net.minecraft.world.World; | ||||
| import net.minecraftforge.api.distmarker.Dist; | ||||
| import net.minecraftforge.client.event.DrawHighlightEvent; | ||||
| import net.minecraftforge.eventbus.api.SubscribeEvent; | ||||
| import net.minecraftforge.fml.common.Mod; | ||||
|  | ||||
| @Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT ) | ||||
| public final class CableHighlightRenderer | ||||
| { | ||||
|     private CableHighlightRenderer() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Draw an outline for a specific part of a cable "Multipart". | ||||
|      * | ||||
|      * @param event The event to observe | ||||
|      * @see WorldRenderer#drawSelectionBox(MatrixStack, IVertexBuilder, Entity, double, double, double, BlockPos, BlockState) | ||||
|      */ | ||||
|     @SubscribeEvent | ||||
|     public static void drawHighlight( DrawHighlightEvent.HighlightBlock event ) | ||||
|     { | ||||
|         BlockHitResult hit = event.getTarget(); | ||||
|         BlockPos pos = hit.getBlockPos(); | ||||
|         World world = event.getInfo().getFocusedEntity().getEntityWorld(); | ||||
|         Camera info = event.getInfo(); | ||||
|  | ||||
|         BlockState state = world.getBlockState( pos ); | ||||
|  | ||||
|         // We only care about instances with both cable and modem. | ||||
|         if( state.getBlock() != Registry.ModBlocks.CABLE.get() || state.get( BlockCable.MODEM ).getFacing() == null || !state.get( BlockCable.CABLE ) ) | ||||
|         { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         event.setCanceled( true ); | ||||
|  | ||||
|         VoxelShape shape = WorldUtil.isVecInside( CableShapes.getModemShape( state ), hit.getPos().subtract( pos.getX(), pos.getY(), pos.getZ() ) ) | ||||
|             ? CableShapes.getModemShape( state ) | ||||
|             : CableShapes.getCableShape( state ); | ||||
|  | ||||
|         Vec3d cameraPos = info.getPos(); | ||||
|         double xOffset = pos.getX() - cameraPos.getX(); | ||||
|         double yOffset = pos.getY() - cameraPos.getY(); | ||||
|         double zOffset = pos.getZ() - cameraPos.getZ(); | ||||
|  | ||||
|         VertexConsumer buffer = event.getBuffers().getBuffer( RenderLayer.getLines() ); | ||||
|         Matrix4f matrix4f = event.getMatrix().peek().getModel(); | ||||
|         shape.forEachEdge( ( x1, y1, z1, x2, y2, z2 ) -> { | ||||
|             buffer.vertex( matrix4f, (float) (x1 + xOffset), (float) (y1 + yOffset), (float) (z1 + zOffset) ) | ||||
|                 .color( 0, 0, 0, 0.4f ).next(); | ||||
|             buffer.vertex( matrix4f, (float) (x2 + xOffset), (float) (y2 + yOffset), (float) (z2 + zOffset) ) | ||||
|                 .color( 0, 0, 0, 0.4f ).next(); | ||||
|         } ); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,175 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
|  | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import com.mojang.blaze3d.systems.RenderSystem; | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import dan200.computercraft.shared.computer.core.ComputerFamily; | ||||
| import org.lwjgl.opengl.GL11; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import net.minecraft.client.render.BufferBuilder; | ||||
| import net.minecraft.client.render.Tessellator; | ||||
| import net.minecraft.client.render.VertexConsumer; | ||||
| import net.minecraft.client.render.VertexFormats; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraft.util.math.Matrix4f; | ||||
|  | ||||
| public class ComputerBorderRenderer | ||||
| { | ||||
|     public static final Identifier BACKGROUND_NORMAL = new Identifier( ComputerCraft.MOD_ID, "textures/gui/corners_normal.png" ); | ||||
|     public static final Identifier BACKGROUND_ADVANCED = new Identifier( ComputerCraft.MOD_ID, "textures/gui/corners_advanced.png" ); | ||||
|     public static final Identifier BACKGROUND_COMMAND = new Identifier( ComputerCraft.MOD_ID, "textures/gui/corners_command.png" ); | ||||
|     public static final Identifier BACKGROUND_COLOUR = new Identifier( ComputerCraft.MOD_ID, "textures/gui/corners_colour.png" ); | ||||
|  | ||||
|     private static final Matrix4f IDENTITY = new Matrix4f(); | ||||
|  | ||||
|     static | ||||
|     { | ||||
|         IDENTITY.loadIdentity(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * The margin between the terminal and its border. | ||||
|      */ | ||||
|     public static final int MARGIN = 2; | ||||
|  | ||||
|     /** | ||||
|      * The width of the terminal border. | ||||
|      */ | ||||
|     public static final int BORDER = 12; | ||||
|  | ||||
|     private static final int CORNER_TOP_Y = 28; | ||||
|     private static final int CORNER_BOTTOM_Y = CORNER_TOP_Y + BORDER; | ||||
|     private static final int CORNER_LEFT_X = BORDER; | ||||
|     private static final int CORNER_RIGHT_X = CORNER_LEFT_X + BORDER; | ||||
|     private static final int BORDER_RIGHT_X = 36; | ||||
|     private static final int GAP = 4; | ||||
|  | ||||
|     private static final float TEX_SCALE = 1 / 256.0f; | ||||
|  | ||||
|     private final Matrix4f transform; | ||||
|     private final VertexConsumer builder; | ||||
|     private final int z; | ||||
|     private final float r, g, b; | ||||
|  | ||||
|     public ComputerBorderRenderer( Matrix4f transform, VertexConsumer builder, int z, float r, float g, float b ) | ||||
|     { | ||||
|         this.transform = transform; | ||||
|         this.builder = builder; | ||||
|         this.z = z; | ||||
|         this.r = r; | ||||
|         this.g = g; | ||||
|         this.b = b; | ||||
|     } | ||||
|  | ||||
|  | ||||
|     @Nonnull | ||||
|     public static Identifier getTexture( @Nonnull ComputerFamily family ) | ||||
|     { | ||||
|         switch( family ) | ||||
|         { | ||||
|             case NORMAL: | ||||
|             default: | ||||
|                 return BACKGROUND_NORMAL; | ||||
|             case ADVANCED: | ||||
|                 return BACKGROUND_ADVANCED; | ||||
|             case COMMAND: | ||||
|                 return BACKGROUND_COMMAND; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static void render( int x, int y, int z, int width, int height ) | ||||
|     { | ||||
|         Tessellator tessellator = Tessellator.getInstance(); | ||||
|         BufferBuilder buffer = tessellator.getBuffer(); | ||||
|         buffer.begin( GL11.GL_QUADS, VertexFormats.POSITION_COLOR_TEXTURE ); | ||||
|  | ||||
|         render( IDENTITY, buffer, x, y, z, width, height ); | ||||
|  | ||||
|         RenderSystem.enableAlphaTest(); | ||||
|         tessellator.draw(); | ||||
|     } | ||||
|  | ||||
|     public static void render( Matrix4f transform, VertexConsumer buffer, int x, int y, int z, int width, int height ) | ||||
|     { | ||||
|         render( transform, buffer, x, y, z, width, height, 1, 1, 1 ); | ||||
|     } | ||||
|  | ||||
|     public static void render( Matrix4f transform, VertexConsumer buffer, int x, int y, int z, int width, int height, float r, float g, float b ) | ||||
|     { | ||||
|         render( transform, buffer, x, y, z, width, height, 0, r, g, b ); | ||||
|     } | ||||
|  | ||||
|     public static void render( Matrix4f transform, VertexConsumer buffer, int x, int y, int z, int width, int height, int borderHeight, float r, float g, float b ) | ||||
|     { | ||||
|         new ComputerBorderRenderer( transform, buffer, z, r, g, b ).doRender( x, y, width, height, borderHeight ); | ||||
|     } | ||||
|  | ||||
|     public void doRender( int x, int y, int width, int height, int bottomHeight ) | ||||
|     { | ||||
|         int endX = x + width; | ||||
|         int endY = y + height; | ||||
|  | ||||
|         // Vertical bars | ||||
|         renderLine( x - BORDER, y, 0, CORNER_TOP_Y, BORDER, endY - y ); | ||||
|         renderLine( endX, y, BORDER_RIGHT_X, CORNER_TOP_Y, BORDER, endY - y ); | ||||
|  | ||||
|         // Top bar | ||||
|         renderLine( x, y - BORDER, 0, 0, endX - x, BORDER ); | ||||
|         renderCorner( x - BORDER, y - BORDER, CORNER_LEFT_X, CORNER_TOP_Y ); | ||||
|         renderCorner( endX, y - BORDER, CORNER_RIGHT_X, CORNER_TOP_Y ); | ||||
|  | ||||
|         // Bottom bar. We allow for drawing a stretched version, which allows for additional elements (such as the | ||||
|         // pocket computer's lights). | ||||
|         if( bottomHeight <= 0 ) | ||||
|         { | ||||
|             renderLine( x, endY, 0, BORDER, endX - x, BORDER ); | ||||
|             renderCorner( x - BORDER, endY, CORNER_LEFT_X, CORNER_BOTTOM_Y ); | ||||
|             renderCorner( endX, endY, CORNER_RIGHT_X, CORNER_BOTTOM_Y ); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             // Bottom left, middle, right. We do this in three portions: the top inner corners, an extended region for | ||||
|             // lights, and then the bottom outer corners. | ||||
|             renderTexture( x - BORDER, endY, CORNER_LEFT_X, CORNER_BOTTOM_Y, BORDER, BORDER / 2 ); | ||||
|             renderTexture( x, endY, 0, BORDER, width, BORDER / 2, BORDER, BORDER / 2 ); | ||||
|             renderTexture( endX, endY, CORNER_RIGHT_X, CORNER_BOTTOM_Y, BORDER, BORDER / 2 ); | ||||
|  | ||||
|             renderTexture( x - BORDER, endY + BORDER / 2, CORNER_LEFT_X, CORNER_BOTTOM_Y + GAP, BORDER, bottomHeight, BORDER, GAP ); | ||||
|             renderTexture( x, endY + BORDER / 2, 0, BORDER + GAP, width, bottomHeight, BORDER, GAP ); | ||||
|             renderTexture( endX, endY + BORDER / 2, CORNER_RIGHT_X, CORNER_BOTTOM_Y + GAP, BORDER, bottomHeight, BORDER, GAP ); | ||||
|  | ||||
|             renderTexture( x - BORDER, endY + bottomHeight + BORDER / 2, CORNER_LEFT_X, CORNER_BOTTOM_Y + BORDER / 2, BORDER, BORDER / 2 ); | ||||
|             renderTexture( x, endY + bottomHeight + BORDER / 2, 0, BORDER + BORDER / 2, width, BORDER / 2 ); | ||||
|             renderTexture( endX, endY + bottomHeight + BORDER / 2, CORNER_RIGHT_X, CORNER_BOTTOM_Y + BORDER / 2, BORDER, BORDER / 2 ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     private void renderCorner( int x, int y, int u, int v ) | ||||
|     { | ||||
|         renderTexture( x, y, u, v, BORDER, BORDER, BORDER, BORDER ); | ||||
|     } | ||||
|  | ||||
|     private void renderLine( int x, int y, int u, int v, int width, int height ) | ||||
|     { | ||||
|         renderTexture( x, y, u, v, width, height, BORDER, BORDER ); | ||||
|     } | ||||
|  | ||||
|     private void renderTexture( int x, int y, int u, int v, int width, int height ) | ||||
|     { | ||||
|         renderTexture( x, y, u, v, width, height, width, height ); | ||||
|     } | ||||
|  | ||||
|     private void renderTexture( int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight ) | ||||
|     { | ||||
|         builder.vertex( transform, x, y + height, z ).color( r, g, b, 1.0f ).texture( u * TEX_SCALE, (v + textureHeight) * TEX_SCALE ).next(); | ||||
|         builder.vertex( transform, x + width, y + height, z ).color( r, g, b, 1.0f ).texture( (u + textureWidth) * TEX_SCALE, (v + textureHeight) * TEX_SCALE ).next(); | ||||
|         builder.vertex( transform, x + width, y, z ).color( r, g, b, 1.0f ).texture( (u + textureWidth) * TEX_SCALE, v * TEX_SCALE ).next(); | ||||
|         builder.vertex( transform, x, y, z ).color( r, g, b, 1.0f ).texture( u * TEX_SCALE, v * TEX_SCALE ).next(); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,138 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import net.minecraft.client.MinecraftClient; | ||||
| import net.minecraft.client.render.VertexConsumerProvider; | ||||
| import net.minecraft.client.render.item.HeldItemRenderer; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.client.util.math.Vector3f; | ||||
| import net.minecraft.entity.player.PlayerEntity; | ||||
| import net.minecraft.item.ItemStack; | ||||
| import net.minecraft.util.Arm; | ||||
| import net.minecraft.util.Hand; | ||||
| import net.minecraft.util.math.MathHelper; | ||||
|  | ||||
| public abstract class ItemMapLikeRenderer | ||||
| { | ||||
|     /** | ||||
|      * The main rendering method for the item. | ||||
|      * | ||||
|      * @param transform The matrix transformation stack | ||||
|      * @param render    The buffer to render to | ||||
|      * @param stack     The stack to render | ||||
|      * @see FirstPersonRenderer#renderItemInFirstPerson(AbstractClientPlayerEntity, float, float, Hand, float, ItemStack, float, MatrixStack, IRenderTypeBuffer, int) | ||||
|      */ | ||||
|     protected abstract void renderItem( MatrixStack transform, VertexConsumerProvider render, ItemStack stack ); | ||||
|  | ||||
|     protected void renderItemFirstPerson( MatrixStack transform, VertexConsumerProvider render, int lightTexture, Hand hand, float pitch, float equipProgress, float swingProgress, ItemStack stack ) | ||||
|     { | ||||
|         PlayerEntity player = MinecraftClient.getInstance().player; | ||||
|  | ||||
|         transform.push(); | ||||
|         if( hand == Hand.MAIN_HAND && player.getOffHandStack().isEmpty() ) | ||||
|         { | ||||
|             renderItemFirstPersonCenter( transform, render, lightTexture, pitch, equipProgress, swingProgress, stack ); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             renderItemFirstPersonSide( | ||||
|                 transform, render, lightTexture, | ||||
|                 hand == Hand.MAIN_HAND ? player.getMainArm() : player.getMainArm().getOpposite(), | ||||
|                 equipProgress, swingProgress, stack | ||||
|             ); | ||||
|         } | ||||
|         transform.pop(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Renders the item to one side of the player. | ||||
|      * | ||||
|      * @param transform     The matrix transformation stack | ||||
|      * @param render        The buffer to render to | ||||
|      * @param combinedLight The current light level | ||||
|      * @param side          The side to render on | ||||
|      * @param equipProgress The equip progress of this item | ||||
|      * @param swingProgress The swing progress of this item | ||||
|      * @param stack         The stack to render | ||||
|      * @see FirstPersonRenderer#renderMapFirstPersonSide(MatrixStack, IRenderTypeBuffer, int, float, HandSide, float, ItemStack) | ||||
|      */ | ||||
|     private void renderItemFirstPersonSide( MatrixStack transform, VertexConsumerProvider render, int combinedLight, Arm side, float equipProgress, float swingProgress, ItemStack stack ) | ||||
|     { | ||||
|         MinecraftClient minecraft = MinecraftClient.getInstance(); | ||||
|         float offset = side == Arm.RIGHT ? 1f : -1f; | ||||
|         transform.translate( offset * 0.125f, -0.125f, 0f ); | ||||
|  | ||||
|         // If the player is not invisible then render a single arm | ||||
|         if( !minecraft.player.isInvisible() ) | ||||
|         { | ||||
|             transform.push(); | ||||
|             transform.multiply( Vector3f.POSITIVE_Z.getDegreesQuaternion( offset * 10f ) ); | ||||
|             minecraft.getHeldItemRenderer().renderArmHoldingItem( transform, render, combinedLight, equipProgress, swingProgress, side ); | ||||
|             transform.pop(); | ||||
|         } | ||||
|  | ||||
|         // Setup the appropriate transformations. This is just copied from the | ||||
|         // corresponding method in ItemRenderer. | ||||
|         transform.push(); | ||||
|         transform.translate( offset * 0.51f, -0.08f + equipProgress * -1.2f, -0.75f ); | ||||
|         float f1 = MathHelper.sqrt( swingProgress ); | ||||
|         float f2 = MathHelper.sin( f1 * (float) Math.PI ); | ||||
|         float f3 = -0.5f * f2; | ||||
|         float f4 = 0.4f * MathHelper.sin( f1 * ((float) Math.PI * 2f) ); | ||||
|         float f5 = -0.3f * MathHelper.sin( swingProgress * (float) Math.PI ); | ||||
|         transform.translate( offset * f3, f4 - 0.3f * f2, f5 ); | ||||
|         transform.multiply( Vector3f.POSITIVE_X.getDegreesQuaternion( f2 * -45f ) ); | ||||
|         transform.multiply( Vector3f.POSITIVE_Y.getDegreesQuaternion( offset * f2 * -30f ) ); | ||||
|  | ||||
|         renderItem( transform, render, stack ); | ||||
|  | ||||
|         transform.pop(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Render an item in the middle of the screen. | ||||
|      * | ||||
|      * @param transform     The matrix transformation stack | ||||
|      * @param render        The buffer to render to | ||||
|      * @param combinedLight The current light level | ||||
|      * @param pitch         The pitch of the player | ||||
|      * @param equipProgress The equip progress of this item | ||||
|      * @param swingProgress The swing progress of this item | ||||
|      * @param stack         The stack to render | ||||
|      * @see FirstPersonRenderer#renderMapFirstPerson(MatrixStack, IRenderTypeBuffer, int, float, float, float) | ||||
|      */ | ||||
|     private void renderItemFirstPersonCenter( MatrixStack transform, VertexConsumerProvider render, int combinedLight, float pitch, float equipProgress, float swingProgress, ItemStack stack ) | ||||
|     { | ||||
|         MinecraftClient minecraft = MinecraftClient.getInstance(); | ||||
|         HeldItemRenderer renderer = minecraft.getHeldItemRenderer(); | ||||
|  | ||||
|         // Setup the appropriate transformations. This is just copied from the | ||||
|         // corresponding method in ItemRenderer. | ||||
|         float swingRt = MathHelper.sqrt( swingProgress ); | ||||
|         float tX = -0.2f * MathHelper.sin( swingProgress * (float) Math.PI ); | ||||
|         float tZ = -0.4f * MathHelper.sin( swingRt * (float) Math.PI ); | ||||
|         transform.translate( 0, -tX / 2, tZ ); | ||||
|  | ||||
|         float pitchAngle = renderer.getMapAngle( pitch ); | ||||
|         transform.translate( 0, 0.04F + equipProgress * -1.2f + pitchAngle * -0.5f, -0.72f ); | ||||
|         transform.multiply( Vector3f.POSITIVE_X.getDegreesQuaternion( pitchAngle * -85.0f ) ); | ||||
|         if( !minecraft.player.isInvisible() ) | ||||
|         { | ||||
|             transform.push(); | ||||
|             transform.multiply( Vector3f.POSITIVE_Y.getDegreesQuaternion( 90.0F ) ); | ||||
|             renderer.renderArm( transform, render, combinedLight, Arm.RIGHT ); | ||||
|             renderer.renderArm( transform, render, combinedLight, Arm.LEFT ); | ||||
|             transform.pop(); | ||||
|         } | ||||
|  | ||||
|         float rX = MathHelper.sin( swingRt * (float) Math.PI ); | ||||
|         transform.multiply( Vector3f.POSITIVE_X.getDegreesQuaternion( rX * 20.0F ) ); | ||||
|         transform.scale( 2.0F, 2.0F, 2.0F ); | ||||
|  | ||||
|         renderItem( transform, render, stack ); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,158 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import com.mojang.blaze3d.systems.RenderSystem; | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import dan200.computercraft.client.gui.FixedWidthFontRenderer; | ||||
| import dan200.computercraft.core.terminal.Terminal; | ||||
| import dan200.computercraft.shared.computer.core.ClientComputer; | ||||
| import dan200.computercraft.shared.computer.core.ComputerFamily; | ||||
| import dan200.computercraft.shared.pocket.items.ItemPocketComputer; | ||||
| import dan200.computercraft.shared.util.Colour; | ||||
| import net.minecraft.client.MinecraftClient; | ||||
| import net.minecraft.client.render.BufferBuilder; | ||||
| import net.minecraft.client.render.Tessellator; | ||||
| import net.minecraft.client.render.VertexConsumerProvider; | ||||
| import net.minecraft.client.render.VertexFormats; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.client.util.math.Vector3f; | ||||
| import net.minecraft.item.ItemStack; | ||||
| import net.minecraft.util.math.Matrix4f; | ||||
| import net.minecraftforge.api.distmarker.Dist; | ||||
| import net.minecraftforge.client.event.RenderHandEvent; | ||||
| import net.minecraftforge.eventbus.api.SubscribeEvent; | ||||
| import net.minecraftforge.fml.common.Mod; | ||||
| import org.lwjgl.opengl.GL11; | ||||
|  | ||||
| import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT; | ||||
| import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_WIDTH; | ||||
| import static dan200.computercraft.client.render.ComputerBorderRenderer.BORDER; | ||||
| import static dan200.computercraft.client.render.ComputerBorderRenderer.MARGIN; | ||||
|  | ||||
| /** | ||||
|  * Emulates map rendering for pocket computers. | ||||
|  */ | ||||
| @Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT ) | ||||
| public final class ItemPocketRenderer extends ItemMapLikeRenderer | ||||
| { | ||||
|     private static final int LIGHT_HEIGHT = 8; | ||||
|  | ||||
|     private static final ItemPocketRenderer INSTANCE = new ItemPocketRenderer(); | ||||
|  | ||||
|     private ItemPocketRenderer() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     @SubscribeEvent | ||||
|     public static void onRenderInHand( RenderHandEvent event ) | ||||
|     { | ||||
|         ItemStack stack = event.getItemStack(); | ||||
|         if( !(stack.getItem() instanceof ItemPocketComputer) ) return; | ||||
|  | ||||
|         event.setCanceled( true ); | ||||
|         INSTANCE.renderItemFirstPerson( | ||||
|             event.getMatrixStack(), event.getBuffers(), event.getLight(), | ||||
|             event.getHand(), event.getInterpolatedPitch(), event.getEquipProgress(), event.getSwingProgress(), event.getItemStack() | ||||
|         ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     protected void renderItem( MatrixStack transform, VertexConsumerProvider render, ItemStack stack ) | ||||
|     { | ||||
|         ClientComputer computer = ItemPocketComputer.createClientComputer( stack ); | ||||
|         Terminal terminal = computer == null ? null : computer.getTerminal(); | ||||
|  | ||||
|         int termWidth, termHeight; | ||||
|         if( terminal == null ) | ||||
|         { | ||||
|             termWidth = ComputerCraft.pocketTermWidth; | ||||
|             termHeight = ComputerCraft.pocketTermHeight; | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             termWidth = terminal.getWidth(); | ||||
|             termHeight = terminal.getHeight(); | ||||
|         } | ||||
|  | ||||
|         int width = termWidth * FONT_WIDTH + MARGIN * 2; | ||||
|         int height = termHeight * FONT_HEIGHT + MARGIN * 2; | ||||
|  | ||||
|         // Setup various transformations. Note that these are partially adapted from the corresponding method | ||||
|         // in ItemRenderer | ||||
|         transform.push(); | ||||
|         transform.multiply( Vector3f.POSITIVE_Y.getDegreesQuaternion( 180f ) ); | ||||
|         transform.multiply( Vector3f.POSITIVE_Z.getDegreesQuaternion( 180f ) ); | ||||
|         transform.scale( 0.5f, 0.5f, 0.5f ); | ||||
|  | ||||
|         float scale = 0.75f / Math.max( width + BORDER * 2, height + BORDER * 2 + LIGHT_HEIGHT ); | ||||
|         transform.scale( scale, scale, 0 ); | ||||
|         transform.translate( -0.5 * width, -0.5 * height, 0 ); | ||||
|  | ||||
|         // Render the main frame | ||||
|         ItemPocketComputer item = (ItemPocketComputer) stack.getItem(); | ||||
|         ComputerFamily family = item.getFamily(); | ||||
|         int frameColour = item.getColour( stack ); | ||||
|  | ||||
|         Matrix4f matrix = transform.peek().getModel(); | ||||
|         renderFrame( matrix, family, frameColour, width, height ); | ||||
|  | ||||
|         // Render the light | ||||
|         int lightColour = ItemPocketComputer.getLightState( stack ); | ||||
|         if( lightColour == -1 ) lightColour = Colour.BLACK.getHex(); | ||||
|         renderLight( matrix, lightColour, width, height ); | ||||
|  | ||||
|         if( computer != null && terminal != null ) | ||||
|         { | ||||
|             FixedWidthFontRenderer.drawTerminal( matrix, MARGIN, MARGIN, terminal, !computer.isColour(), MARGIN, MARGIN, MARGIN, MARGIN ); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             FixedWidthFontRenderer.drawEmptyTerminal( matrix, 0, 0, width, height ); | ||||
|         } | ||||
|  | ||||
|         transform.pop(); | ||||
|     } | ||||
|  | ||||
|     private static void renderFrame( Matrix4f transform, ComputerFamily family, int colour, int width, int height ) | ||||
|     { | ||||
|         MinecraftClient.getInstance().getTextureManager() | ||||
|             .bindTexture( colour != -1 ? ComputerBorderRenderer.BACKGROUND_COLOUR : ComputerBorderRenderer.getTexture( family ) ); | ||||
|  | ||||
|         float r = ((colour >>> 16) & 0xFF) / 255.0f; | ||||
|         float g = ((colour >>> 8) & 0xFF) / 255.0f; | ||||
|         float b = (colour & 0xFF) / 255.0f; | ||||
|  | ||||
|         Tessellator tessellator = Tessellator.getInstance(); | ||||
|         BufferBuilder buffer = tessellator.getBuffer(); | ||||
|         buffer.begin( GL11.GL_QUADS, VertexFormats.POSITION_COLOR_TEXTURE ); | ||||
|  | ||||
|         ComputerBorderRenderer.render( transform, buffer, 0, 0, 0, width, height, LIGHT_HEIGHT, r, g, b ); | ||||
|  | ||||
|         tessellator.draw(); | ||||
|     } | ||||
|  | ||||
|     private static void renderLight( Matrix4f transform, int colour, int width, int height ) | ||||
|     { | ||||
|         RenderSystem.enableBlend(); | ||||
|         RenderSystem.disableTexture(); | ||||
|  | ||||
|         float r = ((colour >>> 16) & 0xFF) / 255.0f; | ||||
|         float g = ((colour >>> 8) & 0xFF) / 255.0f; | ||||
|         float b = (colour & 0xFF) / 255.0f; | ||||
|  | ||||
|         Tessellator tessellator = Tessellator.getInstance(); | ||||
|         BufferBuilder buffer = tessellator.getBuffer(); | ||||
|         buffer.begin( GL11.GL_QUADS, VertexFormats.POSITION_COLOR ); | ||||
|         buffer.vertex( transform, width - LIGHT_HEIGHT * 2, height + LIGHT_HEIGHT + BORDER / 2.0f, 0 ).color( r, g, b, 1.0f ).next(); | ||||
|         buffer.vertex( transform, width, height + LIGHT_HEIGHT + BORDER / 2.0f, 0 ).color( r, g, b, 1.0f ).next(); | ||||
|         buffer.vertex( transform, width, height + BORDER / 2.0f, 0 ).color( r, g, b, 1.0f ).next(); | ||||
|         buffer.vertex( transform, width - LIGHT_HEIGHT * 2, height + BORDER / 2.0f, 0 ).color( r, g, b, 1.0f ).next(); | ||||
|  | ||||
|         tessellator.draw(); | ||||
|         RenderSystem.enableTexture(); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,113 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import dan200.computercraft.shared.media.items.ItemPrintout; | ||||
| import net.minecraft.client.render.VertexConsumerProvider; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.client.util.math.Vector3f; | ||||
| import net.minecraft.item.ItemStack; | ||||
| import net.minecraft.util.math.Matrix4f; | ||||
| import net.minecraftforge.api.distmarker.Dist; | ||||
| import net.minecraftforge.client.event.RenderHandEvent; | ||||
| import net.minecraftforge.client.event.RenderItemInFrameEvent; | ||||
| import net.minecraftforge.eventbus.api.SubscribeEvent; | ||||
| import net.minecraftforge.fml.common.Mod; | ||||
|  | ||||
| import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT; | ||||
| import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_WIDTH; | ||||
| import static dan200.computercraft.client.render.PrintoutRenderer.*; | ||||
| import static dan200.computercraft.shared.media.items.ItemPrintout.LINES_PER_PAGE; | ||||
| import static dan200.computercraft.shared.media.items.ItemPrintout.LINE_MAX_LENGTH; | ||||
|  | ||||
| /** | ||||
|  * Emulates map and item-frame rendering for printouts. | ||||
|  */ | ||||
| @Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT ) | ||||
| public final class ItemPrintoutRenderer extends ItemMapLikeRenderer | ||||
| { | ||||
|     private static final ItemPrintoutRenderer INSTANCE = new ItemPrintoutRenderer(); | ||||
|  | ||||
|     private ItemPrintoutRenderer() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     @SubscribeEvent | ||||
|     public static void onRenderInHand( RenderHandEvent event ) | ||||
|     { | ||||
|         ItemStack stack = event.getItemStack(); | ||||
|         if( !(stack.getItem() instanceof ItemPrintout) ) return; | ||||
|  | ||||
|         event.setCanceled( true ); | ||||
|         INSTANCE.renderItemFirstPerson( | ||||
|             event.getMatrixStack(), event.getBuffers(), event.getLight(), | ||||
|             event.getHand(), event.getInterpolatedPitch(), event.getEquipProgress(), event.getSwingProgress(), event.getItemStack() | ||||
|         ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     protected void renderItem( MatrixStack transform, VertexConsumerProvider render, ItemStack stack ) | ||||
|     { | ||||
|         transform.multiply( Vector3f.POSITIVE_X.getDegreesQuaternion( 180f ) ); | ||||
|         transform.scale( 0.42f, 0.42f, -0.42f ); | ||||
|         transform.translate( -0.5f, -0.48f, 0.0f ); | ||||
|  | ||||
|         drawPrintout( transform, render, stack ); | ||||
|     } | ||||
|  | ||||
|     @SubscribeEvent | ||||
|     public static void onRenderInFrame( RenderItemInFrameEvent event ) | ||||
|     { | ||||
|         ItemStack stack = event.getItem(); | ||||
|         if( !(stack.getItem() instanceof ItemPrintout) ) return; | ||||
|         event.setCanceled( true ); | ||||
|  | ||||
|         MatrixStack transform = event.getMatrix(); | ||||
|  | ||||
|         // Move a little bit forward to ensure we're not clipping with the frame | ||||
|         transform.translate( 0.0f, 0.0f, -0.001f ); | ||||
|         transform.multiply( Vector3f.POSITIVE_Z.getDegreesQuaternion( 180f ) ); | ||||
|         transform.scale( 0.95f, 0.95f, -0.95f ); | ||||
|         transform.translate( -0.5f, -0.5f, 0.0f ); | ||||
|  | ||||
|         drawPrintout( transform, event.getBuffers(), stack ); | ||||
|     } | ||||
|  | ||||
|     private static void drawPrintout( MatrixStack transform, VertexConsumerProvider render, ItemStack stack ) | ||||
|     { | ||||
|         int pages = ItemPrintout.getPageCount( stack ); | ||||
|         boolean book = ((ItemPrintout) stack.getItem()).getType() == ItemPrintout.Type.BOOK; | ||||
|  | ||||
|         double width = LINE_MAX_LENGTH * FONT_WIDTH + X_TEXT_MARGIN * 2; | ||||
|         double height = LINES_PER_PAGE * FONT_HEIGHT + Y_TEXT_MARGIN * 2; | ||||
|  | ||||
|         // Non-books will be left aligned | ||||
|         if( !book ) width += offsetAt( pages ); | ||||
|  | ||||
|         double visualWidth = width, visualHeight = height; | ||||
|  | ||||
|         // Meanwhile books will be centred | ||||
|         if( book ) | ||||
|         { | ||||
|             visualWidth += 2 * COVER_SIZE + 2 * offsetAt( pages ); | ||||
|             visualHeight += 2 * COVER_SIZE; | ||||
|         } | ||||
|  | ||||
|         double max = Math.max( visualHeight, visualWidth ); | ||||
|  | ||||
|         // Scale the printout to fit correctly. | ||||
|         float scale = (float) (1.0 / max); | ||||
|         transform.scale( scale, scale, scale ); | ||||
|         transform.translate( (max - width) / 2.0, (max - height) / 2.0, 0.0 ); | ||||
|  | ||||
|         Matrix4f matrix = transform.peek().getModel(); | ||||
|         drawBorder( matrix, render, 0, 0, -0.01f, 0, pages, book ); | ||||
|         drawText( matrix, render, | ||||
|             X_TEXT_MARGIN, Y_TEXT_MARGIN, 0, ItemPrintout.getText( stack ), ItemPrintout.getColours( stack ) | ||||
|         ); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,96 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import dan200.computercraft.shared.peripheral.monitor.TileMonitor; | ||||
| import net.minecraft.block.entity.BlockEntity; | ||||
| import net.minecraft.client.render.RenderLayer; | ||||
| import net.minecraft.client.render.VertexConsumer; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.util.math.BlockPos; | ||||
| import net.minecraft.util.math.Direction; | ||||
| import net.minecraft.util.math.Matrix4f; | ||||
| import net.minecraft.util.math.Vec3d; | ||||
| import net.minecraft.world.World; | ||||
| import net.minecraftforge.api.distmarker.Dist; | ||||
| import net.minecraftforge.client.event.DrawHighlightEvent; | ||||
| import net.minecraftforge.eventbus.api.SubscribeEvent; | ||||
| import net.minecraftforge.fml.common.Mod; | ||||
|  | ||||
| import java.util.EnumSet; | ||||
|  | ||||
| import static net.minecraft.util.math.Direction.*; | ||||
|  | ||||
| /** | ||||
|  * Overrides monitor highlighting to only render the outline of the <em>whole</em> monitor, rather than the current | ||||
|  * block. This means you do not get an intrusive outline on top of the screen. | ||||
|  */ | ||||
| @Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT ) | ||||
| public final class MonitorHighlightRenderer | ||||
| { | ||||
|     private MonitorHighlightRenderer() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     @SubscribeEvent | ||||
|     public static void drawHighlight( DrawHighlightEvent.HighlightBlock event ) | ||||
|     { | ||||
|         // Preserve normal behaviour when crouching. | ||||
|         if( event.getInfo().getFocusedEntity().isInSneakingPose() ) return; | ||||
|  | ||||
|         World world = event.getInfo().getFocusedEntity().getEntityWorld(); | ||||
|         BlockPos pos = event.getTarget().getBlockPos(); | ||||
|  | ||||
|         BlockEntity tile = world.getBlockEntity( pos ); | ||||
|         if( !(tile instanceof TileMonitor) ) return; | ||||
|  | ||||
|         TileMonitor monitor = (TileMonitor) tile; | ||||
|         event.setCanceled( true ); | ||||
|  | ||||
|         // Determine which sides are part of the external faces of the monitor, and so which need to be rendered. | ||||
|         EnumSet<Direction> faces = EnumSet.allOf( Direction.class ); | ||||
|         Direction front = monitor.getFront(); | ||||
|         faces.remove( front ); | ||||
|         if( monitor.getXIndex() != 0 ) faces.remove( monitor.getRight().getOpposite() ); | ||||
|         if( monitor.getXIndex() != monitor.getWidth() - 1 ) faces.remove( monitor.getRight() ); | ||||
|         if( monitor.getYIndex() != 0 ) faces.remove( monitor.getDown().getOpposite() ); | ||||
|         if( monitor.getYIndex() != monitor.getHeight() - 1 ) faces.remove( monitor.getDown() ); | ||||
|  | ||||
|         MatrixStack transformStack = event.getMatrix(); | ||||
|         Vec3d cameraPos = event.getInfo().getPos(); | ||||
|         transformStack.push(); | ||||
|         transformStack.translate( pos.getX() - cameraPos.getX(), pos.getY() - cameraPos.getY(), pos.getZ() - cameraPos.getZ() ); | ||||
|  | ||||
|         // I wish I could think of a better way to do this | ||||
|         VertexConsumer buffer = event.getBuffers().getBuffer( RenderLayer.getLines() ); | ||||
|         Matrix4f transform = transformStack.peek().getModel(); | ||||
|         if( faces.contains( NORTH ) || faces.contains( WEST ) ) line( buffer, transform, 0, 0, 0, UP ); | ||||
|         if( faces.contains( SOUTH ) || faces.contains( WEST ) ) line( buffer, transform, 0, 0, 1, UP ); | ||||
|         if( faces.contains( NORTH ) || faces.contains( EAST ) ) line( buffer, transform, 1, 0, 0, UP ); | ||||
|         if( faces.contains( SOUTH ) || faces.contains( EAST ) ) line( buffer, transform, 1, 0, 1, UP ); | ||||
|         if( faces.contains( NORTH ) || faces.contains( DOWN ) ) line( buffer, transform, 0, 0, 0, EAST ); | ||||
|         if( faces.contains( SOUTH ) || faces.contains( DOWN ) ) line( buffer, transform, 0, 0, 1, EAST ); | ||||
|         if( faces.contains( NORTH ) || faces.contains( UP ) ) line( buffer, transform, 0, 1, 0, EAST ); | ||||
|         if( faces.contains( SOUTH ) || faces.contains( UP ) ) line( buffer, transform, 0, 1, 1, EAST ); | ||||
|         if( faces.contains( WEST ) || faces.contains( DOWN ) ) line( buffer, transform, 0, 0, 0, SOUTH ); | ||||
|         if( faces.contains( EAST ) || faces.contains( DOWN ) ) line( buffer, transform, 1, 0, 0, SOUTH ); | ||||
|         if( faces.contains( WEST ) || faces.contains( UP ) ) line( buffer, transform, 0, 1, 0, SOUTH ); | ||||
|         if( faces.contains( EAST ) || faces.contains( UP ) ) line( buffer, transform, 1, 1, 0, SOUTH ); | ||||
|  | ||||
|         transformStack.pop(); | ||||
|     } | ||||
|  | ||||
|     private static void line( VertexConsumer buffer, Matrix4f transform, float x, float y, float z, Direction direction ) | ||||
|     { | ||||
|         buffer.vertex( transform, x, y, z ).color( 0, 0, 0, 0.4f ).next(); | ||||
|         buffer.vertex( transform, | ||||
|             x + direction.getOffsetX(), | ||||
|             y + direction.getOffsetY(), | ||||
|             z + direction.getOffsetZ() | ||||
|         ).color( 0, 0, 0, 0.4f ).next(); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,164 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
|  | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import com.google.common.base.Strings; | ||||
| import com.mojang.blaze3d.platform.GlStateManager; | ||||
| import com.mojang.blaze3d.systems.RenderSystem; | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import dan200.computercraft.client.gui.FixedWidthFontRenderer; | ||||
| import dan200.computercraft.shared.util.Palette; | ||||
| import org.lwjgl.BufferUtils; | ||||
| import org.lwjgl.opengl.GL13; | ||||
| import org.lwjgl.opengl.GL20; | ||||
|  | ||||
| import java.io.InputStream; | ||||
| import java.nio.FloatBuffer; | ||||
| import net.minecraft.client.texture.TextureUtil; | ||||
| import net.minecraft.util.math.Matrix4f; | ||||
|  | ||||
| class MonitorTextureBufferShader | ||||
| { | ||||
|     static final int TEXTURE_INDEX = GL13.GL_TEXTURE3; | ||||
|  | ||||
|     private static final FloatBuffer MATRIX_BUFFER = BufferUtils.createFloatBuffer( 16 ); | ||||
|     private static final FloatBuffer PALETTE_BUFFER = BufferUtils.createFloatBuffer( 16 * 3 ); | ||||
|  | ||||
|     private static int uniformMv; | ||||
|  | ||||
|     private static int uniformFont; | ||||
|     private static int uniformWidth; | ||||
|     private static int uniformHeight; | ||||
|     private static int uniformTbo; | ||||
|     private static int uniformPalette; | ||||
|  | ||||
|     private static boolean initialised; | ||||
|     private static boolean ok; | ||||
|     private static int program; | ||||
|  | ||||
|     static void setupUniform( Matrix4f transform, int width, int height, Palette palette, boolean greyscale ) | ||||
|     { | ||||
|         MATRIX_BUFFER.rewind(); | ||||
|         transform.writeToBuffer( MATRIX_BUFFER ); | ||||
|         MATRIX_BUFFER.rewind(); | ||||
|         RenderSystem.glUniformMatrix4( uniformMv, false, MATRIX_BUFFER ); | ||||
|  | ||||
|         RenderSystem.glUniform1i( uniformWidth, width ); | ||||
|         RenderSystem.glUniform1i( uniformHeight, height ); | ||||
|  | ||||
|         // TODO: Cache this? Maybe?? | ||||
|         PALETTE_BUFFER.rewind(); | ||||
|         for( int i = 0; i < 16; i++ ) | ||||
|         { | ||||
|             double[] colour = palette.getColour( i ); | ||||
|             if( greyscale ) | ||||
|             { | ||||
|                 float f = FixedWidthFontRenderer.toGreyscale( colour ); | ||||
|                 PALETTE_BUFFER.put( f ).put( f ).put( f ); | ||||
|             } | ||||
|             else | ||||
|             { | ||||
|                 PALETTE_BUFFER.put( (float) colour[0] ).put( (float) colour[1] ).put( (float) colour[2] ); | ||||
|             } | ||||
|         } | ||||
|         PALETTE_BUFFER.flip(); | ||||
|         RenderSystem.glUniform3( uniformPalette, PALETTE_BUFFER ); | ||||
|     } | ||||
|  | ||||
|     static boolean use() | ||||
|     { | ||||
|         if( initialised ) | ||||
|         { | ||||
|             if( ok ) GlStateManager.useProgram( program ); | ||||
|             return ok; | ||||
|         } | ||||
|  | ||||
|         if( ok = load() ) | ||||
|         { | ||||
|             GL20.glUseProgram( program ); | ||||
|             RenderSystem.glUniform1i( uniformFont, 0 ); | ||||
|             RenderSystem.glUniform1i( uniformTbo, TEXTURE_INDEX - GL13.GL_TEXTURE0 ); | ||||
|         } | ||||
|  | ||||
|         return ok; | ||||
|     } | ||||
|  | ||||
|     private static boolean load() | ||||
|     { | ||||
|         initialised = true; | ||||
|  | ||||
|         try | ||||
|         { | ||||
|             int vertexShader = loadShader( GL20.GL_VERTEX_SHADER, "assets/computercraft/shaders/monitor.vert" ); | ||||
|             int fragmentShader = loadShader( GL20.GL_FRAGMENT_SHADER, "assets/computercraft/shaders/monitor.frag" ); | ||||
|  | ||||
|             program = GlStateManager.createProgram(); | ||||
|             GlStateManager.attachShader( program, vertexShader ); | ||||
|             GlStateManager.attachShader( program, fragmentShader ); | ||||
|             GL20.glBindAttribLocation( program, 0, "v_pos" ); | ||||
|  | ||||
|             GlStateManager.linkProgram( program ); | ||||
|             boolean ok = GlStateManager.getProgram( program, GL20.GL_LINK_STATUS ) != 0; | ||||
|             String log = GlStateManager.getProgramInfoLog( program, Short.MAX_VALUE ).trim(); | ||||
|             if( !Strings.isNullOrEmpty( log ) ) | ||||
|             { | ||||
|                 ComputerCraft.log.warn( "Problems when linking monitor shader: {}", log ); | ||||
|             } | ||||
|  | ||||
|             GL20.glDetachShader( program, vertexShader ); | ||||
|             GL20.glDetachShader( program, fragmentShader ); | ||||
|             GlStateManager.deleteShader( vertexShader ); | ||||
|             GlStateManager.deleteShader( fragmentShader ); | ||||
|  | ||||
|             if( !ok ) return false; | ||||
|  | ||||
|             uniformMv = getUniformLocation( program, "u_mv" ); | ||||
|             uniformFont = getUniformLocation( program, "u_font" ); | ||||
|             uniformWidth = getUniformLocation( program, "u_width" ); | ||||
|             uniformHeight = getUniformLocation( program, "u_height" ); | ||||
|             uniformTbo = getUniformLocation( program, "u_tbo" ); | ||||
|             uniformPalette = getUniformLocation( program, "u_palette" ); | ||||
|  | ||||
|             ComputerCraft.log.info( "Loaded monitor shader." ); | ||||
|             return true; | ||||
|         } | ||||
|         catch( Exception e ) | ||||
|         { | ||||
|             ComputerCraft.log.error( "Cannot load monitor shaders", e ); | ||||
|             return false; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     private static int loadShader( int kind, String path ) | ||||
|     { | ||||
|         InputStream stream = TileEntityMonitorRenderer.class.getClassLoader().getResourceAsStream( path ); | ||||
|         if( stream == null ) throw new IllegalArgumentException( "Cannot find " + path ); | ||||
|         String contents = TextureUtil.readAllToString( stream ); | ||||
|  | ||||
|         int shader = GlStateManager.createShader( kind ); | ||||
|  | ||||
|         GlStateManager.shaderSource( shader, contents ); | ||||
|         GlStateManager.compileShader( shader ); | ||||
|  | ||||
|         boolean ok = GlStateManager.getShader( shader, GL20.GL_COMPILE_STATUS ) != 0; | ||||
|         String log = GlStateManager.getShaderInfoLog( shader, Short.MAX_VALUE ).trim(); | ||||
|         if( !Strings.isNullOrEmpty( log ) ) | ||||
|         { | ||||
|             ComputerCraft.log.warn( "Problems when loading monitor shader {}: {}", path, log ); | ||||
|         } | ||||
|  | ||||
|         if( !ok ) throw new IllegalStateException( "Cannot compile shader " + path ); | ||||
|         return shader; | ||||
|     } | ||||
|  | ||||
|     private static int getUniformLocation( int program, String name ) | ||||
|     { | ||||
|         int uniform = GlStateManager.getUniformLocation( program, name ); | ||||
|         if( uniform == -1 ) throw new IllegalStateException( "Cannot find uniform " + name ); | ||||
|         return uniform; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,185 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import dan200.computercraft.client.gui.FixedWidthFontRenderer; | ||||
| import dan200.computercraft.core.terminal.TextBuffer; | ||||
| import dan200.computercraft.shared.util.Palette; | ||||
| import net.minecraft.client.render.RenderLayer; | ||||
| import net.minecraft.client.render.RenderPhase; | ||||
| import net.minecraft.client.render.VertexConsumer; | ||||
| import net.minecraft.client.render.VertexConsumerProvider; | ||||
| import net.minecraft.client.render.VertexFormats; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraft.util.math.Matrix4f; | ||||
| import org.lwjgl.opengl.GL11; | ||||
|  | ||||
| import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT; | ||||
| import static dan200.computercraft.shared.media.items.ItemPrintout.LINES_PER_PAGE; | ||||
|  | ||||
| public final class PrintoutRenderer | ||||
| { | ||||
|     private static final Identifier BG = new Identifier( "computercraft", "textures/gui/printout.png" ); | ||||
|     private static final float BG_SIZE = 256.0f; | ||||
|  | ||||
|     /** | ||||
|      * Width of a page. | ||||
|      */ | ||||
|     public static final int X_SIZE = 172; | ||||
|  | ||||
|     /** | ||||
|      * Height of a page. | ||||
|      */ | ||||
|     public static final int Y_SIZE = 209; | ||||
|  | ||||
|     /** | ||||
|      * Padding between the left and right of a page and the text. | ||||
|      */ | ||||
|     public static final int X_TEXT_MARGIN = 13; | ||||
|  | ||||
|     /** | ||||
|      * Padding between the top and bottom of a page and the text. | ||||
|      */ | ||||
|     public static final int Y_TEXT_MARGIN = 11; | ||||
|  | ||||
|     /** | ||||
|      * Width of the extra page texture. | ||||
|      */ | ||||
|     private static final int X_FOLD_SIZE = 12; | ||||
|  | ||||
|     /** | ||||
|      * Size of the leather cover. | ||||
|      */ | ||||
|     public static final int COVER_SIZE = 12; | ||||
|  | ||||
|     private static final int COVER_Y = Y_SIZE; | ||||
|     private static final int COVER_X = X_SIZE + 4 * X_FOLD_SIZE; | ||||
|  | ||||
|     private PrintoutRenderer() {} | ||||
|  | ||||
|     public static void drawText( Matrix4f transform, VertexConsumerProvider renderer, int x, int y, int start, TextBuffer[] text, TextBuffer[] colours ) | ||||
|     { | ||||
|         VertexConsumer buffer = renderer.getBuffer( FixedWidthFontRenderer.TYPE ); | ||||
|         for( int line = 0; line < LINES_PER_PAGE && line < text.length; line++ ) | ||||
|         { | ||||
|             FixedWidthFontRenderer.drawString( transform, buffer, | ||||
|                 x, y + line * FONT_HEIGHT, text[start + line], colours[start + line], null, Palette.DEFAULT, | ||||
|                 false, 0, 0 | ||||
|             ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static void drawText( Matrix4f transform, VertexConsumerProvider renderer, int x, int y, int start, String[] text, String[] colours ) | ||||
|     { | ||||
|         VertexConsumer buffer = renderer.getBuffer( FixedWidthFontRenderer.TYPE ); | ||||
|         for( int line = 0; line < LINES_PER_PAGE && line < text.length; line++ ) | ||||
|         { | ||||
|             FixedWidthFontRenderer.drawString( transform, buffer, | ||||
|                 x, y + line * FONT_HEIGHT, | ||||
|                 new TextBuffer( text[start + line] ), new TextBuffer( colours[start + line] ), | ||||
|                 null, Palette.DEFAULT, false, 0, 0 | ||||
|             ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static void drawBorder( Matrix4f transform, VertexConsumerProvider renderer, float x, float y, float z, int page, int pages, boolean isBook ) | ||||
|     { | ||||
|         int leftPages = page; | ||||
|         int rightPages = pages - page - 1; | ||||
|  | ||||
|         VertexConsumer buffer = renderer.getBuffer( Type.TYPE ); | ||||
|  | ||||
|         if( isBook ) | ||||
|         { | ||||
|             // Border | ||||
|             float offset = offsetAt( pages ); | ||||
|             float left = x - 4 - offset; | ||||
|             float right = x + X_SIZE + offset - 4; | ||||
|  | ||||
|             // Left and right border | ||||
|             drawTexture( transform, buffer, left - 4, y - 8, z - 0.02f, COVER_X, 0, COVER_SIZE, Y_SIZE + COVER_SIZE * 2 ); | ||||
|             drawTexture( transform, buffer, right, y - 8, z - 0.02f, COVER_X + COVER_SIZE, 0, COVER_SIZE, Y_SIZE + COVER_SIZE * 2 ); | ||||
|  | ||||
|             // Draw centre panel (just stretched texture, sorry). | ||||
|             drawTexture( transform, buffer, | ||||
|                 x - offset, y, z - 0.02f, X_SIZE + offset * 2, Y_SIZE, | ||||
|                 COVER_X + COVER_SIZE / 2.0f, COVER_SIZE, COVER_SIZE, Y_SIZE | ||||
|             ); | ||||
|  | ||||
|             float borderX = left; | ||||
|             while( borderX < right ) | ||||
|             { | ||||
|                 double thisWidth = Math.min( right - borderX, X_SIZE ); | ||||
|                 drawTexture( transform, buffer, borderX, y - 8, z - 0.02f, 0, COVER_Y, (float) thisWidth, COVER_SIZE ); | ||||
|                 drawTexture( transform, buffer, borderX, y + Y_SIZE - 4, z - 0.02f, 0, COVER_Y + COVER_SIZE, (float) thisWidth, COVER_SIZE ); | ||||
|                 borderX += thisWidth; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         // Left half | ||||
|         drawTexture( transform, buffer, x, y, z, X_FOLD_SIZE * 2, 0, X_SIZE / 2.0f, Y_SIZE ); | ||||
|         for( int n = 0; n <= leftPages; n++ ) | ||||
|         { | ||||
|             drawTexture( transform, buffer, | ||||
|                 x - offsetAt( n ), y, z - 1e-3f * n, | ||||
|                 // Use the left "bold" fold for the outermost page | ||||
|                 n == leftPages ? 0 : X_FOLD_SIZE, 0, | ||||
|                 X_FOLD_SIZE, Y_SIZE | ||||
|             ); | ||||
|         } | ||||
|  | ||||
|         // Right half | ||||
|         drawTexture( transform, buffer, x + X_SIZE / 2.0f, y, z, X_FOLD_SIZE * 2 + X_SIZE / 2.0f, 0, X_SIZE / 2.0f, Y_SIZE ); | ||||
|         for( int n = 0; n <= rightPages; n++ ) | ||||
|         { | ||||
|             drawTexture( transform, buffer, | ||||
|                 x + (X_SIZE - X_FOLD_SIZE) + offsetAt( n ), y, z - 1e-3f * n, | ||||
|                 // Two folds, then the main page. Use the right "bold" fold for the outermost page. | ||||
|                 X_FOLD_SIZE * 2 + X_SIZE + (n == rightPages ? X_FOLD_SIZE : 0), 0, | ||||
|                 X_FOLD_SIZE, Y_SIZE | ||||
|             ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     private static void drawTexture( Matrix4f matrix, VertexConsumer buffer, float x, float y, float z, float u, float v, float width, float height ) | ||||
|     { | ||||
|         buffer.vertex( matrix, x, y + height, z ).texture( u / BG_SIZE, (v + height) / BG_SIZE ).next(); | ||||
|         buffer.vertex( matrix, x + width, y + height, z ).texture( (u + width) / BG_SIZE, (v + height) / BG_SIZE ).next(); | ||||
|         buffer.vertex( matrix, x + width, y, z ).texture( (u + width) / BG_SIZE, v / BG_SIZE ).next(); | ||||
|         buffer.vertex( matrix, x, y, z ).texture( u / BG_SIZE, v / BG_SIZE ).next(); | ||||
|     } | ||||
|  | ||||
|     private static void drawTexture( Matrix4f matrix, VertexConsumer buffer, float x, float y, float z, float width, float height, float u, float v, float tWidth, float tHeight ) | ||||
|     { | ||||
|         buffer.vertex( matrix, x, y + height, z ).texture( u / BG_SIZE, (v + tHeight) / BG_SIZE ).next(); | ||||
|         buffer.vertex( matrix, x + width, y + height, z ).texture( (u + tWidth) / BG_SIZE, (v + tHeight) / BG_SIZE ).next(); | ||||
|         buffer.vertex( matrix, x + width, y, z ).texture( (u + tWidth) / BG_SIZE, v / BG_SIZE ).next(); | ||||
|         buffer.vertex( matrix, x, y, z ).texture( u / BG_SIZE, v / BG_SIZE ).next(); | ||||
|     } | ||||
|  | ||||
|     public static float offsetAt( int page ) | ||||
|     { | ||||
|         return (float) (32 * (1 - Math.pow( 1.2, -page ))); | ||||
|     } | ||||
|  | ||||
|     private static final class Type extends RenderPhase | ||||
|     { | ||||
|         static final RenderLayer TYPE = RenderLayer.of( | ||||
|             "printout_background", VertexFormats.POSITION_TEXTURE, GL11.GL_QUADS, 1024, | ||||
|             false, false, // useDelegate, needsSorting | ||||
|             RenderLayer.MultiPhaseParameters.builder() | ||||
|                 .texture( new RenderPhase.Texture( BG, false, false ) ) // blur, minimap | ||||
|                 .alpha( ONE_TENTH_ALPHA ) | ||||
|                 .lightmap( DISABLE_LIGHTMAP ) | ||||
|                 .build( false ) | ||||
|         ); | ||||
|  | ||||
|         private Type( String name, Runnable setup, Runnable destroy ) | ||||
|         { | ||||
|             super( name, setup, destroy ); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,243 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import com.mojang.blaze3d.platform.GlStateManager; | ||||
| import dan200.computercraft.client.FrameInfo; | ||||
| import dan200.computercraft.client.gui.FixedWidthFontRenderer; | ||||
| import dan200.computercraft.core.terminal.Terminal; | ||||
| import dan200.computercraft.core.terminal.TextBuffer; | ||||
| import dan200.computercraft.shared.peripheral.monitor.ClientMonitor; | ||||
| import dan200.computercraft.shared.peripheral.monitor.MonitorRenderer; | ||||
| import dan200.computercraft.shared.peripheral.monitor.TileMonitor; | ||||
| import dan200.computercraft.shared.util.Colour; | ||||
| import dan200.computercraft.shared.util.DirectionUtil; | ||||
| import net.minecraft.client.gl.VertexBuffer; | ||||
| import net.minecraft.client.render.BufferBuilder; | ||||
| import net.minecraft.client.render.Tessellator; | ||||
| import net.minecraft.client.render.VertexConsumer; | ||||
| import net.minecraft.client.render.VertexConsumerProvider; | ||||
| import net.minecraft.client.render.VertexFormats; | ||||
| import net.minecraft.client.render.block.entity.BlockEntityRenderDispatcher; | ||||
| import net.minecraft.client.render.block.entity.BlockEntityRenderer; | ||||
| import net.minecraft.client.util.GlAllocationUtils; | ||||
| import net.minecraft.client.util.math.AffineTransformation; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.client.util.math.Vector3f; | ||||
| import net.minecraft.util.math.BlockPos; | ||||
| import net.minecraft.util.math.Direction; | ||||
| import net.minecraft.util.math.Matrix4f; | ||||
| import org.lwjgl.opengl.GL11; | ||||
| import org.lwjgl.opengl.GL13; | ||||
| import org.lwjgl.opengl.GL20; | ||||
| import org.lwjgl.opengl.GL31; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.nio.ByteBuffer; | ||||
|  | ||||
| import static dan200.computercraft.client.gui.FixedWidthFontRenderer.*; | ||||
|  | ||||
| public class TileEntityMonitorRenderer extends BlockEntityRenderer<TileMonitor> | ||||
| { | ||||
|     /** | ||||
|      * {@link TileMonitor#RENDER_MARGIN}, but a tiny bit of additional padding to ensure that there is no space between | ||||
|      * the monitor frame and contents. | ||||
|      */ | ||||
|     private static final float MARGIN = (float) (TileMonitor.RENDER_MARGIN * 1.1); | ||||
|     private static ByteBuffer tboContents; | ||||
|  | ||||
|     private static final Matrix4f IDENTITY = AffineTransformation.identity().getMatrix(); | ||||
|  | ||||
|     public TileEntityMonitorRenderer( BlockEntityRenderDispatcher rendererDispatcher ) | ||||
|     { | ||||
|         super( rendererDispatcher ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void render( @Nonnull TileMonitor monitor, float partialTicks, @Nonnull MatrixStack transform, @Nonnull VertexConsumerProvider renderer, int lightmapCoord, int overlayLight ) | ||||
|     { | ||||
|         // Render from the origin monitor | ||||
|         ClientMonitor originTerminal = monitor.getClientMonitor(); | ||||
|  | ||||
|         if( originTerminal == null ) return; | ||||
|         TileMonitor origin = originTerminal.getOrigin(); | ||||
|         BlockPos monitorPos = monitor.getPos(); | ||||
|  | ||||
|         // Ensure each monitor terminal is rendered only once. We allow rendering a specific tile | ||||
|         // multiple times in a single frame to ensure compatibility with shaders which may run a | ||||
|         // pass multiple times. | ||||
|         long renderFrame = FrameInfo.getRenderFrame(); | ||||
|         if( originTerminal.lastRenderFrame == renderFrame && !monitorPos.equals( originTerminal.lastRenderPos ) ) | ||||
|         { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         originTerminal.lastRenderFrame = renderFrame; | ||||
|         originTerminal.lastRenderPos = monitorPos; | ||||
|  | ||||
|         BlockPos originPos = origin.getPos(); | ||||
|  | ||||
|         // Determine orientation | ||||
|         Direction dir = origin.getDirection(); | ||||
|         Direction front = origin.getFront(); | ||||
|         float yaw = dir.asRotation(); | ||||
|         float pitch = DirectionUtil.toPitchAngle( front ); | ||||
|  | ||||
|         // Setup initial transform | ||||
|         transform.push(); | ||||
|         transform.translate( | ||||
|             originPos.getX() - monitorPos.getX() + 0.5, | ||||
|             originPos.getY() - monitorPos.getY() + 0.5, | ||||
|             originPos.getZ() - monitorPos.getZ() + 0.5 | ||||
|         ); | ||||
|  | ||||
|         transform.multiply( Vector3f.NEGATIVE_Y.getDegreesQuaternion( yaw ) ); | ||||
|         transform.multiply( Vector3f.POSITIVE_X.getDegreesQuaternion( pitch ) ); | ||||
|         transform.translate( | ||||
|             -0.5 + TileMonitor.RENDER_BORDER + TileMonitor.RENDER_MARGIN, | ||||
|             origin.getHeight() - 0.5 - (TileMonitor.RENDER_BORDER + TileMonitor.RENDER_MARGIN) + 0, | ||||
|             0.5 | ||||
|         ); | ||||
|         double xSize = origin.getWidth() - 2.0 * (TileMonitor.RENDER_MARGIN + TileMonitor.RENDER_BORDER); | ||||
|         double ySize = origin.getHeight() - 2.0 * (TileMonitor.RENDER_MARGIN + TileMonitor.RENDER_BORDER); | ||||
|  | ||||
|         // Draw the contents | ||||
|         Terminal terminal = originTerminal.getTerminal(); | ||||
|         if( terminal != null ) | ||||
|         { | ||||
|             // Draw a terminal | ||||
|             int width = terminal.getWidth(), height = terminal.getHeight(); | ||||
|             int pixelWidth = width * FONT_WIDTH, pixelHeight = height * FONT_HEIGHT; | ||||
|             double xScale = xSize / pixelWidth; | ||||
|             double yScale = ySize / pixelHeight; | ||||
|             transform.push(); | ||||
|             transform.scale( (float) xScale, (float) -yScale, 1.0f ); | ||||
|  | ||||
|             Matrix4f matrix = transform.peek().getModel(); | ||||
|  | ||||
|             // Sneaky hack here: we get a buffer now in order to flush existing ones and set up the appropriate | ||||
|             // render state. I've no clue how well this'll work in future versions of Minecraft, but it does the trick | ||||
|             // for now. | ||||
|             VertexConsumer buffer = renderer.getBuffer( FixedWidthFontRenderer.TYPE ); | ||||
|             FixedWidthFontRenderer.TYPE.startDrawing(); | ||||
|  | ||||
|             renderTerminal( matrix, originTerminal, (float) (MARGIN / xScale), (float) (MARGIN / yScale) ); | ||||
|  | ||||
|             // We don't draw the cursor with the VBO, as it's dynamic and so we'll end up refreshing far more than is | ||||
|             // reasonable. | ||||
|             FixedWidthFontRenderer.drawCursor( matrix, buffer, 0, 0, terminal, !originTerminal.isColour() ); | ||||
|  | ||||
|             transform.pop(); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             FixedWidthFontRenderer.drawEmptyTerminal( | ||||
|                 transform.peek().getModel(), renderer, | ||||
|                 -MARGIN, MARGIN, | ||||
|                 (float) (xSize + 2 * MARGIN), (float) -(ySize + MARGIN * 2) | ||||
|             ); | ||||
|         } | ||||
|  | ||||
|         FixedWidthFontRenderer.drawBlocker( | ||||
|             transform.peek().getModel(), renderer, | ||||
|             (float) -TileMonitor.RENDER_MARGIN, (float) TileMonitor.RENDER_MARGIN, | ||||
|             (float) (xSize + 2 * TileMonitor.RENDER_MARGIN), (float) -(ySize + TileMonitor.RENDER_MARGIN * 2) | ||||
|         ); | ||||
|  | ||||
|         transform.pop(); | ||||
|     } | ||||
|  | ||||
|     private static void renderTerminal( Matrix4f matrix, ClientMonitor monitor, float xMargin, float yMargin ) | ||||
|     { | ||||
|         Terminal terminal = monitor.getTerminal(); | ||||
|  | ||||
|         MonitorRenderer renderType = MonitorRenderer.current(); | ||||
|         boolean redraw = monitor.pollTerminalChanged(); | ||||
|         if( monitor.createBuffer( renderType ) ) redraw = true; | ||||
|  | ||||
|         switch( renderType ) | ||||
|         { | ||||
|             case TBO: | ||||
|             { | ||||
|                 if( !MonitorTextureBufferShader.use() ) return; | ||||
|  | ||||
|                 int width = terminal.getWidth(), height = terminal.getHeight(); | ||||
|                 int pixelWidth = width * FONT_WIDTH, pixelHeight = height * FONT_HEIGHT; | ||||
|  | ||||
|                 if( redraw ) | ||||
|                 { | ||||
|                     int size = width * height * 3; | ||||
|                     if( tboContents == null || tboContents.capacity() < size ) | ||||
|                     { | ||||
|                         tboContents = GlAllocationUtils.allocateByteBuffer( size ); | ||||
|                     } | ||||
|  | ||||
|                     ByteBuffer monitorBuffer = tboContents; | ||||
|                     monitorBuffer.clear(); | ||||
|                     for( int y = 0; y < height; y++ ) | ||||
|                     { | ||||
|                         TextBuffer text = terminal.getLine( y ), textColour = terminal.getTextColourLine( y ), background = terminal.getBackgroundColourLine( y ); | ||||
|                         for( int x = 0; x < width; x++ ) | ||||
|                         { | ||||
|                             monitorBuffer.put( (byte) (text.charAt( x ) & 0xFF) ); | ||||
|                             monitorBuffer.put( (byte) getColour( textColour.charAt( x ), Colour.WHITE ) ); | ||||
|                             monitorBuffer.put( (byte) getColour( background.charAt( x ), Colour.BLACK ) ); | ||||
|                         } | ||||
|                     } | ||||
|                     monitorBuffer.flip(); | ||||
|  | ||||
|                     GlStateManager.bindBuffers( GL31.GL_TEXTURE_BUFFER, monitor.tboBuffer ); | ||||
|                     GlStateManager.bufferData( GL31.GL_TEXTURE_BUFFER, monitorBuffer, GL20.GL_STATIC_DRAW ); | ||||
|                     GlStateManager.bindBuffers( GL31.GL_TEXTURE_BUFFER, 0 ); | ||||
|                 } | ||||
|  | ||||
|                 // Nobody knows what they're doing! | ||||
|                 GlStateManager.activeTexture( MonitorTextureBufferShader.TEXTURE_INDEX ); | ||||
|                 GL11.glBindTexture( GL31.GL_TEXTURE_BUFFER, monitor.tboTexture ); | ||||
|                 GlStateManager.activeTexture( GL13.GL_TEXTURE0 ); | ||||
|  | ||||
|                 MonitorTextureBufferShader.setupUniform( matrix, width, height, terminal.getPalette(), !monitor.isColour() ); | ||||
|  | ||||
|                 Tessellator tessellator = Tessellator.getInstance(); | ||||
|                 BufferBuilder buffer = tessellator.getBuffer(); | ||||
|                 buffer.begin( GL11.GL_TRIANGLE_STRIP, VertexFormats.POSITION ); | ||||
|                 buffer.vertex( -xMargin, -yMargin, 0 ).next(); | ||||
|                 buffer.vertex( -xMargin, pixelHeight + yMargin, 0 ).next(); | ||||
|                 buffer.vertex( pixelWidth + xMargin, -yMargin, 0 ).next(); | ||||
|                 buffer.vertex( pixelWidth + xMargin, pixelHeight + yMargin, 0 ).next(); | ||||
|                 tessellator.draw(); | ||||
|  | ||||
|                 GlStateManager.useProgram( 0 ); | ||||
|                 break; | ||||
|             } | ||||
|  | ||||
|             case VBO: | ||||
|             { | ||||
|                 VertexBuffer vbo = monitor.buffer; | ||||
|                 if( redraw ) | ||||
|                 { | ||||
|                     Tessellator tessellator = Tessellator.getInstance(); | ||||
|                     BufferBuilder builder = tessellator.getBuffer(); | ||||
|                     builder.begin( FixedWidthFontRenderer.TYPE.getDrawMode(), FixedWidthFontRenderer.TYPE.getVertexFormat() ); | ||||
|                     FixedWidthFontRenderer.drawTerminalWithoutCursor( | ||||
|                         IDENTITY, builder, 0, 0, | ||||
|                         terminal, !monitor.isColour(), yMargin, yMargin, xMargin, xMargin | ||||
|                     ); | ||||
|  | ||||
|                     builder.end(); | ||||
|                     vbo.upload( builder ); | ||||
|                 } | ||||
|  | ||||
|                 vbo.bind(); | ||||
|                 FixedWidthFontRenderer.TYPE.getVertexFormat().startDrawing( 0L ); | ||||
|                 vbo.draw( matrix, FixedWidthFontRenderer.TYPE.getDrawMode() ); | ||||
|                 VertexBuffer.unbind(); | ||||
|                 FixedWidthFontRenderer.TYPE.getVertexFormat().endDrawing(); | ||||
|                 break; | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,191 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import dan200.computercraft.api.client.TransformedModel; | ||||
| import dan200.computercraft.api.turtle.ITurtleUpgrade; | ||||
| import dan200.computercraft.api.turtle.TurtleSide; | ||||
| import dan200.computercraft.shared.computer.core.ComputerFamily; | ||||
| import dan200.computercraft.shared.turtle.blocks.TileTurtle; | ||||
| import dan200.computercraft.shared.util.DirectionUtil; | ||||
| import dan200.computercraft.shared.util.Holiday; | ||||
| import dan200.computercraft.shared.util.HolidayUtil; | ||||
| import net.minecraft.client.MinecraftClient; | ||||
| import net.minecraft.client.font.TextRenderer; | ||||
| import net.minecraft.client.render.TexturedRenderLayers; | ||||
| import net.minecraft.client.render.VertexConsumer; | ||||
| import net.minecraft.client.render.VertexConsumerProvider; | ||||
| import net.minecraft.client.render.block.entity.BlockEntityRenderDispatcher; | ||||
| import net.minecraft.client.render.block.entity.BlockEntityRenderer; | ||||
| import net.minecraft.client.render.model.BakedModel; | ||||
| import net.minecraft.client.render.model.BakedModelManager; | ||||
| import net.minecraft.client.render.model.BakedQuad; | ||||
| import net.minecraft.client.util.ModelIdentifier; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.client.util.math.Vector3f; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraft.util.hit.BlockHitResult; | ||||
| import net.minecraft.util.hit.HitResult; | ||||
| import net.minecraft.util.math.Direction; | ||||
| import net.minecraft.util.math.Matrix4f; | ||||
| import net.minecraft.util.math.Vec3d; | ||||
| import net.minecraftforge.client.model.data.EmptyModelData; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.List; | ||||
| import java.util.Random; | ||||
|  | ||||
| public class TileEntityTurtleRenderer extends BlockEntityRenderer<TileTurtle> | ||||
| { | ||||
|     private static final ModelIdentifier NORMAL_TURTLE_MODEL = new ModelIdentifier( "computercraft:turtle_normal", "inventory" ); | ||||
|     private static final ModelIdentifier ADVANCED_TURTLE_MODEL = new ModelIdentifier( "computercraft:turtle_advanced", "inventory" ); | ||||
|     private static final ModelIdentifier COLOUR_TURTLE_MODEL = new ModelIdentifier( "computercraft:turtle_colour", "inventory" ); | ||||
|     private static final ModelIdentifier ELF_OVERLAY_MODEL = new ModelIdentifier( "computercraft:turtle_elf_overlay", "inventory" ); | ||||
|  | ||||
|     private final Random random = new Random( 0 ); | ||||
|  | ||||
|     public TileEntityTurtleRenderer( BlockEntityRenderDispatcher renderDispatcher ) | ||||
|     { | ||||
|         super( renderDispatcher ); | ||||
|     } | ||||
|  | ||||
|     public static ModelIdentifier getTurtleModel( ComputerFamily family, boolean coloured ) | ||||
|     { | ||||
|         switch( family ) | ||||
|         { | ||||
|             case NORMAL: | ||||
|             default: | ||||
|                 return coloured ? COLOUR_TURTLE_MODEL : NORMAL_TURTLE_MODEL; | ||||
|             case ADVANCED: | ||||
|                 return coloured ? COLOUR_TURTLE_MODEL : ADVANCED_TURTLE_MODEL; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static ModelIdentifier getTurtleOverlayModel( Identifier overlay, boolean christmas ) | ||||
|     { | ||||
|         if( overlay != null ) return new ModelIdentifier( overlay, "inventory" ); | ||||
|         if( christmas ) return ELF_OVERLAY_MODEL; | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void render( @Nonnull TileTurtle turtle, float partialTicks, @Nonnull MatrixStack transform, @Nonnull VertexConsumerProvider renderer, int lightmapCoord, int overlayLight ) | ||||
|     { | ||||
|         // Render the label | ||||
|         String label = turtle.createProxy().getLabel(); | ||||
|         HitResult hit = dispatcher.crosshairTarget; | ||||
|         if( label != null && hit.getType() == HitResult.Type.BLOCK && turtle.getPos().equals( ((BlockHitResult) hit).getBlockPos() ) ) | ||||
|         { | ||||
|             MinecraftClient mc = MinecraftClient.getInstance(); | ||||
|             TextRenderer font = dispatcher.textRenderer; | ||||
|  | ||||
|             transform.push(); | ||||
|             transform.translate( 0.5, 1.2, 0.5 ); | ||||
|             transform.multiply( mc.getEntityRenderDispatcher().getRotation() ); | ||||
|             transform.scale( -0.025f, -0.025f, 0.025f ); | ||||
|  | ||||
|             Matrix4f matrix = transform.peek().getModel(); | ||||
|             int opacity = (int) (mc.options.getTextBackgroundOpacity( 0.25f ) * 255) << 24; | ||||
|             float width = -font.getWidth( label ) / 2.0f; | ||||
|             font.draw( label, width, (float) 0, 0x20ffffff, false, matrix, renderer, true, opacity, lightmapCoord ); | ||||
|             font.draw( label, width, (float) 0, 0xffffffff, false, matrix, renderer, false, 0, lightmapCoord ); | ||||
|  | ||||
|             transform.pop(); | ||||
|         } | ||||
|  | ||||
|         transform.push(); | ||||
|  | ||||
|         // Setup the transform. | ||||
|         Vec3d offset = turtle.getRenderOffset( partialTicks ); | ||||
|         float yaw = turtle.getRenderYaw( partialTicks ); | ||||
|         transform.translate( offset.x, offset.y, offset.z ); | ||||
|  | ||||
|         transform.translate( 0.5f, 0.5f, 0.5f ); | ||||
|         transform.multiply( Vector3f.POSITIVE_Y.getDegreesQuaternion( 180.0f - yaw ) ); | ||||
|         if( label != null && (label.equals( "Dinnerbone" ) || label.equals( "Grumm" )) ) | ||||
|         { | ||||
|             // Flip the model | ||||
|             transform.scale( 1.0f, -1.0f, 1.0f ); | ||||
|         } | ||||
|         transform.translate( -0.5f, -0.5f, -0.5f ); | ||||
|  | ||||
|         // Render the turtle | ||||
|         int colour = turtle.getColour(); | ||||
|         ComputerFamily family = turtle.getFamily(); | ||||
|         Identifier overlay = turtle.getOverlay(); | ||||
|  | ||||
|         VertexConsumer buffer = renderer.getBuffer( TexturedRenderLayers.getEntityTranslucentCull() ); | ||||
|         renderModel( transform, buffer, lightmapCoord, overlayLight, getTurtleModel( family, colour != -1 ), colour == -1 ? null : new int[] { colour } ); | ||||
|  | ||||
|         // Render the overlay | ||||
|         ModelIdentifier overlayModel = getTurtleOverlayModel( overlay, HolidayUtil.getCurrentHoliday() == Holiday.CHRISTMAS ); | ||||
|         if( overlayModel != null ) | ||||
|         { | ||||
|             renderModel( transform, buffer, lightmapCoord, overlayLight, overlayModel, null ); | ||||
|         } | ||||
|  | ||||
|         // Render the upgrades | ||||
|         renderUpgrade( transform, buffer, lightmapCoord, overlayLight, turtle, TurtleSide.LEFT, partialTicks ); | ||||
|         renderUpgrade( transform, buffer, lightmapCoord, overlayLight, turtle, TurtleSide.RIGHT, partialTicks ); | ||||
|  | ||||
|         transform.pop(); | ||||
|     } | ||||
|  | ||||
|     private void renderUpgrade( @Nonnull MatrixStack transform, @Nonnull VertexConsumer renderer, int lightmapCoord, int overlayLight, TileTurtle turtle, TurtleSide side, float f ) | ||||
|     { | ||||
|         ITurtleUpgrade upgrade = turtle.getUpgrade( side ); | ||||
|         if( upgrade == null ) return; | ||||
|         transform.push(); | ||||
|  | ||||
|         float toolAngle = turtle.getToolRenderAngle( side, f ); | ||||
|         transform.translate( 0.0f, 0.5f, 0.5f ); | ||||
|         transform.multiply( Vector3f.NEGATIVE_X.getDegreesQuaternion( toolAngle ) ); | ||||
|         transform.translate( 0.0f, -0.5f, -0.5f ); | ||||
|  | ||||
|         TransformedModel model = upgrade.getModel( turtle.getAccess(), side ); | ||||
|         model.getMatrix().push( transform ); | ||||
|         renderModel( transform, renderer, lightmapCoord, overlayLight, model.getModel(), null ); | ||||
|         transform.pop(); | ||||
|  | ||||
|         transform.pop(); | ||||
|     } | ||||
|  | ||||
|     private void renderModel( @Nonnull MatrixStack transform, @Nonnull VertexConsumer renderer, int lightmapCoord, int overlayLight, ModelIdentifier modelLocation, int[] tints ) | ||||
|     { | ||||
|         BakedModelManager modelManager = MinecraftClient.getInstance().getItemRenderer().getModels().getModelManager(); | ||||
|         renderModel( transform, renderer, lightmapCoord, overlayLight, modelManager.getModel( modelLocation ), tints ); | ||||
|     } | ||||
|  | ||||
|     private void renderModel( @Nonnull MatrixStack transform, @Nonnull VertexConsumer renderer, int lightmapCoord, int overlayLight, BakedModel model, int[] tints ) | ||||
|     { | ||||
|         random.setSeed( 0 ); | ||||
|         renderQuads( transform, renderer, lightmapCoord, overlayLight, model.getQuads( null, null, random, EmptyModelData.INSTANCE ), tints ); | ||||
|         for( Direction facing : DirectionUtil.FACINGS ) | ||||
|         { | ||||
|             renderQuads( transform, renderer, lightmapCoord, overlayLight, model.getQuads( null, facing, random, EmptyModelData.INSTANCE ), tints ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     private static void renderQuads( @Nonnull MatrixStack transform, @Nonnull VertexConsumer buffer, int lightmapCoord, int overlayLight, List<BakedQuad> quads, int[] tints ) | ||||
|     { | ||||
|         MatrixStack.Entry matrix = transform.peek(); | ||||
|  | ||||
|         for( BakedQuad bakedquad : quads ) | ||||
|         { | ||||
|             int tint = -1; | ||||
|             if( tints != null && bakedquad.hasColor() ) | ||||
|             { | ||||
|                 int idx = bakedquad.getColorIndex(); | ||||
|                 if( idx >= 0 && idx < tints.length ) tint = tints[bakedquad.getColorIndex()]; | ||||
|             } | ||||
|  | ||||
|             float f = (float) (tint >> 16 & 255) / 255.0F; | ||||
|             float f1 = (float) (tint >> 8 & 255) / 255.0F; | ||||
|             float f2 = (float) (tint & 255) / 255.0F; | ||||
|             buffer.addVertexData( matrix, bakedquad, f, f1, f2, lightmapCoord, overlayLight, true ); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,83 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import com.google.gson.JsonDeserializationContext; | ||||
| import com.google.gson.JsonObject; | ||||
| import com.mojang.datafixers.util.Pair; | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import net.minecraft.client.render.model.BakedModel; | ||||
| import net.minecraft.client.render.model.ModelBakeSettings; | ||||
| import net.minecraft.client.render.model.ModelLoader; | ||||
| import net.minecraft.client.render.model.UnbakedModel; | ||||
| import net.minecraft.client.render.model.json.ModelOverrideList; | ||||
| import net.minecraft.client.renderer.model.*; | ||||
| import net.minecraft.client.texture.Sprite; | ||||
| import net.minecraft.client.util.SpriteIdentifier; | ||||
| import net.minecraft.resource.ResourceManager; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraft.util.JsonHelper; | ||||
| import net.minecraftforge.client.model.IModelConfiguration; | ||||
| import net.minecraftforge.client.model.IModelLoader; | ||||
| import net.minecraftforge.client.model.geometry.IModelGeometry; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.Collection; | ||||
| import java.util.HashSet; | ||||
| import java.util.Set; | ||||
| import java.util.function.Function; | ||||
|  | ||||
| public final class TurtleModelLoader implements IModelLoader<TurtleModelLoader.TurtleModel> | ||||
| { | ||||
|     private static final Identifier COLOUR_TURTLE_MODEL = new Identifier( ComputerCraft.MOD_ID, "block/turtle_colour" ); | ||||
|  | ||||
|     public static final TurtleModelLoader INSTANCE = new TurtleModelLoader(); | ||||
|  | ||||
|     private TurtleModelLoader() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void apply( @Nonnull ResourceManager manager ) | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public TurtleModel read( @Nonnull JsonDeserializationContext deserializationContext, @Nonnull JsonObject modelContents ) | ||||
|     { | ||||
|         Identifier model = new Identifier( JsonHelper.getString( modelContents, "model" ) ); | ||||
|         return new TurtleModel( model ); | ||||
|     } | ||||
|  | ||||
|     public static final class TurtleModel implements IModelGeometry<TurtleModel> | ||||
|     { | ||||
|         private final Identifier family; | ||||
|  | ||||
|         private TurtleModel( Identifier family ) | ||||
|         { | ||||
|             this.family = family; | ||||
|         } | ||||
|  | ||||
|         @Override | ||||
|         public Collection<SpriteIdentifier> getTextures( IModelConfiguration owner, Function<Identifier, UnbakedModel> modelGetter, Set<Pair<String, String>> missingTextureErrors ) | ||||
|         { | ||||
|             Set<SpriteIdentifier> materials = new HashSet<>(); | ||||
|             materials.addAll( modelGetter.apply( family ).getTextureDependencies( modelGetter, missingTextureErrors ) ); | ||||
|             materials.addAll( modelGetter.apply( COLOUR_TURTLE_MODEL ).getTextureDependencies( modelGetter, missingTextureErrors ) ); | ||||
|             return materials; | ||||
|         } | ||||
|  | ||||
|         @Override | ||||
|         public BakedModel bake( IModelConfiguration owner, ModelLoader bakery, Function<SpriteIdentifier, Sprite> spriteGetter, ModelBakeSettings transform, ModelOverrideList overrides, Identifier modelLocation ) | ||||
|         { | ||||
|             return new TurtleSmartItemModel( | ||||
|                 bakery.getBakedModel( family, transform, spriteGetter ), | ||||
|                 bakery.getBakedModel( COLOUR_TURTLE_MODEL, transform, spriteGetter ) | ||||
|             ); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,149 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import dan200.computercraft.api.client.TransformedModel; | ||||
| import net.minecraft.block.BlockState; | ||||
| import net.minecraft.client.render.model.BakedModel; | ||||
| import net.minecraft.client.render.model.BakedQuad; | ||||
| import net.minecraft.client.render.model.json.ModelOverrideList; | ||||
| import net.minecraft.client.texture.Sprite; | ||||
| import net.minecraft.client.util.math.AffineTransformation; | ||||
| import net.minecraft.util.math.Direction; | ||||
| import net.minecraftforge.client.model.data.EmptyModelData; | ||||
| import net.minecraftforge.client.model.data.IModelData; | ||||
| import net.minecraftforge.client.model.pipeline.BakedQuadBuilder; | ||||
| import net.minecraftforge.client.model.pipeline.TRSRTransformer; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.*; | ||||
|  | ||||
| public class TurtleMultiModel implements BakedModel | ||||
| { | ||||
|     private final BakedModel m_baseModel; | ||||
|     private final BakedModel m_overlayModel; | ||||
|     private final AffineTransformation m_generalTransform; | ||||
|     private final TransformedModel m_leftUpgradeModel; | ||||
|     private final TransformedModel m_rightUpgradeModel; | ||||
|     private List<BakedQuad> m_generalQuads = null; | ||||
|     private Map<Direction, List<BakedQuad>> m_faceQuads = new EnumMap<>( Direction.class ); | ||||
|  | ||||
|     public TurtleMultiModel( BakedModel baseModel, BakedModel overlayModel, AffineTransformation generalTransform, TransformedModel leftUpgradeModel, TransformedModel rightUpgradeModel ) | ||||
|     { | ||||
|         // Get the models | ||||
|         m_baseModel = baseModel; | ||||
|         m_overlayModel = overlayModel; | ||||
|         m_leftUpgradeModel = leftUpgradeModel; | ||||
|         m_rightUpgradeModel = rightUpgradeModel; | ||||
|         m_generalTransform = generalTransform; | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     @Deprecated | ||||
|     public List<BakedQuad> getQuads( BlockState state, Direction side, @Nonnull Random rand ) | ||||
|     { | ||||
|         return getQuads( state, side, rand, EmptyModelData.INSTANCE ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public List<BakedQuad> getQuads( BlockState state, Direction side, @Nonnull Random rand, @Nonnull IModelData data ) | ||||
|     { | ||||
|         if( side != null ) | ||||
|         { | ||||
|             if( !m_faceQuads.containsKey( side ) ) m_faceQuads.put( side, buildQuads( state, side, rand ) ); | ||||
|             return m_faceQuads.get( side ); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             if( m_generalQuads == null ) m_generalQuads = buildQuads( state, side, rand ); | ||||
|             return m_generalQuads; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     private List<BakedQuad> buildQuads( BlockState state, Direction side, Random rand ) | ||||
|     { | ||||
|         ArrayList<BakedQuad> quads = new ArrayList<>(); | ||||
|  | ||||
|  | ||||
|         transformQuadsTo( quads, m_baseModel.getQuads( state, side, rand, EmptyModelData.INSTANCE ), m_generalTransform ); | ||||
|         if( m_overlayModel != null ) | ||||
|         { | ||||
|             transformQuadsTo( quads, m_overlayModel.getQuads( state, side, rand, EmptyModelData.INSTANCE ), m_generalTransform ); | ||||
|         } | ||||
|         if( m_leftUpgradeModel != null ) | ||||
|         { | ||||
|             AffineTransformation upgradeTransform = m_generalTransform.compose( m_leftUpgradeModel.getMatrix() ); | ||||
|             transformQuadsTo( quads, m_leftUpgradeModel.getModel().getQuads( state, side, rand, EmptyModelData.INSTANCE ), upgradeTransform ); | ||||
|         } | ||||
|         if( m_rightUpgradeModel != null ) | ||||
|         { | ||||
|             AffineTransformation upgradeTransform = m_generalTransform.compose( m_rightUpgradeModel.getMatrix() ); | ||||
|             transformQuadsTo( quads, m_rightUpgradeModel.getModel().getQuads( state, side, rand, EmptyModelData.INSTANCE ), upgradeTransform ); | ||||
|         } | ||||
|         quads.trimToSize(); | ||||
|         return quads; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean useAmbientOcclusion() | ||||
|     { | ||||
|         return m_baseModel.useAmbientOcclusion(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean hasDepth() | ||||
|     { | ||||
|         return m_baseModel.hasDepth(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean isBuiltin() | ||||
|     { | ||||
|         return m_baseModel.isBuiltin(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean isSideLit() | ||||
|     { | ||||
|         return m_baseModel.isSideLit(); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     @Deprecated | ||||
|     public Sprite getSprite() | ||||
|     { | ||||
|         return m_baseModel.getSprite(); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     @Deprecated | ||||
|     public net.minecraft.client.render.model.json.ModelTransformation getTransformation() | ||||
|     { | ||||
|         return m_baseModel.getTransformation(); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public ModelOverrideList getOverrides() | ||||
|     { | ||||
|         return ModelOverrideList.EMPTY; | ||||
|     } | ||||
|  | ||||
|     private void transformQuadsTo( List<BakedQuad> output, List<BakedQuad> quads, AffineTransformation transform ) | ||||
|     { | ||||
|         for( BakedQuad quad : quads ) | ||||
|         { | ||||
|             BakedQuadBuilder builder = new BakedQuadBuilder(); | ||||
|             TRSRTransformer transformer = new TRSRTransformer( builder, transform ); | ||||
|             quad.pipe( transformer ); | ||||
|             output.add( builder.build() ); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,35 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
|  | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import dan200.computercraft.shared.turtle.core.TurtlePlayer; | ||||
| import javax.annotation.Nonnull; | ||||
| import net.minecraft.client.render.VertexConsumerProvider; | ||||
| import net.minecraft.client.render.entity.EntityRenderDispatcher; | ||||
| import net.minecraft.client.render.entity.EntityRenderer; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.util.Identifier; | ||||
|  | ||||
| public class TurtlePlayerRenderer extends EntityRenderer<TurtlePlayer> | ||||
| { | ||||
|     public TurtlePlayerRenderer( EntityRenderDispatcher renderManager ) | ||||
|     { | ||||
|         super( renderManager ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public Identifier getEntityTexture( @Nonnull TurtlePlayer entity ) | ||||
|     { | ||||
|         return ComputerBorderRenderer.BACKGROUND_NORMAL; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void render( @Nonnull TurtlePlayer entityIn, float entityYaw, float partialTicks, @Nonnull MatrixStack transform, @Nonnull VertexConsumerProvider buffer, int packedLightIn ) | ||||
|     { | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,214 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.client.render; | ||||
|  | ||||
| import com.google.common.base.Objects; | ||||
| import dan200.computercraft.api.client.TransformedModel; | ||||
| import dan200.computercraft.api.turtle.ITurtleUpgrade; | ||||
| import dan200.computercraft.api.turtle.TurtleSide; | ||||
| import dan200.computercraft.shared.turtle.items.ItemTurtle; | ||||
| import dan200.computercraft.shared.util.Holiday; | ||||
| import dan200.computercraft.shared.util.HolidayUtil; | ||||
| import net.minecraft.block.BlockState; | ||||
| import net.minecraft.client.MinecraftClient; | ||||
| import net.minecraft.client.render.model.BakedModel; | ||||
| import net.minecraft.client.render.model.BakedModelManager; | ||||
| import net.minecraft.client.render.model.BakedQuad; | ||||
| import net.minecraft.client.render.model.json.ModelOverrideList; | ||||
| import net.minecraft.client.render.model.json.ModelTransformation; | ||||
| import net.minecraft.client.renderer.model.*; | ||||
| import net.minecraft.client.texture.Sprite; | ||||
| import net.minecraft.client.util.ModelIdentifier; | ||||
| import net.minecraft.client.util.math.AffineTransformation; | ||||
| import net.minecraft.client.util.math.MatrixStack; | ||||
| import net.minecraft.client.world.ClientWorld; | ||||
| import net.minecraft.entity.LivingEntity; | ||||
| import net.minecraft.item.ItemStack; | ||||
| import net.minecraft.util.Identifier; | ||||
| import net.minecraft.util.math.Direction; | ||||
| import net.minecraftforge.client.model.data.IModelData; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.util.HashMap; | ||||
| import java.util.List; | ||||
| import java.util.Random; | ||||
|  | ||||
| public class TurtleSmartItemModel implements BakedModel | ||||
| { | ||||
|     private static final AffineTransformation identity, flip; | ||||
|  | ||||
|     static | ||||
|     { | ||||
|         MatrixStack stack = new MatrixStack(); | ||||
|         stack.scale( 0, -1, 0 ); | ||||
|         stack.translate( 0, 0, 1 ); | ||||
|  | ||||
|         identity = AffineTransformation.identity(); | ||||
|         flip = new AffineTransformation( stack.peek().getModel() ); | ||||
|     } | ||||
|  | ||||
|     private static class TurtleModelCombination | ||||
|     { | ||||
|         final boolean m_colour; | ||||
|         final ITurtleUpgrade m_leftUpgrade; | ||||
|         final ITurtleUpgrade m_rightUpgrade; | ||||
|         final Identifier m_overlay; | ||||
|         final boolean m_christmas; | ||||
|         final boolean m_flip; | ||||
|  | ||||
|         TurtleModelCombination( boolean colour, ITurtleUpgrade leftUpgrade, ITurtleUpgrade rightUpgrade, Identifier overlay, boolean christmas, boolean flip ) | ||||
|         { | ||||
|             m_colour = colour; | ||||
|             m_leftUpgrade = leftUpgrade; | ||||
|             m_rightUpgrade = rightUpgrade; | ||||
|             m_overlay = overlay; | ||||
|             m_christmas = christmas; | ||||
|             m_flip = flip; | ||||
|         } | ||||
|  | ||||
|         @Override | ||||
|         public boolean equals( Object other ) | ||||
|         { | ||||
|             if( other == this ) return true; | ||||
|             if( !(other instanceof TurtleModelCombination) ) return false; | ||||
|  | ||||
|             TurtleModelCombination otherCombo = (TurtleModelCombination) other; | ||||
|             return otherCombo.m_colour == m_colour && | ||||
|                 otherCombo.m_leftUpgrade == m_leftUpgrade && | ||||
|                 otherCombo.m_rightUpgrade == m_rightUpgrade && | ||||
|                 Objects.equal( otherCombo.m_overlay, m_overlay ) && | ||||
|                 otherCombo.m_christmas == m_christmas && | ||||
|                 otherCombo.m_flip == m_flip; | ||||
|         } | ||||
|  | ||||
|         @Override | ||||
|         public int hashCode() | ||||
|         { | ||||
|             final int prime = 31; | ||||
|             int result = 0; | ||||
|             result = prime * result + (m_colour ? 1 : 0); | ||||
|             result = prime * result + (m_leftUpgrade != null ? m_leftUpgrade.hashCode() : 0); | ||||
|             result = prime * result + (m_rightUpgrade != null ? m_rightUpgrade.hashCode() : 0); | ||||
|             result = prime * result + (m_overlay != null ? m_overlay.hashCode() : 0); | ||||
|             result = prime * result + (m_christmas ? 1 : 0); | ||||
|             result = prime * result + (m_flip ? 1 : 0); | ||||
|             return result; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     private final BakedModel familyModel; | ||||
|     private final BakedModel colourModel; | ||||
|  | ||||
|     private final HashMap<TurtleModelCombination, BakedModel> m_cachedModels = new HashMap<>(); | ||||
|     private final ModelOverrideList m_overrides; | ||||
|  | ||||
|     public TurtleSmartItemModel( BakedModel familyModel, BakedModel colourModel ) | ||||
|     { | ||||
|         this.familyModel = familyModel; | ||||
|         this.colourModel = colourModel; | ||||
|  | ||||
|         m_overrides = new ModelOverrideList() | ||||
|         { | ||||
|             @Nonnull | ||||
|             @Override | ||||
|             public BakedModel apply( @Nonnull BakedModel originalModel, @Nonnull ItemStack stack, @Nullable ClientWorld world, @Nullable LivingEntity entity ) | ||||
|             { | ||||
|                 ItemTurtle turtle = (ItemTurtle) stack.getItem(); | ||||
|                 int colour = turtle.getColour( stack ); | ||||
|                 ITurtleUpgrade leftUpgrade = turtle.getUpgrade( stack, TurtleSide.LEFT ); | ||||
|                 ITurtleUpgrade rightUpgrade = turtle.getUpgrade( stack, TurtleSide.RIGHT ); | ||||
|                 Identifier overlay = turtle.getOverlay( stack ); | ||||
|                 boolean christmas = HolidayUtil.getCurrentHoliday() == Holiday.CHRISTMAS; | ||||
|                 String label = turtle.getLabel( stack ); | ||||
|                 boolean flip = label != null && (label.equals( "Dinnerbone" ) || label.equals( "Grumm" )); | ||||
|                 TurtleModelCombination combo = new TurtleModelCombination( colour != -1, leftUpgrade, rightUpgrade, overlay, christmas, flip ); | ||||
|  | ||||
|                 BakedModel model = m_cachedModels.get( combo ); | ||||
|                 if( model == null ) m_cachedModels.put( combo, model = buildModel( combo ) ); | ||||
|                 return model; | ||||
|             } | ||||
|         }; | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public ModelOverrideList getOverrides() | ||||
|     { | ||||
|         return m_overrides; | ||||
|     } | ||||
|  | ||||
|     private BakedModel buildModel( TurtleModelCombination combo ) | ||||
|     { | ||||
|         MinecraftClient mc = MinecraftClient.getInstance(); | ||||
|         BakedModelManager modelManager = mc.getItemRenderer().getModels().getModelManager(); | ||||
|         ModelIdentifier overlayModelLocation = TileEntityTurtleRenderer.getTurtleOverlayModel( combo.m_overlay, combo.m_christmas ); | ||||
|  | ||||
|         BakedModel baseModel = combo.m_colour ? colourModel : familyModel; | ||||
|         BakedModel overlayModel = overlayModelLocation != null ? modelManager.getModel( overlayModelLocation ) : null; | ||||
|         AffineTransformation transform = combo.m_flip ? flip : identity; | ||||
|         TransformedModel leftModel = combo.m_leftUpgrade != null ? combo.m_leftUpgrade.getModel( null, TurtleSide.LEFT ) : null; | ||||
|         TransformedModel rightModel = combo.m_rightUpgrade != null ? combo.m_rightUpgrade.getModel( null, TurtleSide.RIGHT ) : null; | ||||
|         return new TurtleMultiModel( baseModel, overlayModel, transform, leftModel, rightModel ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     @Deprecated | ||||
|     public List<BakedQuad> getQuads( BlockState state, Direction facing, @Nonnull Random rand ) | ||||
|     { | ||||
|         return familyModel.getQuads( state, facing, rand ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     @Deprecated | ||||
|     public List<BakedQuad> getQuads( BlockState state, Direction facing, @Nonnull Random rand, @Nonnull IModelData data ) | ||||
|     { | ||||
|         return familyModel.getQuads( state, facing, rand, data ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean useAmbientOcclusion() | ||||
|     { | ||||
|         return familyModel.useAmbientOcclusion(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean hasDepth() | ||||
|     { | ||||
|         return familyModel.hasDepth(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean isBuiltin() | ||||
|     { | ||||
|         return familyModel.isBuiltin(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean isSideLit() | ||||
|     { | ||||
|         return familyModel.isSideLit(); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     @Deprecated | ||||
|     public Sprite getSprite() | ||||
|     { | ||||
|         return familyModel.getSprite(); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     @Deprecated | ||||
|     public ModelTransformation getTransformation() | ||||
|     { | ||||
|         return familyModel.getTransformation(); | ||||
|     } | ||||
|  | ||||
| } | ||||
| @@ -0,0 +1,35 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.core.apis; | ||||
|  | ||||
| import dan200.computercraft.api.lua.ILuaAPIFactory; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.Collection; | ||||
| import java.util.Collections; | ||||
| import java.util.LinkedHashSet; | ||||
| import java.util.Objects; | ||||
|  | ||||
| public final class ApiFactories | ||||
| { | ||||
|     private ApiFactories() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     private static final Collection<ILuaAPIFactory> factories = new LinkedHashSet<>(); | ||||
|     private static final Collection<ILuaAPIFactory> factoriesView = Collections.unmodifiableCollection( factories ); | ||||
|  | ||||
|     public static synchronized void register( @Nonnull ILuaAPIFactory factory ) | ||||
|     { | ||||
|         Objects.requireNonNull( factory, "provider cannot be null" ); | ||||
|         factories.add( factory ); | ||||
|     } | ||||
|  | ||||
|     public static Iterable<ILuaAPIFactory> getAll() | ||||
|     { | ||||
|         return factoriesView; | ||||
|     } | ||||
| } | ||||
							
								
								
									
										147
									
								
								src/main/java/dan200/computercraft/core/apis/ComputerAccess.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										147
									
								
								src/main/java/dan200/computercraft/core/apis/ComputerAccess.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,147 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.core.apis; | ||||
|  | ||||
| import dan200.computercraft.api.filesystem.IMount; | ||||
| import dan200.computercraft.api.filesystem.IWritableMount; | ||||
| import dan200.computercraft.api.peripheral.IComputerAccess; | ||||
| import dan200.computercraft.api.peripheral.IWorkMonitor; | ||||
| import dan200.computercraft.core.filesystem.FileSystem; | ||||
| import dan200.computercraft.core.filesystem.FileSystemException; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.util.HashSet; | ||||
| import java.util.Objects; | ||||
| import java.util.Set; | ||||
|  | ||||
| public abstract class ComputerAccess implements IComputerAccess | ||||
| { | ||||
|     private final IAPIEnvironment m_environment; | ||||
|     private final Set<String> m_mounts = new HashSet<>(); | ||||
|  | ||||
|     protected ComputerAccess( IAPIEnvironment environment ) | ||||
|     { | ||||
|         this.m_environment = environment; | ||||
|     } | ||||
|  | ||||
|     public void unmountAll() | ||||
|     { | ||||
|         FileSystem fileSystem = m_environment.getFileSystem(); | ||||
|         for( String mount : m_mounts ) | ||||
|         { | ||||
|             fileSystem.unmount( mount ); | ||||
|         } | ||||
|         m_mounts.clear(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public synchronized String mount( @Nonnull String desiredLoc, @Nonnull IMount mount, @Nonnull String driveName ) | ||||
|     { | ||||
|         Objects.requireNonNull( desiredLoc, "desiredLocation cannot be null" ); | ||||
|         Objects.requireNonNull( mount, "mount cannot be null" ); | ||||
|         Objects.requireNonNull( driveName, "driveName cannot be null" ); | ||||
|  | ||||
|         // Mount the location | ||||
|         String location; | ||||
|         FileSystem fileSystem = m_environment.getFileSystem(); | ||||
|         if( fileSystem == null ) throw new IllegalStateException( "File system has not been created" ); | ||||
|  | ||||
|         synchronized( fileSystem ) | ||||
|         { | ||||
|             location = findFreeLocation( desiredLoc ); | ||||
|             if( location != null ) | ||||
|             { | ||||
|                 try | ||||
|                 { | ||||
|                     fileSystem.mount( driveName, location, mount ); | ||||
|                 } | ||||
|                 catch( FileSystemException ignored ) | ||||
|                 { | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         if( location != null ) m_mounts.add( location ); | ||||
|         return location; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public synchronized String mountWritable( @Nonnull String desiredLoc, @Nonnull IWritableMount mount, @Nonnull String driveName ) | ||||
|     { | ||||
|         Objects.requireNonNull( desiredLoc, "desiredLocation cannot be null" ); | ||||
|         Objects.requireNonNull( mount, "mount cannot be null" ); | ||||
|         Objects.requireNonNull( driveName, "driveName cannot be null" ); | ||||
|  | ||||
|         // Mount the location | ||||
|         String location; | ||||
|         FileSystem fileSystem = m_environment.getFileSystem(); | ||||
|         if( fileSystem == null ) throw new IllegalStateException( "File system has not been created" ); | ||||
|  | ||||
|         synchronized( fileSystem ) | ||||
|         { | ||||
|             location = findFreeLocation( desiredLoc ); | ||||
|             if( location != null ) | ||||
|             { | ||||
|                 try | ||||
|                 { | ||||
|                     fileSystem.mountWritable( driveName, location, mount ); | ||||
|                 } | ||||
|                 catch( FileSystemException ignored ) | ||||
|                 { | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         if( location != null ) m_mounts.add( location ); | ||||
|         return location; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void unmount( String location ) | ||||
|     { | ||||
|         if( location == null ) return; | ||||
|         if( !m_mounts.contains( location ) ) throw new IllegalStateException( "You didn't mount this location" ); | ||||
|  | ||||
|         m_environment.getFileSystem().unmount( location ); | ||||
|         m_mounts.remove( location ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public int getID() | ||||
|     { | ||||
|         return m_environment.getComputerID(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void queueEvent( @Nonnull String event, Object... arguments ) | ||||
|     { | ||||
|         Objects.requireNonNull( event, "event cannot be null" ); | ||||
|         m_environment.queueEvent( event, arguments ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public IWorkMonitor getMainThreadMonitor() | ||||
|     { | ||||
|         return m_environment.getMainThreadMonitor(); | ||||
|     } | ||||
|  | ||||
|     private String findFreeLocation( String desiredLoc ) | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             FileSystem fileSystem = m_environment.getFileSystem(); | ||||
|             if( !fileSystem.exists( desiredLoc ) ) return desiredLoc; | ||||
|  | ||||
|             // We used to check foo2, foo3, foo4, etc here but the disk drive does this itself now | ||||
|             return null; | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             return null; | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										498
									
								
								src/main/java/dan200/computercraft/core/apis/FSAPI.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										498
									
								
								src/main/java/dan200/computercraft/core/apis/FSAPI.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,498 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.core.apis; | ||||
|  | ||||
| import dan200.computercraft.api.lua.ILuaAPI; | ||||
| import dan200.computercraft.api.lua.LuaException; | ||||
| import dan200.computercraft.api.lua.LuaFunction; | ||||
| import dan200.computercraft.core.apis.handles.BinaryReadableHandle; | ||||
| import dan200.computercraft.core.apis.handles.BinaryWritableHandle; | ||||
| import dan200.computercraft.core.apis.handles.EncodedReadableHandle; | ||||
| import dan200.computercraft.core.apis.handles.EncodedWritableHandle; | ||||
| import dan200.computercraft.core.filesystem.FileSystem; | ||||
| import dan200.computercraft.core.filesystem.FileSystemException; | ||||
| import dan200.computercraft.core.filesystem.FileSystemWrapper; | ||||
| import dan200.computercraft.core.tracking.TrackingField; | ||||
|  | ||||
| import java.io.BufferedReader; | ||||
| import java.io.BufferedWriter; | ||||
| import java.nio.channels.ReadableByteChannel; | ||||
| import java.nio.channels.WritableByteChannel; | ||||
| import java.nio.file.attribute.BasicFileAttributes; | ||||
| import java.nio.file.attribute.FileTime; | ||||
| import java.util.HashMap; | ||||
| import java.util.Map; | ||||
| import java.util.OptionalLong; | ||||
| import java.util.function.Function; | ||||
|  | ||||
| /** | ||||
|  * The FS API allows you to manipulate files and the filesystem. | ||||
|  * | ||||
|  * @cc.module fs | ||||
|  */ | ||||
| public class FSAPI implements ILuaAPI | ||||
| { | ||||
|     private final IAPIEnvironment environment; | ||||
|     private FileSystem fileSystem = null; | ||||
|  | ||||
|     public FSAPI( IAPIEnvironment env ) | ||||
|     { | ||||
|         environment = env; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public String[] getNames() | ||||
|     { | ||||
|         return new String[] { "fs" }; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void startup() | ||||
|     { | ||||
|         fileSystem = environment.getFileSystem(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void shutdown() | ||||
|     { | ||||
|         fileSystem = null; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns a list of files in a directory. | ||||
|      * | ||||
|      * @param path The path to list. | ||||
|      * @return A table with a list of files in the directory. | ||||
|      * @throws LuaException If the path doesn't exist. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final String[] list( String path ) throws LuaException | ||||
|     { | ||||
|         environment.addTrackingChange( TrackingField.FS_OPS ); | ||||
|         try | ||||
|         { | ||||
|             return fileSystem.list( path ); | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             throw new LuaException( e.getMessage() ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Combines two parts of a path into one full path, adding separators as | ||||
|      * needed. | ||||
|      * | ||||
|      * @param pathA The first part of the path. For example, a parent directory path. | ||||
|      * @param pathB The second part of the path. For example, a file name. | ||||
|      * @return The new path, with separators added between parts as needed. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final String combine( String pathA, String pathB ) | ||||
|     { | ||||
|         return fileSystem.combine( pathA, pathB ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns the file name portion of a path. | ||||
|      * | ||||
|      * @param path The path to get the name from. | ||||
|      * @return The final part of the path (the file name). | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final String getName( String path ) | ||||
|     { | ||||
|         return FileSystem.getName( path ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns the parent directory portion of a path. | ||||
|      * | ||||
|      * @param path The path to get the directory from. | ||||
|      * @return The path with the final part removed (the parent directory). | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final String getDir( String path ) | ||||
|     { | ||||
|         return FileSystem.getDirectory( path ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns the size of the specified file. | ||||
|      * | ||||
|      * @param path The file to get the file size of. | ||||
|      * @return The size of the file, in bytes. | ||||
|      * @throws LuaException If the path doesn't exist. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final long getSize( String path ) throws LuaException | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             return fileSystem.getSize( path ); | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             throw new LuaException( e.getMessage() ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns whether the specified path exists. | ||||
|      * | ||||
|      * @param path The path to check the existence of. | ||||
|      * @return Whether the path exists. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final boolean exists( String path ) | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             return fileSystem.exists( path ); | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             return false; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns whether the specified path is a directory. | ||||
|      * | ||||
|      * @param path The path to check. | ||||
|      * @return Whether the path is a directory. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final boolean isDir( String path ) | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             return fileSystem.isDir( path ); | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             return false; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns whether a path is read-only. | ||||
|      * | ||||
|      * @param path The path to check. | ||||
|      * @return Whether the path cannot be written to. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final boolean isReadOnly( String path ) | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             return fileSystem.isReadOnly( path ); | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             return false; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Creates a directory, and any missing parents, at the specified path. | ||||
|      * | ||||
|      * @param path The path to the directory to create. | ||||
|      * @throws LuaException If the directory couldn't be created. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final void makeDir( String path ) throws LuaException | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             environment.addTrackingChange( TrackingField.FS_OPS ); | ||||
|             fileSystem.makeDir( path ); | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             throw new LuaException( e.getMessage() ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Moves a file or directory from one path to another. | ||||
|      * | ||||
|      * Any parent directories are created as needed. | ||||
|      * | ||||
|      * @param path The current file or directory to move from. | ||||
|      * @param dest The destination path for the file or directory. | ||||
|      * @throws LuaException If the file or directory couldn't be moved. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final void move( String path, String dest ) throws LuaException | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             environment.addTrackingChange( TrackingField.FS_OPS ); | ||||
|             fileSystem.move( path, dest ); | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             throw new LuaException( e.getMessage() ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Copies a file or directory to a new path. | ||||
|      * | ||||
|      * Any parent directories are created as needed. | ||||
|      * | ||||
|      * @param path The file or directory to copy. | ||||
|      * @param dest The path to the destination file or directory. | ||||
|      * @throws LuaException If the file or directory couldn't be copied. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final void copy( String path, String dest ) throws LuaException | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             environment.addTrackingChange( TrackingField.FS_OPS ); | ||||
|             fileSystem.copy( path, dest ); | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             throw new LuaException( e.getMessage() ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Deletes a file or directory. | ||||
|      * | ||||
|      * If the path points to a directory, all of the enclosed files and | ||||
|      * subdirectories are also deleted. | ||||
|      * | ||||
|      * @param path The path to the file or directory to delete. | ||||
|      * @throws LuaException If the file or directory couldn't be deleted. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final void delete( String path ) throws LuaException | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             environment.addTrackingChange( TrackingField.FS_OPS ); | ||||
|             fileSystem.delete( path ); | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             throw new LuaException( e.getMessage() ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     // FIXME: Add individual handle type documentation | ||||
|  | ||||
|     /** | ||||
|      * Opens a file for reading or writing at a path. | ||||
|      * | ||||
|      * The mode parameter can be {@code r} to read, {@code w} to write (deleting | ||||
|      * all contents), or {@code a} to append (keeping contents). If {@code b} is | ||||
|      * added to the end, the file will be opened in binary mode; otherwise, it's | ||||
|      * opened in text mode. | ||||
|      * | ||||
|      * @param path The path to the file to open. | ||||
|      * @param mode The mode to open the file with. | ||||
|      * @return A file handle object for the file, or {@code nil} + an error message on error. | ||||
|      * @throws LuaException If an invalid mode was specified. | ||||
|      * @cc.treturn [1] table A file handle object for the file. | ||||
|      * @cc.treturn [2] nil If the file does not exist, or cannot be opened. | ||||
|      * @cc.treturn string|nil A message explaining why the file cannot be opened. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final Object[] open( String path, String mode ) throws LuaException | ||||
|     { | ||||
|         environment.addTrackingChange( TrackingField.FS_OPS ); | ||||
|         try | ||||
|         { | ||||
|             switch( mode ) | ||||
|             { | ||||
|                 case "r": | ||||
|                 { | ||||
|                     // Open the file for reading, then create a wrapper around the reader | ||||
|                     FileSystemWrapper<BufferedReader> reader = fileSystem.openForRead( path, EncodedReadableHandle::openUtf8 ); | ||||
|                     return new Object[] { new EncodedReadableHandle( reader.get(), reader ) }; | ||||
|                 } | ||||
|                 case "w": | ||||
|                 { | ||||
|                     // Open the file for writing, then create a wrapper around the writer | ||||
|                     FileSystemWrapper<BufferedWriter> writer = fileSystem.openForWrite( path, false, EncodedWritableHandle::openUtf8 ); | ||||
|                     return new Object[] { new EncodedWritableHandle( writer.get(), writer ) }; | ||||
|                 } | ||||
|                 case "a": | ||||
|                 { | ||||
|                     // Open the file for appending, then create a wrapper around the writer | ||||
|                     FileSystemWrapper<BufferedWriter> writer = fileSystem.openForWrite( path, true, EncodedWritableHandle::openUtf8 ); | ||||
|                     return new Object[] { new EncodedWritableHandle( writer.get(), writer ) }; | ||||
|                 } | ||||
|                 case "rb": | ||||
|                 { | ||||
|                     // Open the file for binary reading, then create a wrapper around the reader | ||||
|                     FileSystemWrapper<ReadableByteChannel> reader = fileSystem.openForRead( path, Function.identity() ); | ||||
|                     return new Object[] { BinaryReadableHandle.of( reader.get(), reader ) }; | ||||
|                 } | ||||
|                 case "wb": | ||||
|                 { | ||||
|                     // Open the file for binary writing, then create a wrapper around the writer | ||||
|                     FileSystemWrapper<WritableByteChannel> writer = fileSystem.openForWrite( path, false, Function.identity() ); | ||||
|                     return new Object[] { BinaryWritableHandle.of( writer.get(), writer ) }; | ||||
|                 } | ||||
|                 case "ab": | ||||
|                 { | ||||
|                     // Open the file for binary appending, then create a wrapper around the reader | ||||
|                     FileSystemWrapper<WritableByteChannel> writer = fileSystem.openForWrite( path, true, Function.identity() ); | ||||
|                     return new Object[] { BinaryWritableHandle.of( writer.get(), writer ) }; | ||||
|                 } | ||||
|                 default: | ||||
|                     throw new LuaException( "Unsupported mode" ); | ||||
|             } | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             return new Object[] { null, e.getMessage() }; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns the name of the mount that the specified path is located on. | ||||
|      * | ||||
|      * @param path The path to get the drive of. | ||||
|      * @return The name of the drive that the file is on; e.g. {@code hdd} for local files, or {@code rom} for ROM files. | ||||
|      * @throws LuaException If the path doesn't exist. | ||||
|      * @cc.treturn string The name of the drive that the file is on; e.g. {@code hdd} for local files, or {@code rom} for ROM files. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final Object[] getDrive( String path ) throws LuaException | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             return fileSystem.exists( path ) ? new Object[] { fileSystem.getMountLabel( path ) } : null; | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             throw new LuaException( e.getMessage() ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns the amount of free space available on the drive the path is | ||||
|      * located on. | ||||
|      * | ||||
|      * @param path The path to check the free space for. | ||||
|      * @return The amount of free space available, in bytes. | ||||
|      * @throws LuaException If the path doesn't exist. | ||||
|      * @cc.treturn number|"unlimited" The amount of free space available, in bytes, or "unlimited". | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final Object getFreeSpace( String path ) throws LuaException | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             long freeSpace = fileSystem.getFreeSpace( path ); | ||||
|             return freeSpace >= 0 ? freeSpace : "unlimited"; | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             throw new LuaException( e.getMessage() ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Searches for files matching a string with wildcards. | ||||
|      * | ||||
|      * This string is formatted like a normal path string, but can include any | ||||
|      * number of wildcards ({@code *}) to look for files matching anything. | ||||
|      * For example, {@code rom/* /command*} will look for any path starting with | ||||
|      * {@code command} inside any subdirectory of {@code /rom}. | ||||
|      * | ||||
|      * @param path The wildcard-qualified path to search for. | ||||
|      * @return A list of paths that match the search string. | ||||
|      * @throws LuaException If the path doesn't exist. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final String[] find( String path ) throws LuaException | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             environment.addTrackingChange( TrackingField.FS_OPS ); | ||||
|             return fileSystem.find( path ); | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             throw new LuaException( e.getMessage() ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns true if a path is mounted to the parent filesystem. | ||||
|      * | ||||
|      * The root filesystem "/" is considered a mount, along with disk folders and the rom folder. Other programs | ||||
|      * (such as network shares) can extend this to make other mount types by correctly assigning their return value for | ||||
|      * getDrive. | ||||
|      * | ||||
|      * @param path The path of the drive to get. | ||||
|      * @return The drive's capacity. | ||||
|      * @throws LuaException If the capacity cannot be determined. | ||||
|      * @cc.treturn number|nil This drive's capacity. This will be nil for "read-only" drives, such as the ROM or | ||||
|      * treasure disks. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final Object getCapacity( String path ) throws LuaException | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             OptionalLong capacity = fileSystem.getCapacity( path ); | ||||
|             return capacity.isPresent() ? capacity.getAsLong() : null; | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             throw new LuaException( e.getMessage() ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get attributes about a specific file or folder. | ||||
|      * | ||||
|      * The returned attributes table contains information about the size of the file, whether it is a directory, and | ||||
|      * when it was created and last modified. | ||||
|      * | ||||
|      * The creation and modification times are given as the number of milliseconds since the UNIX epoch. This may be | ||||
|      * given to {@link OSAPI#date} in order to convert it to more usable form. | ||||
|      * | ||||
|      * @param path The path to get attributes for. | ||||
|      * @return The resulting attributes. | ||||
|      * @throws LuaException If the path does not exist. | ||||
|      * @cc.treturn { size = number, isDir = boolean, created = number, modified = number } The resulting attributes. | ||||
|      * @see #getSize If you only care about the file's size. | ||||
|      * @see #isDir If you only care whether a path is a directory or not. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final Map<String, Object> attributes( String path ) throws LuaException | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             BasicFileAttributes attributes = fileSystem.getAttributes( path ); | ||||
|             Map<String, Object> result = new HashMap<>(); | ||||
|             result.put( "modification", getFileTime( attributes.lastModifiedTime() ) ); | ||||
|             result.put( "modified", getFileTime( attributes.lastModifiedTime() ) ); | ||||
|             result.put( "created", getFileTime( attributes.creationTime() ) ); | ||||
|             result.put( "size", attributes.isDirectory() ? 0 : attributes.size() ); | ||||
|             result.put( "isDir", attributes.isDirectory() ); | ||||
|             return result; | ||||
|         } | ||||
|         catch( FileSystemException e ) | ||||
|         { | ||||
|             throw new LuaException( e.getMessage() ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     private static long getFileTime( FileTime time ) | ||||
|     { | ||||
|         return time == null ? 0 : time.toMillis(); | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,35 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
|  | ||||
| package dan200.computercraft.core.apis; | ||||
|  | ||||
| import dan200.computercraft.api.lua.LuaException; | ||||
|  | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| /** | ||||
|  * A Lua exception which does not contain its stack trace. | ||||
|  */ | ||||
| public class FastLuaException extends LuaException | ||||
| { | ||||
|     private static final long serialVersionUID = 5957864899303561143L; | ||||
|  | ||||
|     public FastLuaException( @Nullable String message ) | ||||
|     { | ||||
|         super( message ); | ||||
|     } | ||||
|  | ||||
|     public FastLuaException( @Nullable String message, int level ) | ||||
|     { | ||||
|         super( message, level ); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public synchronized Throwable fillInStackTrace() | ||||
|     { | ||||
|         return this; | ||||
|     } | ||||
| } | ||||
							
								
								
									
										202
									
								
								src/main/java/dan200/computercraft/core/apis/HTTPAPI.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										202
									
								
								src/main/java/dan200/computercraft/core/apis/HTTPAPI.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,202 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.core.apis; | ||||
|  | ||||
| import dan200.computercraft.ComputerCraft; | ||||
| import dan200.computercraft.api.lua.IArguments; | ||||
| import dan200.computercraft.api.lua.ILuaAPI; | ||||
| import dan200.computercraft.api.lua.LuaException; | ||||
| import dan200.computercraft.api.lua.LuaFunction; | ||||
| import dan200.computercraft.core.apis.http.*; | ||||
| import dan200.computercraft.core.apis.http.request.HttpRequest; | ||||
| import dan200.computercraft.core.apis.http.websocket.Websocket; | ||||
| import io.netty.handler.codec.http.DefaultHttpHeaders; | ||||
| import io.netty.handler.codec.http.HttpHeaders; | ||||
| import io.netty.handler.codec.http.HttpMethod; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.net.URI; | ||||
| import java.util.Collections; | ||||
| import java.util.Locale; | ||||
| import java.util.Map; | ||||
| import java.util.Optional; | ||||
|  | ||||
| import static dan200.computercraft.core.apis.TableHelper.*; | ||||
|  | ||||
| /** | ||||
|  * The http library allows communicating with web servers, sending and receiving data from them. | ||||
|  * | ||||
|  * @cc.module http | ||||
|  * @hidden | ||||
|  */ | ||||
| public class HTTPAPI implements ILuaAPI | ||||
| { | ||||
|     private final IAPIEnvironment m_apiEnvironment; | ||||
|  | ||||
|     private final ResourceGroup<CheckUrl> checkUrls = new ResourceGroup<>(); | ||||
|     private final ResourceGroup<HttpRequest> requests = new ResourceQueue<>( () -> ComputerCraft.httpMaxRequests ); | ||||
|     private final ResourceGroup<Websocket> websockets = new ResourceGroup<>( () -> ComputerCraft.httpMaxWebsockets ); | ||||
|  | ||||
|     public HTTPAPI( IAPIEnvironment environment ) | ||||
|     { | ||||
|         m_apiEnvironment = environment; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public String[] getNames() | ||||
|     { | ||||
|         return new String[] { "http" }; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void startup() | ||||
|     { | ||||
|         checkUrls.startup(); | ||||
|         requests.startup(); | ||||
|         websockets.startup(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void shutdown() | ||||
|     { | ||||
|         checkUrls.shutdown(); | ||||
|         requests.shutdown(); | ||||
|         websockets.shutdown(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void update() | ||||
|     { | ||||
|         // It's rather ugly to run this here, but we need to clean up | ||||
|         // resources as often as possible to reduce blocking. | ||||
|         Resource.cleanup(); | ||||
|     } | ||||
|  | ||||
|     @LuaFunction | ||||
|     public final Object[] request( IArguments args ) throws LuaException | ||||
|     { | ||||
|         String address, postString, requestMethod; | ||||
|         Map<?, ?> headerTable; | ||||
|         boolean binary, redirect; | ||||
|  | ||||
|         if( args.get( 0 ) instanceof Map ) | ||||
|         { | ||||
|             Map<?, ?> options = args.getTable( 0 ); | ||||
|             address = getStringField( options, "url" ); | ||||
|             postString = optStringField( options, "body", null ); | ||||
|             headerTable = optTableField( options, "headers", Collections.emptyMap() ); | ||||
|             binary = optBooleanField( options, "binary", false ); | ||||
|             requestMethod = optStringField( options, "method", null ); | ||||
|             redirect = optBooleanField( options, "redirect", true ); | ||||
|  | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             // Get URL and post information | ||||
|             address = args.getString( 0 ); | ||||
|             postString = args.optString( 1, null ); | ||||
|             headerTable = args.optTable( 2, Collections.emptyMap() ); | ||||
|             binary = args.optBoolean( 3, false ); | ||||
|             requestMethod = null; | ||||
|             redirect = true; | ||||
|         } | ||||
|  | ||||
|         HttpHeaders headers = getHeaders( headerTable ); | ||||
|  | ||||
|         HttpMethod httpMethod; | ||||
|         if( requestMethod == null ) | ||||
|         { | ||||
|             httpMethod = postString == null ? HttpMethod.GET : HttpMethod.POST; | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             httpMethod = HttpMethod.valueOf( requestMethod.toUpperCase( Locale.ROOT ) ); | ||||
|             if( httpMethod == null || requestMethod.equalsIgnoreCase( "CONNECT" ) ) | ||||
|             { | ||||
|                 throw new LuaException( "Unsupported HTTP method" ); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         try | ||||
|         { | ||||
|             URI uri = HttpRequest.checkUri( address ); | ||||
|             HttpRequest request = new HttpRequest( requests, m_apiEnvironment, address, postString, headers, binary, redirect ); | ||||
|  | ||||
|             // Make the request | ||||
|             request.queue( r -> r.request( uri, httpMethod ) ); | ||||
|  | ||||
|             return new Object[] { true }; | ||||
|         } | ||||
|         catch( HTTPRequestException e ) | ||||
|         { | ||||
|             return new Object[] { false, e.getMessage() }; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @LuaFunction | ||||
|     public final Object[] checkURL( String address ) | ||||
|     { | ||||
|         try | ||||
|         { | ||||
|             URI uri = HttpRequest.checkUri( address ); | ||||
|             new CheckUrl( checkUrls, m_apiEnvironment, address, uri ).queue( CheckUrl::run ); | ||||
|  | ||||
|             return new Object[] { true }; | ||||
|         } | ||||
|         catch( HTTPRequestException e ) | ||||
|         { | ||||
|             return new Object[] { false, e.getMessage() }; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @LuaFunction | ||||
|     public final Object[] websocket( String address, Optional<Map<?, ?>> headerTbl ) throws LuaException | ||||
|     { | ||||
|         if( !ComputerCraft.httpWebsocketEnabled ) | ||||
|         { | ||||
|             throw new LuaException( "Websocket connections are disabled" ); | ||||
|         } | ||||
|  | ||||
|         HttpHeaders headers = getHeaders( headerTbl.orElse( Collections.emptyMap() ) ); | ||||
|  | ||||
|         try | ||||
|         { | ||||
|             URI uri = Websocket.checkUri( address ); | ||||
|             if( !new Websocket( websockets, m_apiEnvironment, uri, address, headers ).queue( Websocket::connect ) ) | ||||
|             { | ||||
|                 throw new LuaException( "Too many websockets already open" ); | ||||
|             } | ||||
|  | ||||
|             return new Object[] { true }; | ||||
|         } | ||||
|         catch( HTTPRequestException e ) | ||||
|         { | ||||
|             return new Object[] { false, e.getMessage() }; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     private static HttpHeaders getHeaders( @Nonnull Map<?, ?> headerTable ) throws LuaException | ||||
|     { | ||||
|         HttpHeaders headers = new DefaultHttpHeaders(); | ||||
|         for( Map.Entry<?, ?> entry : headerTable.entrySet() ) | ||||
|         { | ||||
|             Object value = entry.getValue(); | ||||
|             if( entry.getKey() instanceof String && value instanceof String ) | ||||
|             { | ||||
|                 try | ||||
|                 { | ||||
|                     headers.add( (String) entry.getKey(), value ); | ||||
|                 } | ||||
|                 catch( IllegalArgumentException e ) | ||||
|                 { | ||||
|                     throw new LuaException( e.getMessage() ); | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|         return headers; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,79 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.core.apis; | ||||
|  | ||||
| import dan200.computercraft.api.peripheral.IPeripheral; | ||||
| import dan200.computercraft.api.peripheral.IWorkMonitor; | ||||
| import dan200.computercraft.core.computer.ComputerSide; | ||||
| import dan200.computercraft.core.computer.IComputerEnvironment; | ||||
| import dan200.computercraft.core.filesystem.FileSystem; | ||||
| import dan200.computercraft.core.terminal.Terminal; | ||||
| import dan200.computercraft.core.tracking.TrackingField; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
|  | ||||
| public interface IAPIEnvironment | ||||
| { | ||||
|     String TIMER_EVENT = "timer"; | ||||
|  | ||||
|     @FunctionalInterface | ||||
|     interface IPeripheralChangeListener | ||||
|     { | ||||
|         void onPeripheralChanged( ComputerSide side, @Nullable IPeripheral newPeripheral ); | ||||
|     } | ||||
|  | ||||
|     int getComputerID(); | ||||
|  | ||||
|     @Nonnull | ||||
|     IComputerEnvironment getComputerEnvironment(); | ||||
|  | ||||
|     @Nonnull | ||||
|     IWorkMonitor getMainThreadMonitor(); | ||||
|  | ||||
|     @Nonnull | ||||
|     Terminal getTerminal(); | ||||
|  | ||||
|     FileSystem getFileSystem(); | ||||
|  | ||||
|     void shutdown(); | ||||
|  | ||||
|     void reboot(); | ||||
|  | ||||
|     void queueEvent( String event, Object... args ); | ||||
|  | ||||
|     void setOutput( ComputerSide side, int output ); | ||||
|  | ||||
|     int getOutput( ComputerSide side ); | ||||
|  | ||||
|     int getInput( ComputerSide side ); | ||||
|  | ||||
|     void setBundledOutput( ComputerSide side, int output ); | ||||
|  | ||||
|     int getBundledOutput( ComputerSide side ); | ||||
|  | ||||
|     int getBundledInput( ComputerSide side ); | ||||
|  | ||||
|     void setPeripheralChangeListener( @Nullable IPeripheralChangeListener listener ); | ||||
|  | ||||
|     @Nullable | ||||
|     IPeripheral getPeripheral( ComputerSide side ); | ||||
|  | ||||
|     String getLabel(); | ||||
|  | ||||
|     void setLabel( @Nullable String label ); | ||||
|  | ||||
|     int startTimer( long ticks ); | ||||
|  | ||||
|     void cancelTimer( int id ); | ||||
|  | ||||
|     void addTrackingChange( @Nonnull TrackingField field, long change ); | ||||
|  | ||||
|     default void addTrackingChange( @Nonnull TrackingField field ) | ||||
|     { | ||||
|         addTrackingChange( field, 1 ); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										280
									
								
								src/main/java/dan200/computercraft/core/apis/LuaDateTime.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										280
									
								
								src/main/java/dan200/computercraft/core/apis/LuaDateTime.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,280 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.core.apis; | ||||
|  | ||||
| import dan200.computercraft.api.lua.LuaException; | ||||
|  | ||||
| import java.time.Instant; | ||||
| import java.time.LocalDateTime; | ||||
| import java.time.ZoneId; | ||||
| import java.time.ZoneOffset; | ||||
| import java.time.format.DateTimeFormatterBuilder; | ||||
| import java.time.format.TextStyle; | ||||
| import java.time.temporal.*; | ||||
| import java.util.HashMap; | ||||
| import java.util.Map; | ||||
| import java.util.function.LongUnaryOperator; | ||||
|  | ||||
| final class LuaDateTime | ||||
| { | ||||
|     private LuaDateTime() | ||||
|     { | ||||
|     } | ||||
|  | ||||
|     static void format( DateTimeFormatterBuilder formatter, String format, ZoneOffset offset ) throws LuaException | ||||
|     { | ||||
|         for( int i = 0; i < format.length(); ) | ||||
|         { | ||||
|             char c; | ||||
|             switch( c = format.charAt( i++ ) ) | ||||
|             { | ||||
|                 case '\n': | ||||
|                     formatter.appendLiteral( '\n' ); | ||||
|                     break; | ||||
|                 default: | ||||
|                     formatter.appendLiteral( c ); | ||||
|                     break; | ||||
|                 case '%': | ||||
|                     if( i >= format.length() ) break; | ||||
|                     switch( c = format.charAt( i++ ) ) | ||||
|                     { | ||||
|                         default: | ||||
|                             throw new LuaException( "bad argument #1: invalid conversion specifier '%" + c + "'" ); | ||||
|  | ||||
|                         case '%': | ||||
|                             formatter.appendLiteral( '%' ); | ||||
|                             break; | ||||
|                         case 'a': | ||||
|                             formatter.appendText( ChronoField.DAY_OF_WEEK, TextStyle.SHORT ); | ||||
|                             break; | ||||
|                         case 'A': | ||||
|                             formatter.appendText( ChronoField.DAY_OF_WEEK, TextStyle.FULL ); | ||||
|                             break; | ||||
|                         case 'b': | ||||
|                         case 'h': | ||||
|                             formatter.appendText( ChronoField.MONTH_OF_YEAR, TextStyle.SHORT ); | ||||
|                             break; | ||||
|                         case 'B': | ||||
|                             formatter.appendText( ChronoField.MONTH_OF_YEAR, TextStyle.FULL ); | ||||
|                             break; | ||||
|                         case 'c': | ||||
|                             format( formatter, "%a %b %e %H:%M:%S %Y", offset ); | ||||
|                             break; | ||||
|                         case 'C': | ||||
|                             formatter.appendValueReduced( CENTURY, 2, 2, 0 ); | ||||
|                             break; | ||||
|                         case 'd': | ||||
|                             formatter.appendValue( ChronoField.DAY_OF_MONTH, 2 ); | ||||
|                             break; | ||||
|                         case 'D': | ||||
|                         case 'x': | ||||
|                             format( formatter, "%m/%d/%y", offset ); | ||||
|                             break; | ||||
|                         case 'e': | ||||
|                             formatter.padNext( 2 ).appendValue( ChronoField.DAY_OF_MONTH ); | ||||
|                             break; | ||||
|                         case 'F': | ||||
|                             format( formatter, "%Y-%m-%d", offset ); | ||||
|                             break; | ||||
|                         case 'g': | ||||
|                             formatter.appendValueReduced( IsoFields.WEEK_BASED_YEAR, 2, 2, 0 ); | ||||
|                             break; | ||||
|                         case 'G': | ||||
|                             formatter.appendValue( IsoFields.WEEK_BASED_YEAR ); | ||||
|                             break; | ||||
|                         case 'H': | ||||
|                             formatter.appendValue( ChronoField.HOUR_OF_DAY, 2 ); | ||||
|                             break; | ||||
|                         case 'I': | ||||
|                             formatter.appendValue( ChronoField.HOUR_OF_AMPM ); | ||||
|                             break; | ||||
|                         case 'j': | ||||
|                             formatter.appendValue( ChronoField.DAY_OF_YEAR, 3 ); | ||||
|                             break; | ||||
|                         case 'm': | ||||
|                             formatter.appendValue( ChronoField.MONTH_OF_YEAR, 2 ); | ||||
|                             break; | ||||
|                         case 'M': | ||||
|                             formatter.appendValue( ChronoField.MINUTE_OF_HOUR, 2 ); | ||||
|                             break; | ||||
|                         case 'n': | ||||
|                             formatter.appendLiteral( '\n' ); | ||||
|                             break; | ||||
|                         case 'p': | ||||
|                             formatter.appendText( ChronoField.AMPM_OF_DAY ); | ||||
|                             break; | ||||
|                         case 'r': | ||||
|                             format( formatter, "%I:%M:%S %p", offset ); | ||||
|                             break; | ||||
|                         case 'R': | ||||
|                             format( formatter, "%H:%M", offset ); | ||||
|                             break; | ||||
|                         case 'S': | ||||
|                             formatter.appendValue( ChronoField.SECOND_OF_MINUTE, 2 ); | ||||
|                             break; | ||||
|                         case 't': | ||||
|                             formatter.appendLiteral( '\t' ); | ||||
|                             break; | ||||
|                         case 'T': | ||||
|                         case 'X': | ||||
|                             format( formatter, "%H:%M:%S", offset ); | ||||
|                             break; | ||||
|                         case 'u': | ||||
|                             formatter.appendValue( ChronoField.DAY_OF_WEEK ); | ||||
|                             break; | ||||
|                         case 'U': | ||||
|                             formatter.appendValue( ChronoField.ALIGNED_WEEK_OF_YEAR, 2 ); | ||||
|                             break; | ||||
|                         case 'V': | ||||
|                             formatter.appendValue( IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2 ); | ||||
|                             break; | ||||
|                         case 'w': | ||||
|                             formatter.appendValue( ZERO_WEEK ); | ||||
|                             break; | ||||
|                         case 'W': | ||||
|                             formatter.appendValue( WeekFields.ISO.weekOfYear(), 2 ); | ||||
|                             break; | ||||
|                         case 'y': | ||||
|                             formatter.appendValueReduced( ChronoField.YEAR, 2, 2, 0 ); | ||||
|                             break; | ||||
|                         case 'Y': | ||||
|                             formatter.appendValue( ChronoField.YEAR ); | ||||
|                             break; | ||||
|                         case 'z': | ||||
|                             formatter.appendOffset( "+HHMM", "+0000" ); | ||||
|                             break; | ||||
|                         case 'Z': | ||||
|                             formatter.appendChronologyId(); | ||||
|                             break; | ||||
|                     } | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     static long fromTable( Map<?, ?> table ) throws LuaException | ||||
|     { | ||||
|         int year = getField( table, "year", -1 ); | ||||
|         int month = getField( table, "month", -1 ); | ||||
|         int day = getField( table, "day", -1 ); | ||||
|         int hour = getField( table, "hour", 12 ); | ||||
|         int minute = getField( table, "min", 12 ); | ||||
|         int second = getField( table, "sec", 12 ); | ||||
|         LocalDateTime time = LocalDateTime.of( year, month, day, hour, minute, second ); | ||||
|  | ||||
|         Boolean isDst = getBoolField( table, "isdst" ); | ||||
|         if( isDst != null ) | ||||
|         { | ||||
|             boolean requireDst = isDst; | ||||
|             for( ZoneOffset possibleOffset : ZoneOffset.systemDefault().getRules().getValidOffsets( time ) ) | ||||
|             { | ||||
|                 Instant instant = time.toInstant( possibleOffset ); | ||||
|                 if( possibleOffset.getRules().getDaylightSavings( instant ).isZero() == requireDst ) | ||||
|                 { | ||||
|                     return instant.getEpochSecond(); | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         ZoneOffset offset = ZoneOffset.systemDefault().getRules().getOffset( time ); | ||||
|         return time.toInstant( offset ).getEpochSecond(); | ||||
|     } | ||||
|  | ||||
|     static Map<String, ?> toTable( TemporalAccessor date, ZoneId offset, Instant instant ) | ||||
|     { | ||||
|         HashMap<String, Object> table = new HashMap<>( 9 ); | ||||
|         table.put( "year", date.getLong( ChronoField.YEAR ) ); | ||||
|         table.put( "month", date.getLong( ChronoField.MONTH_OF_YEAR ) ); | ||||
|         table.put( "day", date.getLong( ChronoField.DAY_OF_MONTH ) ); | ||||
|         table.put( "hour", date.getLong( ChronoField.HOUR_OF_DAY ) ); | ||||
|         table.put( "min", date.getLong( ChronoField.MINUTE_OF_HOUR ) ); | ||||
|         table.put( "sec", date.getLong( ChronoField.SECOND_OF_MINUTE ) ); | ||||
|         table.put( "wday", date.getLong( WeekFields.SUNDAY_START.dayOfWeek() ) ); | ||||
|         table.put( "yday", date.getLong( ChronoField.DAY_OF_YEAR ) ); | ||||
|         table.put( "isdst", offset.getRules().isDaylightSavings( instant ) ); | ||||
|         return table; | ||||
|     } | ||||
|  | ||||
|     private static int getField( Map<?, ?> table, String field, int def ) throws LuaException | ||||
|     { | ||||
|         Object value = table.get( field ); | ||||
|         if( value instanceof Number ) return ((Number) value).intValue(); | ||||
|         if( def < 0 ) throw new LuaException( "field \"" + field + "\" missing in date table" ); | ||||
|         return def; | ||||
|     } | ||||
|  | ||||
|     private static Boolean getBoolField( Map<?, ?> table, String field ) throws LuaException | ||||
|     { | ||||
|         Object value = table.get( field ); | ||||
|         if( value instanceof Boolean || value == null ) return (Boolean) value; | ||||
|         throw new LuaException( "field \"" + field + "\" missing in date table" ); | ||||
|     } | ||||
|  | ||||
|     private static final TemporalField CENTURY = map( ChronoField.YEAR, ValueRange.of( 0, 6 ), x -> (x / 100) % 100 ); | ||||
|     private static final TemporalField ZERO_WEEK = map( WeekFields.SUNDAY_START.dayOfWeek(), ValueRange.of( 0, 6 ), x -> x - 1 ); | ||||
|  | ||||
|     private static TemporalField map( TemporalField field, ValueRange range, LongUnaryOperator convert ) | ||||
|     { | ||||
|         return new TemporalField() | ||||
|         { | ||||
|             private final ValueRange range = ValueRange.of( 0, 99 ); | ||||
|  | ||||
|             @Override | ||||
|             public TemporalUnit getBaseUnit() | ||||
|             { | ||||
|                 return field.getBaseUnit(); | ||||
|             } | ||||
|  | ||||
|             @Override | ||||
|             public TemporalUnit getRangeUnit() | ||||
|             { | ||||
|                 return field.getRangeUnit(); | ||||
|             } | ||||
|  | ||||
|             @Override | ||||
|             public ValueRange range() | ||||
|             { | ||||
|                 return range; | ||||
|             } | ||||
|  | ||||
|             @Override | ||||
|             public boolean isDateBased() | ||||
|             { | ||||
|                 return field.isDateBased(); | ||||
|             } | ||||
|  | ||||
|             @Override | ||||
|             public boolean isTimeBased() | ||||
|             { | ||||
|                 return field.isTimeBased(); | ||||
|             } | ||||
|  | ||||
|             @Override | ||||
|             public boolean isSupportedBy( TemporalAccessor temporal ) | ||||
|             { | ||||
|                 return field.isSupportedBy( temporal ); | ||||
|             } | ||||
|  | ||||
|             @Override | ||||
|             public ValueRange rangeRefinedBy( TemporalAccessor temporal ) | ||||
|             { | ||||
|                 return range; | ||||
|             } | ||||
|  | ||||
|             @Override | ||||
|             public long getFrom( TemporalAccessor temporal ) | ||||
|             { | ||||
|                 return convert.applyAsLong( temporal.getLong( field ) ); | ||||
|             } | ||||
|  | ||||
|             @Override | ||||
|             @SuppressWarnings( "unchecked" ) | ||||
|             public <R extends Temporal> R adjustInto( R temporal, long newValue ) | ||||
|             { | ||||
|                 return (R) temporal.with( field, newValue ); | ||||
|             } | ||||
|         }; | ||||
|     } | ||||
| } | ||||
							
								
								
									
										462
									
								
								src/main/java/dan200/computercraft/core/apis/OSAPI.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										462
									
								
								src/main/java/dan200/computercraft/core/apis/OSAPI.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,462 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.core.apis; | ||||
|  | ||||
| import dan200.computercraft.api.lua.IArguments; | ||||
| import dan200.computercraft.api.lua.ILuaAPI; | ||||
| import dan200.computercraft.api.lua.LuaException; | ||||
| import dan200.computercraft.api.lua.LuaFunction; | ||||
| import dan200.computercraft.shared.util.StringUtil; | ||||
| import it.unimi.dsi.fastutil.ints.Int2ObjectMap; | ||||
| import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import java.time.Instant; | ||||
| import java.time.ZoneId; | ||||
| import java.time.ZoneOffset; | ||||
| import java.time.ZonedDateTime; | ||||
| import java.time.format.DateTimeFormatterBuilder; | ||||
| import java.util.*; | ||||
|  | ||||
| import static dan200.computercraft.api.lua.LuaValues.checkFinite; | ||||
|  | ||||
| /** | ||||
|  * The {@link OSAPI} API allows interacting with the current computer. | ||||
|  * | ||||
|  * @cc.module os | ||||
|  */ | ||||
| public class OSAPI implements ILuaAPI | ||||
| { | ||||
|     private final IAPIEnvironment apiEnvironment; | ||||
|  | ||||
|     private final Int2ObjectMap<Alarm> m_alarms = new Int2ObjectOpenHashMap<>(); | ||||
|     private int m_clock; | ||||
|     private double m_time; | ||||
|     private int m_day; | ||||
|  | ||||
|     private int m_nextAlarmToken = 0; | ||||
|  | ||||
|     private static class Alarm implements Comparable<Alarm> | ||||
|     { | ||||
|         final double m_time; | ||||
|         final int m_day; | ||||
|  | ||||
|         Alarm( double time, int day ) | ||||
|         { | ||||
|             m_time = time; | ||||
|             m_day = day; | ||||
|         } | ||||
|  | ||||
|         @Override | ||||
|         public int compareTo( @Nonnull Alarm o ) | ||||
|         { | ||||
|             double t = m_day * 24.0 + m_time; | ||||
|             double ot = m_day * 24.0 + m_time; | ||||
|             return Double.compare( t, ot ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public OSAPI( IAPIEnvironment environment ) | ||||
|     { | ||||
|         apiEnvironment = environment; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public String[] getNames() | ||||
|     { | ||||
|         return new String[] { "os" }; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void startup() | ||||
|     { | ||||
|         m_time = apiEnvironment.getComputerEnvironment().getTimeOfDay(); | ||||
|         m_day = apiEnvironment.getComputerEnvironment().getDay(); | ||||
|         m_clock = 0; | ||||
|  | ||||
|         synchronized( m_alarms ) | ||||
|         { | ||||
|             m_alarms.clear(); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void update() | ||||
|     { | ||||
|         m_clock++; | ||||
|  | ||||
|         // Wait for all of our alarms | ||||
|         synchronized( m_alarms ) | ||||
|         { | ||||
|             double previousTime = m_time; | ||||
|             int previousDay = m_day; | ||||
|             double time = apiEnvironment.getComputerEnvironment().getTimeOfDay(); | ||||
|             int day = apiEnvironment.getComputerEnvironment().getDay(); | ||||
|  | ||||
|             if( time > previousTime || day > previousDay ) | ||||
|             { | ||||
|                 double now = m_day * 24.0 + m_time; | ||||
|                 Iterator<Int2ObjectMap.Entry<Alarm>> it = m_alarms.int2ObjectEntrySet().iterator(); | ||||
|                 while( it.hasNext() ) | ||||
|                 { | ||||
|                     Int2ObjectMap.Entry<Alarm> entry = it.next(); | ||||
|                     Alarm alarm = entry.getValue(); | ||||
|                     double t = alarm.m_day * 24.0 + alarm.m_time; | ||||
|                     if( now >= t ) | ||||
|                     { | ||||
|                         apiEnvironment.queueEvent( "alarm", entry.getIntKey() ); | ||||
|                         it.remove(); | ||||
|                     } | ||||
|                 } | ||||
|             } | ||||
|  | ||||
|             m_time = time; | ||||
|             m_day = day; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void shutdown() | ||||
|     { | ||||
|         synchronized( m_alarms ) | ||||
|         { | ||||
|             m_alarms.clear(); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     private static float getTimeForCalendar( Calendar c ) | ||||
|     { | ||||
|         float time = c.get( Calendar.HOUR_OF_DAY ); | ||||
|         time += c.get( Calendar.MINUTE ) / 60.0f; | ||||
|         time += c.get( Calendar.SECOND ) / (60.0f * 60.0f); | ||||
|         return time; | ||||
|     } | ||||
|  | ||||
|     private static int getDayForCalendar( Calendar c ) | ||||
|     { | ||||
|         GregorianCalendar g = c instanceof GregorianCalendar ? (GregorianCalendar) c : new GregorianCalendar(); | ||||
|         int year = c.get( Calendar.YEAR ); | ||||
|         int day = 0; | ||||
|         for( int y = 1970; y < year; y++ ) | ||||
|         { | ||||
|             day += g.isLeapYear( y ) ? 366 : 365; | ||||
|         } | ||||
|         day += c.get( Calendar.DAY_OF_YEAR ); | ||||
|         return day; | ||||
|     } | ||||
|  | ||||
|     private static long getEpochForCalendar( Calendar c ) | ||||
|     { | ||||
|         return c.getTime().getTime(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Adds an event to the event queue. This event can later be pulled with | ||||
|      * os.pullEvent. | ||||
|      * | ||||
|      * @param name The name of the event to queue. | ||||
|      * @param args The parameters of the event. | ||||
|      * @cc.tparam string name The name of the event to queue. | ||||
|      * @cc.param ... The parameters of the event. | ||||
|      * @cc.see os.pullEvent To pull the event queued | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final void queueEvent( String name, IArguments args ) | ||||
|     { | ||||
|         apiEnvironment.queueEvent( name, args.drop( 1 ).getAll() ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Starts a timer that will run for the specified number of seconds. Once | ||||
|      * the timer fires, a timer event will be added to the queue with the ID | ||||
|      * returned from this function as the first parameter. | ||||
|      * | ||||
|      * @param timer The number of seconds until the timer fires. | ||||
|      * @return The ID of the new timer. | ||||
|      * @throws LuaException If the time is below zero. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final int startTimer( double timer ) throws LuaException | ||||
|     { | ||||
|         return apiEnvironment.startTimer( Math.round( checkFinite( 0, timer ) / 0.05 ) ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Cancels a timer previously started with startTimer. This will stop the | ||||
|      * timer from firing. | ||||
|      * | ||||
|      * @param token The ID of the timer to cancel. | ||||
|      * @see #startTimer To start a timer. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final void cancelTimer( int token ) | ||||
|     { | ||||
|         apiEnvironment.cancelTimer( token ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Sets an alarm that will fire at the specified world time. When it fires, | ||||
|      * an alarm event will be added to the event queue. | ||||
|      * | ||||
|      * @param time The time at which to fire the alarm, in the range [0.0, 24.0). | ||||
|      * @return The ID of the alarm that was set. | ||||
|      * @throws LuaException If the time is out of range. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final int setAlarm( double time ) throws LuaException | ||||
|     { | ||||
|         checkFinite( 0, time ); | ||||
|         if( time < 0.0 || time >= 24.0 ) throw new LuaException( "Number out of range" ); | ||||
|         synchronized( m_alarms ) | ||||
|         { | ||||
|             int day = time > m_time ? m_day : m_day + 1; | ||||
|             m_alarms.put( m_nextAlarmToken, new Alarm( time, day ) ); | ||||
|             return m_nextAlarmToken++; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Cancels an alarm previously started with setAlarm. This will stop the | ||||
|      * alarm from firing. | ||||
|      * | ||||
|      * @param token The ID of the alarm to cancel. | ||||
|      * @see #setAlarm To set an alarm. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final void cancelAlarm( int token ) | ||||
|     { | ||||
|         synchronized( m_alarms ) | ||||
|         { | ||||
|             m_alarms.remove( token ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Shuts down the computer immediately. | ||||
|      */ | ||||
|     @LuaFunction( "shutdown" ) | ||||
|     public final void doShutdown() | ||||
|     { | ||||
|         apiEnvironment.shutdown(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Reboots the computer immediately. | ||||
|      */ | ||||
|     @LuaFunction( "reboot" ) | ||||
|     public final void doReboot() | ||||
|     { | ||||
|         apiEnvironment.reboot(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns the ID of the computer. | ||||
|      * | ||||
|      * @return The ID of the computer. | ||||
|      */ | ||||
|     @LuaFunction( { "getComputerID", "computerID" } ) | ||||
|     public final int getComputerID() | ||||
|     { | ||||
|         return apiEnvironment.getComputerID(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns the label of the computer, or {@code nil} if none is set. | ||||
|      * | ||||
|      * @return The label of the computer. | ||||
|      * @cc.treturn string The label of the computer. | ||||
|      */ | ||||
|     @LuaFunction( { "getComputerLabel", "computerLabel" } ) | ||||
|     public final Object[] getComputerLabel() | ||||
|     { | ||||
|         String label = apiEnvironment.getLabel(); | ||||
|         return label == null ? null : new Object[] { label }; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Set the label of this computer. | ||||
|      * | ||||
|      * @param label The new label. May be {@code nil} in order to clear it. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final void setComputerLabel( Optional<String> label ) | ||||
|     { | ||||
|         apiEnvironment.setLabel( StringUtil.normaliseLabel( label.orElse( null ) ) ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns the number of seconds that the computer has been running. | ||||
|      * | ||||
|      * @return The computer's uptime. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final double clock() | ||||
|     { | ||||
|         return m_clock * 0.05; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns the current time depending on the string passed in. This will | ||||
|      * always be in the range [0.0, 24.0). | ||||
|      * | ||||
|      * * If called with {@code ingame}, the current world time will be returned. | ||||
|      * This is the default if nothing is passed. | ||||
|      * * If called with {@code utc}, returns the hour of the day in UTC time. | ||||
|      * * If called with {@code local}, returns the hour of the day in the | ||||
|      * timezone the server is located in. | ||||
|      * | ||||
|      * This function can also be called with a table returned from {@link #date}, | ||||
|      * which will convert the date fields into a UNIX timestamp (number of | ||||
|      * seconds since 1 January 1970). | ||||
|      * | ||||
|      * @param args The locale of the time, or a table filled by {@code os.date("*t")} to decode. Defaults to {@code ingame} locale if not specified. | ||||
|      * @return The hour of the selected locale, or a UNIX timestamp from the table, depending on the argument passed in. | ||||
|      * @throws LuaException If an invalid locale is passed. | ||||
|      * @cc.tparam [opt] string|table locale The locale of the time, or a table filled by {@code os.date("*t")} to decode. Defaults to {@code ingame} locale if not specified. | ||||
|      * @see #date To get a date table that can be converted with this function. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final Object time( IArguments args ) throws LuaException | ||||
|     { | ||||
|         Object value = args.get( 0 ); | ||||
|         if( value instanceof Map ) return LuaDateTime.fromTable( (Map<?, ?>) value ); | ||||
|  | ||||
|         String param = args.optString( 0, "ingame" ); | ||||
|         switch( param.toLowerCase( Locale.ROOT ) ) | ||||
|         { | ||||
|             case "utc": // Get Hour of day (UTC) | ||||
|                 return getTimeForCalendar( Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ) ); | ||||
|             case "local": // Get Hour of day (local time) | ||||
|                 return getTimeForCalendar( Calendar.getInstance() ); | ||||
|             case "ingame": // Get in-game hour | ||||
|                 return m_time; | ||||
|             default: | ||||
|                 throw new LuaException( "Unsupported operation" ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns the day depending on the locale specified. | ||||
|      * | ||||
|      * * If called with {@code ingame}, returns the number of days since the | ||||
|      * world was created. This is the default. | ||||
|      * * If called with {@code utc}, returns the number of days since 1 January | ||||
|      * 1970 in the UTC timezone. | ||||
|      * * If called with {@code local}, returns the number of days since 1 | ||||
|      * January 1970 in the server's local timezone. | ||||
|      * | ||||
|      * @param args The locale to get the day for. Defaults to {@code ingame} if not set. | ||||
|      * @return The day depending on the selected locale. | ||||
|      * @throws LuaException If an invalid locale is passed. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final int day( Optional<String> args ) throws LuaException | ||||
|     { | ||||
|         switch( args.orElse( "ingame" ).toLowerCase( Locale.ROOT ) ) | ||||
|         { | ||||
|             case "utc":     // Get numbers of days since 1970-01-01 (utc) | ||||
|                 return getDayForCalendar( Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ) ); | ||||
|             case "local": // Get numbers of days since 1970-01-01 (local time) | ||||
|                 return getDayForCalendar( Calendar.getInstance() ); | ||||
|             case "ingame":// Get game day | ||||
|                 return m_day; | ||||
|             default: | ||||
|                 throw new LuaException( "Unsupported operation" ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns the number of seconds since an epoch depending on the locale. | ||||
|      * | ||||
|      * * If called with {@code ingame}, returns the number of seconds since the | ||||
|      * world was created. This is the default. | ||||
|      * * If called with {@code utc}, returns the number of seconds since 1 | ||||
|      * January 1970 in the UTC timezone. | ||||
|      * * If called with {@code local}, returns the number of seconds since 1 | ||||
|      * January 1970 in the server's local timezone. | ||||
|      * | ||||
|      * @param args The locale to get the seconds for. Defaults to {@code ingame} if not set. | ||||
|      * @return The seconds since the epoch depending on the selected locale. | ||||
|      * @throws LuaException If an invalid locale is passed. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final long epoch( Optional<String> args ) throws LuaException | ||||
|     { | ||||
|         switch( args.orElse( "ingame" ).toLowerCase( Locale.ROOT ) ) | ||||
|         { | ||||
|             case "utc": | ||||
|             { | ||||
|                 // Get utc epoch | ||||
|                 Calendar c = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ); | ||||
|                 return getEpochForCalendar( c ); | ||||
|             } | ||||
|             case "local": | ||||
|             { | ||||
|                 // Get local epoch | ||||
|                 Calendar c = Calendar.getInstance(); | ||||
|                 return getEpochForCalendar( c ); | ||||
|             } | ||||
|             case "ingame": | ||||
|                 // Get in-game epoch | ||||
|                 synchronized( m_alarms ) | ||||
|                 { | ||||
|                     return m_day * 86400000 + (int) (m_time * 3600000.0f); | ||||
|                 } | ||||
|             default: | ||||
|                 throw new LuaException( "Unsupported operation" ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns a date string (or table) using a specified format string and | ||||
|      * optional time to format. | ||||
|      * | ||||
|      * The format string takes the same formats as C's {@code strftime} function | ||||
|      * (http://www.cplusplus.com/reference/ctime/strftime/). In extension, it | ||||
|      * can be prefixed with an exclamation mark ({@code !}) to use UTC time | ||||
|      * instead of the server's local timezone. | ||||
|      * | ||||
|      * If the format is exactly {@code *t} (optionally prefixed with {@code !}), a | ||||
|      * table will be returned instead. This table has fields for the year, month, | ||||
|      * day, hour, minute, second, day of the week, day of the year, and whether | ||||
|      * Daylight Savings Time is in effect. This table can be converted to a UNIX | ||||
|      * timestamp (days since 1 January 1970) with {@link #date}. | ||||
|      * | ||||
|      * @param formatA The format of the string to return. This defaults to {@code %c}, which expands to a string similar to "Sat Dec 24 16:58:00 2011". | ||||
|      * @param timeA   The time to convert to a string. This defaults to the current time. | ||||
|      * @return The resulting format string. | ||||
|      * @throws LuaException If an invalid format is passed. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final Object date( Optional<String> formatA, Optional<Long> timeA ) throws LuaException | ||||
|     { | ||||
|         String format = formatA.orElse( "%c" ); | ||||
|         long time = timeA.orElseGet( () -> Instant.now().getEpochSecond() ); | ||||
|  | ||||
|         Instant instant = Instant.ofEpochSecond( time ); | ||||
|         ZonedDateTime date; | ||||
|         ZoneOffset offset; | ||||
|         if( format.startsWith( "!" ) ) | ||||
|         { | ||||
|             offset = ZoneOffset.UTC; | ||||
|             date = ZonedDateTime.ofInstant( instant, offset ); | ||||
|             format = format.substring( 1 ); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             ZoneId id = ZoneId.systemDefault(); | ||||
|             offset = id.getRules().getOffset( instant ); | ||||
|             date = ZonedDateTime.ofInstant( instant, id ); | ||||
|         } | ||||
|  | ||||
|         if( format.equals( "*t" ) ) return LuaDateTime.toTable( date, offset, instant ); | ||||
|  | ||||
|         DateTimeFormatterBuilder formatter = new DateTimeFormatterBuilder(); | ||||
|         LuaDateTime.format( formatter, format, offset ); | ||||
|         return formatter.toFormatter( Locale.ROOT ).format( date ); | ||||
|     } | ||||
|  | ||||
| } | ||||
							
								
								
									
										368
									
								
								src/main/java/dan200/computercraft/core/apis/PeripheralAPI.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										368
									
								
								src/main/java/dan200/computercraft/core/apis/PeripheralAPI.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,368 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.core.apis; | ||||
|  | ||||
| import dan200.computercraft.api.filesystem.IMount; | ||||
| import dan200.computercraft.api.filesystem.IWritableMount; | ||||
| import dan200.computercraft.api.lua.*; | ||||
| import dan200.computercraft.api.peripheral.IDynamicPeripheral; | ||||
| import dan200.computercraft.api.peripheral.IPeripheral; | ||||
| import dan200.computercraft.api.peripheral.IWorkMonitor; | ||||
| import dan200.computercraft.api.peripheral.NotAttachedException; | ||||
| import dan200.computercraft.core.asm.LuaMethod; | ||||
| import dan200.computercraft.core.asm.NamedMethod; | ||||
| import dan200.computercraft.core.asm.PeripheralMethod; | ||||
| import dan200.computercraft.core.computer.ComputerSide; | ||||
| import dan200.computercraft.core.tracking.TrackingField; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.util.*; | ||||
|  | ||||
| /** | ||||
|  * CC's "native" peripheral API. This is wrapped within CraftOS to provide a version which works with modems. | ||||
|  * | ||||
|  * @cc.module peripheral | ||||
|  * @hidden | ||||
|  */ | ||||
| public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChangeListener | ||||
| { | ||||
|     private class PeripheralWrapper extends ComputerAccess | ||||
|     { | ||||
|         private final String side; | ||||
|         private final IPeripheral peripheral; | ||||
|  | ||||
|         private final String type; | ||||
|         private final Map<String, PeripheralMethod> methodMap; | ||||
|         private boolean attached; | ||||
|  | ||||
|         PeripheralWrapper( IPeripheral peripheral, String side ) | ||||
|         { | ||||
|             super( environment ); | ||||
|             this.side = side; | ||||
|             this.peripheral = peripheral; | ||||
|             attached = false; | ||||
|  | ||||
|             type = Objects.requireNonNull( peripheral.getType(), "Peripheral type cannot be null" ); | ||||
|  | ||||
|             methodMap = PeripheralAPI.getMethods( peripheral ); | ||||
|         } | ||||
|  | ||||
|         public IPeripheral getPeripheral() | ||||
|         { | ||||
|             return peripheral; | ||||
|         } | ||||
|  | ||||
|         public String getType() | ||||
|         { | ||||
|             return type; | ||||
|         } | ||||
|  | ||||
|         public Collection<String> getMethods() | ||||
|         { | ||||
|             return methodMap.keySet(); | ||||
|         } | ||||
|  | ||||
|         public synchronized boolean isAttached() | ||||
|         { | ||||
|             return attached; | ||||
|         } | ||||
|  | ||||
|         public synchronized void attach() | ||||
|         { | ||||
|             attached = true; | ||||
|             peripheral.attach( this ); | ||||
|         } | ||||
|  | ||||
|         public void detach() | ||||
|         { | ||||
|             // Call detach | ||||
|             peripheral.detach( this ); | ||||
|  | ||||
|             synchronized( this ) | ||||
|             { | ||||
|                 // Unmount everything the detach function forgot to do | ||||
|                 unmountAll(); | ||||
|             } | ||||
|  | ||||
|             attached = false; | ||||
|         } | ||||
|  | ||||
|         public MethodResult call( ILuaContext context, String methodName, IArguments arguments ) throws LuaException | ||||
|         { | ||||
|             PeripheralMethod method; | ||||
|             synchronized( this ) | ||||
|             { | ||||
|                 method = methodMap.get( methodName ); | ||||
|             } | ||||
|  | ||||
|             if( method == null ) throw new LuaException( "No such method " + methodName ); | ||||
|  | ||||
|             environment.addTrackingChange( TrackingField.PERIPHERAL_OPS ); | ||||
|             return method.apply( peripheral, context, this, arguments ); | ||||
|         } | ||||
|  | ||||
|         // IComputerAccess implementation | ||||
|         @Override | ||||
|         public synchronized String mount( @Nonnull String desiredLoc, @Nonnull IMount mount, @Nonnull String driveName ) | ||||
|         { | ||||
|             if( !attached ) throw new NotAttachedException(); | ||||
|             return super.mount( desiredLoc, mount, driveName ); | ||||
|         } | ||||
|  | ||||
|         @Override | ||||
|         public synchronized String mountWritable( @Nonnull String desiredLoc, @Nonnull IWritableMount mount, @Nonnull String driveName ) | ||||
|         { | ||||
|             if( !attached ) throw new NotAttachedException(); | ||||
|             return super.mountWritable( desiredLoc, mount, driveName ); | ||||
|         } | ||||
|  | ||||
|         @Override | ||||
|         public synchronized void unmount( String location ) | ||||
|         { | ||||
|             if( !attached ) throw new NotAttachedException(); | ||||
|             super.unmount( location ); | ||||
|         } | ||||
|  | ||||
|         @Override | ||||
|         public int getID() | ||||
|         { | ||||
|             if( !attached ) throw new NotAttachedException(); | ||||
|             return super.getID(); | ||||
|         } | ||||
|  | ||||
|         @Override | ||||
|         public void queueEvent( @Nonnull String event, Object... arguments ) | ||||
|         { | ||||
|             if( !attached ) throw new NotAttachedException(); | ||||
|             super.queueEvent( event, arguments ); | ||||
|         } | ||||
|  | ||||
|         @Nonnull | ||||
|         @Override | ||||
|         public String getAttachmentName() | ||||
|         { | ||||
|             if( !attached ) throw new NotAttachedException(); | ||||
|             return side; | ||||
|         } | ||||
|  | ||||
|         @Nonnull | ||||
|         @Override | ||||
|         public Map<String, IPeripheral> getAvailablePeripherals() | ||||
|         { | ||||
|             if( !attached ) throw new NotAttachedException(); | ||||
|  | ||||
|             Map<String, IPeripheral> peripherals = new HashMap<>(); | ||||
|             for( PeripheralWrapper wrapper : PeripheralAPI.this.peripherals ) | ||||
|             { | ||||
|                 if( wrapper != null && wrapper.isAttached() ) | ||||
|                 { | ||||
|                     peripherals.put( wrapper.getAttachmentName(), wrapper.getPeripheral() ); | ||||
|                 } | ||||
|             } | ||||
|  | ||||
|             return Collections.unmodifiableMap( peripherals ); | ||||
|         } | ||||
|  | ||||
|         @Nullable | ||||
|         @Override | ||||
|         public IPeripheral getAvailablePeripheral( @Nonnull String name ) | ||||
|         { | ||||
|             if( !attached ) throw new NotAttachedException(); | ||||
|  | ||||
|             for( PeripheralWrapper wrapper : peripherals ) | ||||
|             { | ||||
|                 if( wrapper != null && wrapper.isAttached() && wrapper.getAttachmentName().equals( name ) ) | ||||
|                 { | ||||
|                     return wrapper.getPeripheral(); | ||||
|                 } | ||||
|             } | ||||
|             return null; | ||||
|         } | ||||
|  | ||||
|         @Nonnull | ||||
|         @Override | ||||
|         public IWorkMonitor getMainThreadMonitor() | ||||
|         { | ||||
|             if( !attached ) throw new NotAttachedException(); | ||||
|             return super.getMainThreadMonitor(); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     private final IAPIEnvironment environment; | ||||
|     private final PeripheralWrapper[] peripherals = new PeripheralWrapper[6]; | ||||
|     private boolean running; | ||||
|  | ||||
|     public PeripheralAPI( IAPIEnvironment environment ) | ||||
|     { | ||||
|         this.environment = environment; | ||||
|         this.environment.setPeripheralChangeListener( this ); | ||||
|         running = false; | ||||
|     } | ||||
|  | ||||
|     // IPeripheralChangeListener | ||||
|  | ||||
|     @Override | ||||
|     public void onPeripheralChanged( ComputerSide side, IPeripheral newPeripheral ) | ||||
|     { | ||||
|         synchronized( peripherals ) | ||||
|         { | ||||
|             int index = side.ordinal(); | ||||
|             if( peripherals[index] != null ) | ||||
|             { | ||||
|                 // Queue a detachment | ||||
|                 final PeripheralWrapper wrapper = peripherals[index]; | ||||
|                 if( wrapper.isAttached() ) wrapper.detach(); | ||||
|  | ||||
|                 // Queue a detachment event | ||||
|                 environment.queueEvent( "peripheral_detach", side.getName() ); | ||||
|             } | ||||
|  | ||||
|             // Assign the new peripheral | ||||
|             peripherals[index] = newPeripheral == null ? null | ||||
|                 : new PeripheralWrapper( newPeripheral, side.getName() ); | ||||
|  | ||||
|             if( peripherals[index] != null ) | ||||
|             { | ||||
|                 // Queue an attachment | ||||
|                 final PeripheralWrapper wrapper = peripherals[index]; | ||||
|                 if( running && !wrapper.isAttached() ) wrapper.attach(); | ||||
|  | ||||
|                 // Queue an attachment event | ||||
|                 environment.queueEvent( "peripheral", side.getName() ); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public String[] getNames() | ||||
|     { | ||||
|         return new String[] { "peripheral" }; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void startup() | ||||
|     { | ||||
|         synchronized( peripherals ) | ||||
|         { | ||||
|             running = true; | ||||
|             for( int i = 0; i < 6; i++ ) | ||||
|             { | ||||
|                 PeripheralWrapper wrapper = peripherals[i]; | ||||
|                 if( wrapper != null && !wrapper.isAttached() ) wrapper.attach(); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void shutdown() | ||||
|     { | ||||
|         synchronized( peripherals ) | ||||
|         { | ||||
|             running = false; | ||||
|             for( int i = 0; i < 6; i++ ) | ||||
|             { | ||||
|                 PeripheralWrapper wrapper = peripherals[i]; | ||||
|                 if( wrapper != null && wrapper.isAttached() ) | ||||
|                 { | ||||
|                     wrapper.detach(); | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @LuaFunction | ||||
|     public final boolean isPresent( String sideName ) | ||||
|     { | ||||
|         ComputerSide side = ComputerSide.valueOfInsensitive( sideName ); | ||||
|         if( side != null ) | ||||
|         { | ||||
|             synchronized( peripherals ) | ||||
|             { | ||||
|                 PeripheralWrapper p = peripherals[side.ordinal()]; | ||||
|                 if( p != null ) return true; | ||||
|             } | ||||
|         } | ||||
|         return false; | ||||
|     } | ||||
|  | ||||
|     @LuaFunction | ||||
|     public final Object[] getType( String sideName ) | ||||
|     { | ||||
|         ComputerSide side = ComputerSide.valueOfInsensitive( sideName ); | ||||
|         if( side == null ) return null; | ||||
|  | ||||
|         synchronized( peripherals ) | ||||
|         { | ||||
|             PeripheralWrapper p = peripherals[side.ordinal()]; | ||||
|             if( p != null ) return new Object[] { p.getType() }; | ||||
|         } | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     @LuaFunction | ||||
|     public final Object[] getMethods( String sideName ) | ||||
|     { | ||||
|         ComputerSide side = ComputerSide.valueOfInsensitive( sideName ); | ||||
|         if( side == null ) return null; | ||||
|  | ||||
|         synchronized( peripherals ) | ||||
|         { | ||||
|             PeripheralWrapper p = peripherals[side.ordinal()]; | ||||
|             if( p != null ) return new Object[] { p.getMethods() }; | ||||
|         } | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     @LuaFunction | ||||
|     public final MethodResult call( ILuaContext context, IArguments args ) throws LuaException | ||||
|     { | ||||
|         ComputerSide side = ComputerSide.valueOfInsensitive( args.getString( 0 ) ); | ||||
|         String methodName = args.getString( 1 ); | ||||
|         IArguments methodArgs = args.drop( 2 ); | ||||
|  | ||||
|         if( side == null ) throw new LuaException( "No peripheral attached" ); | ||||
|  | ||||
|         PeripheralWrapper p; | ||||
|         synchronized( peripherals ) | ||||
|         { | ||||
|             p = peripherals[side.ordinal()]; | ||||
|         } | ||||
|         if( p == null ) throw new LuaException( "No peripheral attached" ); | ||||
|  | ||||
|         try | ||||
|         { | ||||
|             return p.call( context, methodName, methodArgs ).adjustError( 1 ); | ||||
|         } | ||||
|         catch( LuaException e ) | ||||
|         { | ||||
|             // We increase the error level by one in order to shift the error level to where peripheral.call was | ||||
|             // invoked. It would be possible to do it in Lua code, but would add significantly more overhead. | ||||
|             if( e.getLevel() > 0 ) throw new FastLuaException( e.getMessage(), e.getLevel() + 1 ); | ||||
|             throw e; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static Map<String, PeripheralMethod> getMethods( IPeripheral peripheral ) | ||||
|     { | ||||
|         String[] dynamicMethods = peripheral instanceof IDynamicPeripheral | ||||
|             ? Objects.requireNonNull( ((IDynamicPeripheral) peripheral).getMethodNames(), "Peripheral methods cannot be null" ) | ||||
|             : LuaMethod.EMPTY_METHODS; | ||||
|  | ||||
|         List<NamedMethod<PeripheralMethod>> methods = PeripheralMethod.GENERATOR.getMethods( peripheral.getClass() ); | ||||
|  | ||||
|         Map<String, PeripheralMethod> methodMap = new HashMap<>( methods.size() + dynamicMethods.length ); | ||||
|         for( int i = 0; i < dynamicMethods.length; i++ ) | ||||
|         { | ||||
|             methodMap.put( dynamicMethods[i], PeripheralMethod.DYNAMIC.get( i ) ); | ||||
|         } | ||||
|         for( NamedMethod<PeripheralMethod> method : methods ) | ||||
|         { | ||||
|             methodMap.put( method.getName(), method.getMethod() ); | ||||
|         } | ||||
|         return methodMap; | ||||
|     } | ||||
| } | ||||
							
								
								
									
										215
									
								
								src/main/java/dan200/computercraft/core/apis/RedstoneAPI.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										215
									
								
								src/main/java/dan200/computercraft/core/apis/RedstoneAPI.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,215 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.core.apis; | ||||
|  | ||||
| import dan200.computercraft.api.lua.ILuaAPI; | ||||
| import dan200.computercraft.api.lua.LuaException; | ||||
| import dan200.computercraft.api.lua.LuaFunction; | ||||
| import dan200.computercraft.core.computer.ComputerSide; | ||||
|  | ||||
| /** | ||||
|  * Interact with redstone attached to this computer. | ||||
|  * | ||||
|  * The {@link RedstoneAPI} library exposes three "types" of redstone control: | ||||
|  * - Binary input/output ({@link #setOutput}/{@link #getInput}): These simply check if a redstone wire has any input or | ||||
|  * output. A signal strength of 1 and 15 are treated the same. | ||||
|  * - Analogue input/output ({@link #setAnalogOutput}/{@link #getAnalogInput}): These work with the actual signal | ||||
|  * strength of the redstone wired, from 0 to 15. | ||||
|  * - Bundled cables ({@link #setBundledOutput}/{@link #getBundledInput}): These interact with "bundled" cables, such | ||||
|  * as those from Project:Red. These allow you to send 16 separate on/off signals. Each channel corresponds to a | ||||
|  * colour, with the first being @{colors.white} and the last @{colors.black}. | ||||
|  * | ||||
|  * Whenever a redstone input changes, a {@code redstone} event will be fired. This may be used instead of repeativly | ||||
|  * polling. | ||||
|  * | ||||
|  * This module may also be referred to as {@code rs}. For example, one may call {@code rs.getSides()} instead of | ||||
|  * {@link #getSides}. | ||||
|  * | ||||
|  * @cc.usage Toggle the redstone signal above the computer every 0.5 seconds. | ||||
|  * | ||||
|  * <pre> | ||||
|  * while true do | ||||
|  *   redstone.setOutput("top", not redstone.getOutput("top")) | ||||
|  *   sleep(0.5) | ||||
|  * end | ||||
|  * </pre> | ||||
|  * @cc.usage Mimic a redstone comparator in [subtraction mode][comparator]. | ||||
|  * | ||||
|  * <pre> | ||||
|  * while true do | ||||
|  *   local rear = rs.getAnalogueInput("back") | ||||
|  *   local sides = math.max(rs.getAnalogueInput("left"), rs.getAnalogueInput("right")) | ||||
|  *   rs.setAnalogueOutput("front", math.max(rear - sides, 0)) | ||||
|  * | ||||
|  *   os.pullEvent("redstone") -- Wait for a change to inputs. | ||||
|  * end | ||||
|  * </pre> | ||||
|  * | ||||
|  * [comparator]: https://minecraft.gamepedia.com/Redstone_Comparator#Subtract_signal_strength "Redstone Comparator on | ||||
|  * the Minecraft wiki." | ||||
|  * @cc.module redstone | ||||
|  */ | ||||
| public class RedstoneAPI implements ILuaAPI | ||||
| { | ||||
|     private final IAPIEnvironment environment; | ||||
|  | ||||
|     public RedstoneAPI( IAPIEnvironment environment ) | ||||
|     { | ||||
|         this.environment = environment; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public String[] getNames() | ||||
|     { | ||||
|         return new String[] { "rs", "redstone" }; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns a table containing the six sides of the computer. Namely, "top", "bottom", "left", "right", "front" and | ||||
|      * "back". | ||||
|      * | ||||
|      * @return A table of valid sides. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final String[] getSides() | ||||
|     { | ||||
|         return ComputerSide.NAMES; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Turn the redstone signal of a specific side on or off. | ||||
|      * | ||||
|      * @param side The side to set. | ||||
|      * @param on   Whether the redstone signal should be on or off. When on, a signal strength of 15 is emitted. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final void setOutput( ComputerSide side, boolean on ) | ||||
|     { | ||||
|         environment.setOutput( side, on ? 15 : 0 ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the current redstone output of a specific side. | ||||
|      * | ||||
|      * @param side The side to get. | ||||
|      * @return Whether the redstone output is on or off. | ||||
|      * @see #setOutput | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final boolean getOutput( ComputerSide side ) | ||||
|     { | ||||
|         return environment.getOutput( side ) > 0; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the current redstone input of a specific side. | ||||
|      * | ||||
|      * @param side The side to get. | ||||
|      * @return Whether the redstone input is on or off. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final boolean getInput( ComputerSide side ) | ||||
|     { | ||||
|         return environment.getInput( side ) > 0; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Set the redstone signal strength for a specific side. | ||||
|      * | ||||
|      * @param side  The side to set. | ||||
|      * @param value The signal strength between 0 and 15. | ||||
|      * @throws LuaException If {@code value} is not betwene 0 and 15. | ||||
|      */ | ||||
|     @LuaFunction( { "setAnalogOutput", "setAnalogueOutput" } ) | ||||
|     public final void setAnalogOutput( ComputerSide side, int value ) throws LuaException | ||||
|     { | ||||
|         if( value < 0 || value > 15 ) throw new LuaException( "Expected number in range 0-15" ); | ||||
|         environment.setOutput( side, value ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the redstone output signal strength for a specific side. | ||||
|      * | ||||
|      * @param side The side to get. | ||||
|      * @return The output signal strength, between 0 and 15. | ||||
|      * @see #setAnalogOutput | ||||
|      */ | ||||
|     @LuaFunction( { "getAnalogOutput", "getAnalogueOutput" } ) | ||||
|     public final int getAnalogOutput( ComputerSide side ) | ||||
|     { | ||||
|         return environment.getOutput( side ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the redstone input signal strength for a specific side. | ||||
|      * | ||||
|      * @param side The side to get. | ||||
|      * @return The input signal strength, between 0 and 15. | ||||
|      */ | ||||
|     @LuaFunction( { "getAnalogInput", "getAnalogueInput" } ) | ||||
|     public final int getAnalogInput( ComputerSide side ) | ||||
|     { | ||||
|         return environment.getInput( side ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Set the bundled cable output for a specific side. | ||||
|      * | ||||
|      * @param side   The side to set. | ||||
|      * @param output The colour bitmask to set. | ||||
|      * @cc.see colors.subtract For removing a colour from the bitmask. | ||||
|      * @cc.see colors.combine For adding a color to the bitmask. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final void setBundledOutput( ComputerSide side, int output ) | ||||
|     { | ||||
|         environment.setBundledOutput( side, output ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the bundled cable output for a specific side. | ||||
|      * | ||||
|      * @param side The side to get. | ||||
|      * @return The bundle cable's output. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final int getBundledOutput( ComputerSide side ) | ||||
|     { | ||||
|         return environment.getBundledOutput( side ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the bundled cable input for a specific side. | ||||
|      * | ||||
|      * @param side The side to get. | ||||
|      * @return The bundle cable's input. | ||||
|      * @see #testBundledInput To determine if a specific colour is set. | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final int getBundledInput( ComputerSide side ) | ||||
|     { | ||||
|         return environment.getBundledOutput( side ); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Determine if a specific combination of colours are on for the given side. | ||||
|      * | ||||
|      * @param side The side to test. | ||||
|      * @param mask The mask to test. | ||||
|      * @return If the colours are on. | ||||
|      * @cc.usage Check if @{colors.white} and @{colors.black} are on above the computer. | ||||
|      * <pre> | ||||
|      * print(redstone.testBundledInput("top", colors.combine(colors.white, colors.black))) | ||||
|      * </pre> | ||||
|      * @see #getBundledInput | ||||
|      */ | ||||
|     @LuaFunction | ||||
|     public final boolean testBundledInput( ComputerSide side, int mask ) | ||||
|     { | ||||
|         int input = environment.getBundledInput( side ); | ||||
|         return (input & mask) == mask; | ||||
|     } | ||||
| } | ||||
							
								
								
									
										208
									
								
								src/main/java/dan200/computercraft/core/apis/TableHelper.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										208
									
								
								src/main/java/dan200/computercraft/core/apis/TableHelper.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,208 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.core.apis; | ||||
|  | ||||
| import dan200.computercraft.api.lua.LuaException; | ||||
| import dan200.computercraft.api.lua.LuaValues; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
| import javax.annotation.Nullable; | ||||
| import java.util.Map; | ||||
|  | ||||
| import static dan200.computercraft.api.lua.LuaValues.getNumericType; | ||||
|  | ||||
| /** | ||||
|  * Various helpers for tables. | ||||
|  */ | ||||
| public final class TableHelper | ||||
| { | ||||
|     private TableHelper() | ||||
|     { | ||||
|         throw new IllegalStateException( "Cannot instantiate singleton " + getClass().getName() ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     public static LuaException badKey( @Nonnull String key, @Nonnull String expected, @Nullable Object actual ) | ||||
|     { | ||||
|         return badKey( key, expected, LuaValues.getType( actual ) ); | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     public static LuaException badKey( @Nonnull String key, @Nonnull String expected, @Nonnull String actual ) | ||||
|     { | ||||
|         return new LuaException( "bad field '" + key + "' (" + expected + " expected, got " + actual + ")" ); | ||||
|     } | ||||
|  | ||||
|     public static double getNumberField( @Nonnull Map<?, ?> table, @Nonnull String key ) throws LuaException | ||||
|     { | ||||
|         Object value = table.get( key ); | ||||
|         if( value instanceof Number ) | ||||
|         { | ||||
|             return ((Number) value).doubleValue(); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             throw badKey( key, "number", value ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static int getIntField( @Nonnull Map<?, ?> table, @Nonnull String key ) throws LuaException | ||||
|     { | ||||
|         Object value = table.get( key ); | ||||
|         if( value instanceof Number ) | ||||
|         { | ||||
|             return (int) ((Number) value).longValue(); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             throw badKey( key, "number", value ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static double getRealField( @Nonnull Map<?, ?> table, @Nonnull String key ) throws LuaException | ||||
|     { | ||||
|         return checkReal( key, getNumberField( table, key ) ); | ||||
|     } | ||||
|  | ||||
|     public static boolean getBooleanField( @Nonnull Map<?, ?> table, @Nonnull String key ) throws LuaException | ||||
|     { | ||||
|         Object value = table.get( key ); | ||||
|         if( value instanceof Boolean ) | ||||
|         { | ||||
|             return (Boolean) value; | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             throw badKey( key, "boolean", value ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     public static String getStringField( @Nonnull Map<?, ?> table, @Nonnull String key ) throws LuaException | ||||
|     { | ||||
|         Object value = table.get( key ); | ||||
|         if( value instanceof String ) | ||||
|         { | ||||
|             return (String) value; | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             throw badKey( key, "string", value ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @SuppressWarnings( "unchecked" ) | ||||
|     @Nonnull | ||||
|     public static Map<Object, Object> getTableField( @Nonnull Map<?, ?> table, @Nonnull String key ) throws LuaException | ||||
|     { | ||||
|         Object value = table.get( key ); | ||||
|         if( value instanceof Map ) | ||||
|         { | ||||
|             return (Map<Object, Object>) value; | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             throw badKey( key, "table", value ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static double optNumberField( @Nonnull Map<?, ?> table, @Nonnull String key, double def ) throws LuaException | ||||
|     { | ||||
|         Object value = table.get( key ); | ||||
|         if( value == null ) | ||||
|         { | ||||
|             return def; | ||||
|         } | ||||
|         else if( value instanceof Number ) | ||||
|         { | ||||
|             return ((Number) value).doubleValue(); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             throw badKey( key, "number", value ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static int optIntField( @Nonnull Map<?, ?> table, @Nonnull String key, int def ) throws LuaException | ||||
|     { | ||||
|         Object value = table.get( key ); | ||||
|         if( value == null ) | ||||
|         { | ||||
|             return def; | ||||
|         } | ||||
|         else if( value instanceof Number ) | ||||
|         { | ||||
|             return (int) ((Number) value).longValue(); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             throw badKey( key, "number", value ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static double optRealField( @Nonnull Map<?, ?> table, @Nonnull String key, double def ) throws LuaException | ||||
|     { | ||||
|         return checkReal( key, optNumberField( table, key, def ) ); | ||||
|     } | ||||
|  | ||||
|     public static boolean optBooleanField( @Nonnull Map<?, ?> table, @Nonnull String key, boolean def ) throws LuaException | ||||
|     { | ||||
|         Object value = table.get( key ); | ||||
|         if( value == null ) | ||||
|         { | ||||
|             return def; | ||||
|         } | ||||
|         else if( value instanceof Boolean ) | ||||
|         { | ||||
|             return (Boolean) value; | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             throw badKey( key, "boolean", value ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public static String optStringField( @Nonnull Map<?, ?> table, @Nonnull String key, String def ) throws LuaException | ||||
|     { | ||||
|         Object value = table.get( key ); | ||||
|         if( value == null ) | ||||
|         { | ||||
|             return def; | ||||
|         } | ||||
|         else if( value instanceof String ) | ||||
|         { | ||||
|             return (String) value; | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             throw badKey( key, "string", value ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     @SuppressWarnings( "unchecked" ) | ||||
|     public static Map<Object, Object> optTableField( @Nonnull Map<?, ?> table, @Nonnull String key, Map<Object, Object> def ) throws LuaException | ||||
|     { | ||||
|         Object value = table.get( key ); | ||||
|         if( value == null ) | ||||
|         { | ||||
|             return def; | ||||
|         } | ||||
|         else if( value instanceof Map ) | ||||
|         { | ||||
|             return (Map<Object, Object>) value; | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|             throw badKey( key, "table", value ); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     private static double checkReal( @Nonnull String key, double value ) throws LuaException | ||||
|     { | ||||
|         if( !Double.isFinite( value ) ) throw badKey( key, "number", getNumericType( value ) ); | ||||
|         return value; | ||||
|     } | ||||
| } | ||||
							
								
								
									
										76
									
								
								src/main/java/dan200/computercraft/core/apis/TermAPI.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										76
									
								
								src/main/java/dan200/computercraft/core/apis/TermAPI.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,76 @@ | ||||
| /* | ||||
|  * This file is part of ComputerCraft - http://www.computercraft.info | ||||
|  * Copyright Daniel Ratcliffe, 2011-2020. Do not distribute without permission. | ||||
|  * Send enquiries to dratcliffe@gmail.com | ||||
|  */ | ||||
| package dan200.computercraft.core.apis; | ||||
|  | ||||
| import dan200.computercraft.api.lua.IArguments; | ||||
| import dan200.computercraft.api.lua.ILuaAPI; | ||||
| import dan200.computercraft.api.lua.LuaException; | ||||
| import dan200.computercraft.api.lua.LuaFunction; | ||||
| import dan200.computercraft.core.computer.IComputerEnvironment; | ||||
| import dan200.computercraft.core.terminal.Terminal; | ||||
| import dan200.computercraft.shared.util.Colour; | ||||
|  | ||||
| import javax.annotation.Nonnull; | ||||
|  | ||||
| /** | ||||
|  * The Terminal API provides functions for writing text to the terminal and monitors, and drawing ASCII graphics. | ||||
|  * | ||||
|  * @cc.module term | ||||
|  */ | ||||
| public class TermAPI extends TermMethods implements ILuaAPI | ||||
| { | ||||
|     private final Terminal terminal; | ||||
|     private final IComputerEnvironment environment; | ||||
|  | ||||
|     public TermAPI( IAPIEnvironment environment ) | ||||
|     { | ||||
|         terminal = environment.getTerminal(); | ||||
|         this.environment = environment.getComputerEnvironment(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public String[] getNames() | ||||
|     { | ||||
|         return new String[] { "term" }; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get the default palette value for a colour. | ||||
|      * | ||||
|      * @param colour The colour whose palette should be fetched. | ||||
|      * @return The RGB values. | ||||
|      * @throws LuaException When given an invalid colour. | ||||
|      * @cc.treturn number The red channel, will be between 0 and 1. | ||||
|      * @cc.treturn number The green channel, will be between 0 and 1. | ||||
|      * @cc.treturn number The blue channel, will be between 0 and 1. | ||||
|      * @see TermMethods#setPaletteColour(IArguments) To change the palette colour. | ||||
|      */ | ||||
|     @LuaFunction( { "nativePaletteColour", "nativePaletteColor" } ) | ||||
|     public final Object[] nativePaletteColour( int colour ) throws LuaException | ||||
|     { | ||||
|         int actualColour = 15 - parseColour( colour ); | ||||
|         Colour c = Colour.fromInt( actualColour ); | ||||
|  | ||||
|         float[] rgb = c.getRGB(); | ||||
|  | ||||
|         Object[] rgbObj = new Object[rgb.length]; | ||||
|         for( int i = 0; i < rgbObj.length; ++i ) rgbObj[i] = rgb[i]; | ||||
|         return rgbObj; | ||||
|     } | ||||
|  | ||||
|     @Nonnull | ||||
|     @Override | ||||
|     public Terminal getTerminal() | ||||
|     { | ||||
|         return terminal; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public boolean isColour() | ||||
|     { | ||||
|         return environment.isColour(); | ||||
|     } | ||||
| } | ||||
Some files were not shown because too many files have changed in this diff Show More
		Reference in New Issue
	
	Block a user
	 Devan-Kerman
					Devan-Kerman