mirror of
https://github.com/SquidDev-CC/CC-Tweaked
synced 2026-11-19 12:54:27 +00:00
ComputerCraft 1.79 initial upload
Added the complete source code to ComputerCraft 1.79 for Minecraft 1.8.9, plus newly written README and LICENSE files for the open source release.
This commit is contained in:
1 parent
38623b31c4
commit
e85cdacbc5
1123 files changed
+191332
-3
No files matched your search
@@ -0,0 +1,790 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft;
|
||||
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
import dan200.computercraft.api.filesystem.IWritableMount;
|
||||
import dan200.computercraft.api.media.IMedia;
|
||||
import dan200.computercraft.api.media.IMediaProvider;
|
||||
import dan200.computercraft.api.peripheral.IPeripheral;
|
||||
import dan200.computercraft.api.peripheral.IPeripheralProvider;
|
||||
import dan200.computercraft.api.permissions.ITurtlePermissionProvider;
|
||||
import dan200.computercraft.api.redstone.IBundledRedstoneProvider;
|
||||
import dan200.computercraft.api.turtle.ITurtleUpgrade;
|
||||
import dan200.computercraft.core.filesystem.ComboMount;
|
||||
import dan200.computercraft.core.filesystem.FileMount;
|
||||
import dan200.computercraft.core.filesystem.JarMount;
|
||||
import dan200.computercraft.shared.common.DefaultBundledRedstoneProvider;
|
||||
import dan200.computercraft.shared.computer.blocks.BlockCommandComputer;
|
||||
import dan200.computercraft.shared.computer.blocks.BlockComputer;
|
||||
import dan200.computercraft.shared.computer.blocks.TileComputer;
|
||||
import dan200.computercraft.shared.computer.core.ClientComputerRegistry;
|
||||
import dan200.computercraft.shared.computer.core.ServerComputerRegistry;
|
||||
import dan200.computercraft.shared.media.items.ItemDiskExpanded;
|
||||
import dan200.computercraft.shared.media.items.ItemDiskLegacy;
|
||||
import dan200.computercraft.shared.media.items.ItemPrintout;
|
||||
import dan200.computercraft.shared.media.items.ItemTreasureDisk;
|
||||
import dan200.computercraft.shared.network.ComputerCraftPacket;
|
||||
import dan200.computercraft.shared.network.PacketHandler;
|
||||
import dan200.computercraft.shared.peripheral.common.BlockCable;
|
||||
import dan200.computercraft.shared.peripheral.common.BlockPeripheral;
|
||||
import dan200.computercraft.shared.peripheral.diskdrive.TileDiskDrive;
|
||||
import dan200.computercraft.shared.peripheral.modem.BlockAdvancedModem;
|
||||
import dan200.computercraft.shared.peripheral.modem.WirelessNetwork;
|
||||
import dan200.computercraft.shared.peripheral.printer.TilePrinter;
|
||||
import dan200.computercraft.shared.pocket.items.ItemPocketComputer;
|
||||
import dan200.computercraft.shared.proxy.ICCTurtleProxy;
|
||||
import dan200.computercraft.shared.proxy.IComputerCraftProxy;
|
||||
import dan200.computercraft.shared.turtle.blocks.BlockTurtle;
|
||||
import dan200.computercraft.shared.turtle.blocks.TileTurtle;
|
||||
import dan200.computercraft.shared.turtle.upgrades.*;
|
||||
import dan200.computercraft.shared.util.CreativeTabMain;
|
||||
import dan200.computercraft.shared.util.IDAssigner;
|
||||
import dan200.computercraft.shared.util.IEntityDropConsumer;
|
||||
import dan200.computercraft.shared.util.WorldUtil;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.network.PacketBuffer;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraftforge.common.config.Configuration;
|
||||
import net.minecraftforge.common.config.Property;
|
||||
import net.minecraftforge.fml.common.FMLCommonHandler;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.common.SidedProxy;
|
||||
import net.minecraftforge.fml.common.event.*;
|
||||
import net.minecraftforge.fml.common.network.FMLEventChannel;
|
||||
import net.minecraftforge.fml.common.network.NetworkRegistry;
|
||||
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket;
|
||||
import net.minecraftforge.fml.relauncher.Side;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
///////////////
|
||||
// UNIVERSAL //
|
||||
///////////////
|
||||
|
||||
@Mod( modid = "ComputerCraft", name = "ComputerCraft", version = "${version}" )
|
||||
public class ComputerCraft
|
||||
{
|
||||
// GUI IDs
|
||||
public static final int diskDriveGUIID = 100;
|
||||
public static final int computerGUIID = 101;
|
||||
public static final int printerGUIID = 102;
|
||||
public static final int turtleGUIID = 103;
|
||||
// ComputerCraftEdu uses ID 104
|
||||
public static final int printoutGUIID = 105;
|
||||
public static final int pocketComputerGUIID = 106;
|
||||
|
||||
// Configuration options
|
||||
public static boolean http_enable = true;
|
||||
public static String http_whitelist = "*";
|
||||
public static boolean disable_lua51_features = false;
|
||||
public static String default_computer_settings = "";
|
||||
|
||||
public static boolean enableCommandBlock = false;
|
||||
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 final int terminalWidth_computer = 51;
|
||||
public static final int terminalHeight_computer = 19;
|
||||
|
||||
public static final int terminalWidth_turtle = 39;
|
||||
public static final int terminalHeight_turtle = 13;
|
||||
|
||||
public static final int terminalWidth_pocketComputer = 26;
|
||||
public static final int terminalHeight_pocketComputer = 20;
|
||||
|
||||
public static int modem_range = 64;
|
||||
public static int modem_highAltitudeRange = 384;
|
||||
public static int modem_rangeDuringStorm = 64;
|
||||
public static int modem_highAltitudeRangeDuringStorm = 384;
|
||||
|
||||
public static int computerSpaceLimit = 1000 * 1000;
|
||||
public static int floppySpaceLimit = 125 * 1000;
|
||||
|
||||
public static int treasureDiskLootFrequency = 1;
|
||||
|
||||
// Blocks and Items
|
||||
public static class Blocks
|
||||
{
|
||||
public static BlockComputer computer;
|
||||
public static BlockPeripheral peripheral;
|
||||
public static BlockCable cable;
|
||||
public static BlockTurtle turtle;
|
||||
public static BlockTurtle turtleExpanded;
|
||||
public static BlockTurtle turtleAdvanced;
|
||||
public static BlockCommandComputer commandComputer;
|
||||
public static BlockAdvancedModem advancedModem;
|
||||
}
|
||||
|
||||
public static class Items
|
||||
{
|
||||
public static ItemDiskLegacy disk;
|
||||
public static ItemDiskExpanded diskExpanded;
|
||||
public static ItemPrintout printout;
|
||||
public static ItemTreasureDisk treasureDisk;
|
||||
public static ItemPocketComputer pocketComputer;
|
||||
}
|
||||
|
||||
public static class Upgrades
|
||||
{
|
||||
public static TurtleModem wirelessModem;
|
||||
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 TurtleModem advancedModem;
|
||||
}
|
||||
|
||||
// Registries
|
||||
public static ClientComputerRegistry clientComputerRegistry = new ClientComputerRegistry();
|
||||
public static ServerComputerRegistry serverComputerRegistry = new ServerComputerRegistry();
|
||||
|
||||
// Networking
|
||||
public static FMLEventChannel networkEventChannel;
|
||||
|
||||
// Creative
|
||||
public static CreativeTabMain mainCreativeTab;
|
||||
|
||||
// API users
|
||||
private static List<IPeripheralProvider> peripheralProviders = new ArrayList<IPeripheralProvider>();
|
||||
private static List<IBundledRedstoneProvider> bundledRedstoneProviders = new ArrayList<IBundledRedstoneProvider>();
|
||||
private static List<IMediaProvider> mediaProviders = new ArrayList<IMediaProvider>();
|
||||
private static List<ITurtlePermissionProvider> permissionProviders = new ArrayList<ITurtlePermissionProvider>();
|
||||
|
||||
// Implementation
|
||||
@Mod.Instance( value = "ComputerCraft" )
|
||||
public static ComputerCraft instance;
|
||||
|
||||
@SidedProxy( clientSide = "dan200.computercraft.client.proxy.ComputerCraftProxyClient", serverSide = "dan200.computercraft.server.proxy.ComputerCraftProxyServer" )
|
||||
public static IComputerCraftProxy proxy;
|
||||
|
||||
@SidedProxy( clientSide = "dan200.computercraft.client.proxy.CCTurtleProxyClient", serverSide = "dan200.computercraft.server.proxy.CCTurtleProxyServer" )
|
||||
public static ICCTurtleProxy turtleProxy;
|
||||
|
||||
public ComputerCraft()
|
||||
{
|
||||
}
|
||||
|
||||
@Mod.EventHandler
|
||||
public void preInit( FMLPreInitializationEvent event )
|
||||
{
|
||||
// Load config
|
||||
Configuration config = new Configuration( event.getSuggestedConfigurationFile() );
|
||||
config.load();
|
||||
|
||||
// Setup general
|
||||
|
||||
Property prop = config.get(Configuration.CATEGORY_GENERAL, "http_enable", http_enable);
|
||||
prop.comment = "Enable the \"http\" API on Computers (see \"http_whitelist\" for more fine grained control than this)";
|
||||
http_enable = prop.getBoolean(http_enable);
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "http_whitelist", http_whitelist );
|
||||
prop.comment = "A semicolon limited list of wildcards for domains that can be accessed through the \"http\" API on Computers. Set this to \"*\" to access to the entire internet. Example: \"*.pastebin.com;*.github.com;*.computercraft.info\" will restrict access to just those 3 domains.";
|
||||
http_whitelist = prop.getString();
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "disable_lua51_features", disable_lua51_features );
|
||||
prop.comment = "Set this to true to disable Lua 5.1 functions that will be removed in a future update. Useful for ensuring forward compatibility of your programs now.";
|
||||
disable_lua51_features = prop.getBoolean( disable_lua51_features );
|
||||
|
||||
prop = config.get( Configuration.CATEGORY_GENERAL, "default_computer_settings", default_computer_settings );
|
||||
prop.comment = "A comma seperated list of default system settings to set on new computers. Example: \"shell.autocomplete=false,lua.autocomplete=false,edit.autocomplete=false\" will disable all autocompletion";
|
||||
default_computer_settings = prop.getString();
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "enableCommandBlock", enableCommandBlock);
|
||||
prop.comment = "Enable Command Block peripheral support";
|
||||
enableCommandBlock = prop.getBoolean(enableCommandBlock);
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "modem_range", modem_range);
|
||||
prop.comment = "The range of Wireless Modems at low altitude in clear weather, in meters";
|
||||
modem_range = Math.min( prop.getInt(), 100000 );
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "modem_highAltitudeRange", modem_highAltitudeRange);
|
||||
prop.comment = "The range of Wireless Modems at maximum altitude in clear weather, in meters";
|
||||
modem_highAltitudeRange = Math.min( prop.getInt(), 100000 );
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "modem_rangeDuringStorm", modem_rangeDuringStorm);
|
||||
prop.comment = "The range of Wireless Modems at low altitude in stormy weather, in meters";
|
||||
modem_rangeDuringStorm = Math.min( prop.getInt(), 100000 );
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "modem_highAltitudeRangeDuringStorm", modem_highAltitudeRangeDuringStorm);
|
||||
prop.comment = "The range of Wireless Modems at maximum altitude in stormy weather, in meters";
|
||||
modem_highAltitudeRangeDuringStorm = Math.min( prop.getInt(), 100000 );
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "computerSpaceLimit", computerSpaceLimit);
|
||||
prop.comment = "The disk space limit for computers and turtles, in bytes";
|
||||
computerSpaceLimit = prop.getInt();
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "floppySpaceLimit", floppySpaceLimit);
|
||||
prop.comment = "The disk space limit for floppy disks, in bytes";
|
||||
floppySpaceLimit = prop.getInt();
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "treasureDiskLootFrequency", treasureDiskLootFrequency);
|
||||
prop.comment = "The frequency that treasure disks will be found in dungeon chests, from 0 to 100. Increase this value if running a modpack with lots of mods that add dungeon loot, or you just want more treasure disks. Set to 0 to disable treasure disks.";
|
||||
treasureDiskLootFrequency = prop.getInt();
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "turtlesNeedFuel", turtlesNeedFuel);
|
||||
prop.comment = "Set whether Turtles require fuel to move";
|
||||
turtlesNeedFuel = prop.getBoolean( turtlesNeedFuel );
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "turtleFuelLimit", turtleFuelLimit);
|
||||
prop.comment = "The fuel limit for Turtles";
|
||||
turtleFuelLimit = prop.getInt( turtleFuelLimit );
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "advancedTurtleFuelLimit", advancedTurtleFuelLimit);
|
||||
prop.comment = "The fuel limit for Advanced Turtles";
|
||||
advancedTurtleFuelLimit = prop.getInt(advancedTurtleFuelLimit);
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "turtlesObeyBlockProtection", turtlesObeyBlockProtection);
|
||||
prop.comment = "If set to true, Turtles will be unable to build, dig, or enter protected areas (such as near the server spawn point)";
|
||||
turtlesObeyBlockProtection = prop.getBoolean( turtlesObeyBlockProtection );
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "turtlesCanPush", turtlesCanPush);
|
||||
prop.comment = "If set to true, Turtles will push entities out of the way instead of stopping if there is space to do so";
|
||||
turtlesCanPush = prop.getBoolean(turtlesCanPush);
|
||||
|
||||
config.save();
|
||||
|
||||
// Setup network
|
||||
networkEventChannel = NetworkRegistry.INSTANCE.newEventDrivenChannel( "CC" );
|
||||
networkEventChannel.register( new PacketHandler() );
|
||||
|
||||
proxy.preInit();
|
||||
turtleProxy.preInit();
|
||||
}
|
||||
|
||||
@Mod.EventHandler
|
||||
public void init( FMLInitializationEvent event )
|
||||
{
|
||||
proxy.init();
|
||||
turtleProxy.init();
|
||||
}
|
||||
|
||||
@Mod.EventHandler
|
||||
public void onServerStarting( FMLServerStartingEvent event )
|
||||
{
|
||||
ItemTreasureDisk.registerDungeonLoot();
|
||||
}
|
||||
|
||||
@Mod.EventHandler
|
||||
public void onServerStart( FMLServerStartedEvent event )
|
||||
{
|
||||
if( FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER )
|
||||
{
|
||||
ComputerCraft.serverComputerRegistry.reset();
|
||||
WirelessNetwork.resetNetworks();
|
||||
}
|
||||
}
|
||||
|
||||
@Mod.EventHandler
|
||||
public void onServerStopped( FMLServerStoppedEvent event )
|
||||
{
|
||||
if( FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER )
|
||||
{
|
||||
ComputerCraft.serverComputerRegistry.reset();
|
||||
WirelessNetwork.resetNetworks();
|
||||
}
|
||||
}
|
||||
|
||||
public static String getVersion()
|
||||
{
|
||||
return "${version}";
|
||||
}
|
||||
|
||||
public static boolean isClient()
|
||||
{
|
||||
return proxy.isClient();
|
||||
}
|
||||
|
||||
public static boolean getGlobalCursorBlink()
|
||||
{
|
||||
return proxy.getGlobalCursorBlink();
|
||||
}
|
||||
|
||||
public static long getRenderFrame()
|
||||
{
|
||||
return proxy.getRenderFrame();
|
||||
}
|
||||
|
||||
public static void deleteDisplayLists( int list, int range )
|
||||
{
|
||||
proxy.deleteDisplayLists( list, range );
|
||||
}
|
||||
|
||||
public static Object getFixedWidthFontRenderer()
|
||||
{
|
||||
return proxy.getFixedWidthFontRenderer();
|
||||
}
|
||||
|
||||
public static void playRecord( String record, String recordInfo, World world, BlockPos pos )
|
||||
{
|
||||
proxy.playRecord( record, recordInfo, world, pos );
|
||||
}
|
||||
|
||||
public static String getRecordInfo( ItemStack recordStack )
|
||||
{
|
||||
return proxy.getRecordInfo( recordStack );
|
||||
}
|
||||
|
||||
public static void openDiskDriveGUI( EntityPlayer player, TileDiskDrive drive )
|
||||
{
|
||||
BlockPos pos = drive.getPos();
|
||||
player.openGui( ComputerCraft.instance, ComputerCraft.diskDriveGUIID, player.getEntityWorld(), pos.getX(), pos.getY(), pos.getZ() );
|
||||
}
|
||||
|
||||
public static void openComputerGUI( EntityPlayer player, TileComputer computer )
|
||||
{
|
||||
BlockPos pos = computer.getPos();
|
||||
player.openGui( ComputerCraft.instance, ComputerCraft.computerGUIID, player.getEntityWorld(), pos.getX(), pos.getY(), pos.getZ() );
|
||||
}
|
||||
|
||||
public static void openPrinterGUI( EntityPlayer player, TilePrinter printer )
|
||||
{
|
||||
BlockPos pos = printer.getPos();
|
||||
player.openGui( ComputerCraft.instance, ComputerCraft.printerGUIID, player.getEntityWorld(), pos.getX(), pos.getY(), pos.getZ() );
|
||||
}
|
||||
|
||||
public static void openTurtleGUI( EntityPlayer player, TileTurtle turtle )
|
||||
{
|
||||
BlockPos pos = turtle.getPos();
|
||||
player.openGui( instance, ComputerCraft.turtleGUIID, player.getEntityWorld(), pos.getX(), pos.getY(), pos.getZ() );
|
||||
}
|
||||
|
||||
public static void openPrintoutGUI( EntityPlayer player )
|
||||
{
|
||||
player.openGui( ComputerCraft.instance, ComputerCraft.printoutGUIID, player.getEntityWorld(), 0, 0, 0 );
|
||||
}
|
||||
|
||||
public static void openPocketComputerGUI( EntityPlayer player )
|
||||
{
|
||||
player.openGui( ComputerCraft.instance, ComputerCraft.pocketComputerGUIID, player.getEntityWorld(), 0, 0, 0 );
|
||||
}
|
||||
|
||||
public static File getBaseDir()
|
||||
{
|
||||
return FMLCommonHandler.instance().getMinecraftServerInstance().getFile(".");
|
||||
}
|
||||
|
||||
public static File getResourcePackDir()
|
||||
{
|
||||
return new File( getBaseDir(), "resourcepacks" );
|
||||
}
|
||||
|
||||
public static File getWorldDir( World world )
|
||||
{
|
||||
return proxy.getWorldDir( world );
|
||||
}
|
||||
|
||||
private static FMLProxyPacket encode( ComputerCraftPacket packet )
|
||||
{
|
||||
PacketBuffer buffer = new PacketBuffer( Unpooled.buffer() );
|
||||
packet.toBytes( buffer );
|
||||
return new FMLProxyPacket( buffer, "CC" );
|
||||
}
|
||||
|
||||
public static void sendToPlayer( EntityPlayer player, ComputerCraftPacket packet )
|
||||
{
|
||||
networkEventChannel.sendTo( encode( packet ), (EntityPlayerMP)player );
|
||||
}
|
||||
|
||||
public static void sendToAllPlayers( ComputerCraftPacket packet )
|
||||
{
|
||||
networkEventChannel.sendToAll( encode( packet ) );
|
||||
}
|
||||
|
||||
public static void sendToServer( ComputerCraftPacket packet )
|
||||
{
|
||||
networkEventChannel.sendToServer( encode( packet ) );
|
||||
}
|
||||
|
||||
public static void handlePacket( ComputerCraftPacket packet, EntityPlayer player )
|
||||
{
|
||||
proxy.handlePacket( packet, player );
|
||||
}
|
||||
|
||||
public static boolean canPlayerUseCommands( EntityPlayer player )
|
||||
{
|
||||
MinecraftServer server = MinecraftServer.getServer();
|
||||
if( server != null )
|
||||
{
|
||||
return server.getConfigurationManager().canSendCommands( player.getGameProfile() );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isPlayerOpped( EntityPlayer player )
|
||||
{
|
||||
MinecraftServer server = MinecraftServer.getServer();
|
||||
if( server != null )
|
||||
{
|
||||
return server.getConfigurationManager().getOppedPlayers().getEntry( player.getGameProfile() ) != null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void registerPermissionProvider( ITurtlePermissionProvider provider )
|
||||
{
|
||||
if( provider != null && !permissionProviders.contains( provider ) )
|
||||
{
|
||||
permissionProviders.add( provider );
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isBlockEnterable( World world, BlockPos pos, EntityPlayer player )
|
||||
{
|
||||
MinecraftServer server = MinecraftServer.getServer();
|
||||
if( server != null && !world.isRemote )
|
||||
{
|
||||
if( server.isBlockProtected( world, pos, player ) )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for( int i=0; i<permissionProviders.size(); ++i )
|
||||
{
|
||||
ITurtlePermissionProvider provider = permissionProviders.get( i );
|
||||
if( !provider.isBlockEnterable( world, pos ) )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isBlockEditable( World world, BlockPos pos, EntityPlayer player )
|
||||
{
|
||||
MinecraftServer server = MinecraftServer.getServer();
|
||||
if( server != null && !world.isRemote )
|
||||
{
|
||||
if( server.isBlockProtected( world, pos, player ) )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for( int i=0; i<permissionProviders.size(); ++i )
|
||||
{
|
||||
ITurtlePermissionProvider provider = permissionProviders.get( i );
|
||||
if( !provider.isBlockEditable( world, pos ) )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void registerPeripheralProvider( IPeripheralProvider provider )
|
||||
{
|
||||
if( provider != null && !peripheralProviders.contains( provider ) )
|
||||
{
|
||||
peripheralProviders.add( provider );
|
||||
}
|
||||
}
|
||||
|
||||
public static void registerBundledRedstoneProvider( IBundledRedstoneProvider provider )
|
||||
{
|
||||
if( provider != null && !bundledRedstoneProviders.contains( provider ) )
|
||||
{
|
||||
bundledRedstoneProviders.add( provider );
|
||||
}
|
||||
}
|
||||
|
||||
public static void registerMediaProvider( IMediaProvider provider )
|
||||
{
|
||||
if( provider != null && !mediaProviders.contains( provider ) )
|
||||
{
|
||||
mediaProviders.add( provider );
|
||||
}
|
||||
}
|
||||
|
||||
public static IPeripheral getPeripheralAt( World world, BlockPos pos, EnumFacing side )
|
||||
{
|
||||
// Try the handlers in order:
|
||||
Iterator<IPeripheralProvider> it = peripheralProviders.iterator();
|
||||
while( it.hasNext() )
|
||||
{
|
||||
try
|
||||
{
|
||||
IPeripheralProvider handler = it.next();
|
||||
IPeripheral peripheral = handler.getPeripheral( world, pos, side );
|
||||
if( peripheral != null )
|
||||
{
|
||||
return peripheral;
|
||||
}
|
||||
}
|
||||
catch( Exception e )
|
||||
{
|
||||
// mod misbehaved, ignore it
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int getDefaultBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side )
|
||||
{
|
||||
if( WorldUtil.isBlockInWorld( world, pos ) )
|
||||
{
|
||||
return DefaultBundledRedstoneProvider.getDefaultBundledRedstoneOutput( world, pos, side );
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int getBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side )
|
||||
{
|
||||
int y = pos.getY();
|
||||
if( y < 0 || y >= world.getHeight() )
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Try the handlers in order:
|
||||
int combinedSignal = -1;
|
||||
Iterator<IBundledRedstoneProvider> it = bundledRedstoneProviders.iterator();
|
||||
while( it.hasNext() )
|
||||
{
|
||||
try
|
||||
{
|
||||
IBundledRedstoneProvider handler = it.next();
|
||||
int signal = handler.getBundledRedstoneOutput( world, pos, side );
|
||||
if( signal >= 0 )
|
||||
{
|
||||
if( combinedSignal < 0 )
|
||||
{
|
||||
combinedSignal = (signal & 0xffff);
|
||||
}
|
||||
else
|
||||
{
|
||||
combinedSignal = combinedSignal | (signal & 0xffff);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch( Exception e )
|
||||
{
|
||||
// mod misbehaved, ignore it
|
||||
}
|
||||
}
|
||||
return combinedSignal;
|
||||
}
|
||||
|
||||
public static IMedia getMedia( ItemStack stack )
|
||||
{
|
||||
if( stack != null )
|
||||
{
|
||||
// Try the handlers in order:
|
||||
Iterator<IMediaProvider> it = mediaProviders.iterator();
|
||||
while( it.hasNext() )
|
||||
{
|
||||
try
|
||||
{
|
||||
IMediaProvider handler = it.next();
|
||||
IMedia media = handler.getMedia( stack );
|
||||
if( media != null )
|
||||
{
|
||||
return media;
|
||||
}
|
||||
}
|
||||
catch( Exception e )
|
||||
{
|
||||
// mod misbehaved, ignore it
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int createUniqueNumberedSaveDir( World world, String parentSubPath )
|
||||
{
|
||||
return IDAssigner.getNextIDFromDirectory(new File(getWorldDir(world), parentSubPath));
|
||||
}
|
||||
|
||||
public static IWritableMount createSaveDirMount( World world, String subPath, long capacity )
|
||||
{
|
||||
try
|
||||
{
|
||||
return new FileMount( new File( getWorldDir( world ), subPath ), capacity );
|
||||
}
|
||||
catch( Exception e )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static IMount createResourceMount( Class modClass, String domain, String subPath )
|
||||
{
|
||||
// Start building list of mounts
|
||||
List<IMount> mounts = new ArrayList<IMount>();
|
||||
subPath = "assets/" + domain + "/" + subPath;
|
||||
|
||||
// Mount from debug dir
|
||||
File codeDir = getDebugCodeDir( modClass );
|
||||
if( codeDir != null )
|
||||
{
|
||||
File subResource = new File( codeDir, subPath );
|
||||
if( subResource.exists() )
|
||||
{
|
||||
IMount resourcePackMount = new FileMount( subResource, 0 );
|
||||
mounts.add( resourcePackMount );
|
||||
}
|
||||
}
|
||||
|
||||
// Mount from mod jar
|
||||
File modJar = getContainingJar( modClass );
|
||||
if( modJar != null )
|
||||
{
|
||||
try
|
||||
{
|
||||
IMount jarMount = new JarMount( modJar, subPath );
|
||||
mounts.add( jarMount );
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
// Mount from resource packs
|
||||
File resourcePackDir = getResourcePackDir();
|
||||
if( resourcePackDir.exists() && resourcePackDir.isDirectory() )
|
||||
{
|
||||
String[] resourcePacks = resourcePackDir.list();
|
||||
for( int i=0; i<resourcePacks.length; ++i )
|
||||
{
|
||||
try
|
||||
{
|
||||
File resourcePack = new File( resourcePackDir, resourcePacks[i] );
|
||||
if( !resourcePack.isDirectory() )
|
||||
{
|
||||
// Mount a resource pack from a jar
|
||||
IMount resourcePackMount = new JarMount( resourcePack, subPath );
|
||||
mounts.add( resourcePackMount );
|
||||
}
|
||||
else
|
||||
{
|
||||
// Mount a resource pack from a folder
|
||||
File subResource = new File( resourcePack, subPath );
|
||||
if( subResource.exists() )
|
||||
{
|
||||
IMount resourcePackMount = new FileMount( subResource, 0 );
|
||||
mounts.add( resourcePackMount );
|
||||
}
|
||||
}
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Return the combination of all the mounts found
|
||||
if( mounts.size() >= 2 )
|
||||
{
|
||||
IMount[] mountArray = new IMount[ mounts.size() ];
|
||||
mounts.toArray( mountArray );
|
||||
return new ComboMount( mountArray );
|
||||
}
|
||||
else if( mounts.size() == 1 )
|
||||
{
|
||||
return mounts.get( 0 );
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static File getContainingJar( Class modClass )
|
||||
{
|
||||
String path = modClass.getProtectionDomain().getCodeSource().getLocation().getPath();
|
||||
int bangIndex = path.indexOf( "!" );
|
||||
if( bangIndex >= 0 )
|
||||
{
|
||||
path = path.substring( 0, bangIndex );
|
||||
}
|
||||
|
||||
URL url;
|
||||
try {
|
||||
url = new URL( path );
|
||||
} catch (MalformedURLException e1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
File file;
|
||||
try {
|
||||
file = new File( url.toURI() );
|
||||
} catch(URISyntaxException e) {
|
||||
file = new File( url.getPath() );
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private static File getDebugCodeDir( Class modClass )
|
||||
{
|
||||
String path = modClass.getProtectionDomain().getCodeSource().getLocation().getPath();
|
||||
int bangIndex = path.indexOf("!");
|
||||
if( bangIndex >= 0 )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return new File( new File( path ).getParentFile(), "../.." );
|
||||
}
|
||||
|
||||
public static void registerTurtleUpgrade( ITurtleUpgrade upgrade )
|
||||
{
|
||||
turtleProxy.registerTurtleUpgrade( upgrade );
|
||||
}
|
||||
|
||||
public static ITurtleUpgrade getTurtleUpgrade( String id )
|
||||
{
|
||||
return turtleProxy.getTurtleUpgrade( id );
|
||||
}
|
||||
|
||||
public static ITurtleUpgrade getTurtleUpgrade( int legacyID )
|
||||
{
|
||||
return turtleProxy.getTurtleUpgrade( legacyID );
|
||||
}
|
||||
|
||||
public static ITurtleUpgrade getTurtleUpgrade( ItemStack item )
|
||||
{
|
||||
return turtleProxy.getTurtleUpgrade( item );
|
||||
}
|
||||
|
||||
public static void addAllUpgradedTurtles( List<ItemStack> list )
|
||||
{
|
||||
turtleProxy.addAllUpgradedTurtles( list );
|
||||
}
|
||||
|
||||
public static void setEntityDropConsumer( Entity entity, IEntityDropConsumer consumer )
|
||||
{
|
||||
turtleProxy.setEntityDropConsumer( entity, consumer );
|
||||
}
|
||||
|
||||
public static void clearEntityDropConsumer( Entity entity )
|
||||
{
|
||||
turtleProxy.clearEntityDropConsumer( entity );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.media.IMediaProvider;
|
||||
import dan200.computercraft.api.peripheral.IPeripheralProvider;
|
||||
import dan200.computercraft.api.permissions.ITurtlePermissionProvider;
|
||||
import dan200.computercraft.api.redstone.IBundledRedstoneProvider;
|
||||
import dan200.computercraft.api.turtle.ITurtleUpgrade;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* 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
|
||||
{
|
||||
public static boolean isInstalled()
|
||||
{
|
||||
findCC();
|
||||
return computerCraft != null;
|
||||
}
|
||||
|
||||
public static String getInstalledVersion()
|
||||
{
|
||||
findCC();
|
||||
if( computerCraft_getVersion != null )
|
||||
{
|
||||
try {
|
||||
return (String)computerCraft_getVersion.invoke( null );
|
||||
} catch (Exception e) {
|
||||
// It failed
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static String getAPIVersion()
|
||||
{
|
||||
return "${version}";
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a numbered directory in a subfolder of the save directory for a given world, and returns that number.<br>
|
||||
* Use in conjuction with createSaveDirMount() to create a unique place for your peripherals or media items to store files.<br>
|
||||
* @param world The world for which the save dir should be created. This should be the serverside 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.<br>
|
||||
* 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( World world, String parentSubPath )
|
||||
{
|
||||
findCC();
|
||||
if( computerCraft_createUniqueNumberedSaveDir != null )
|
||||
{
|
||||
try {
|
||||
return (Integer)computerCraft_createUniqueNumberedSaveDir.invoke( null, world, parentSubPath );
|
||||
} catch (Exception e) {
|
||||
// It failed
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a file system mount that maps to a subfolder of the save directory for a given world, and returns it.<br>
|
||||
* Use in conjuction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a folder from the
|
||||
* users save directory onto a computers file system.<br>
|
||||
* @param world The world for which the save dir can be found. This should be the serverside world object.
|
||||
* @param subPath The folder path within the save directory that the mount should map to. eg: "computer/disk/42".<br>
|
||||
* Use createUniqueNumberedSaveDir() to create a new numbered folder to use.
|
||||
* @param capacity The ammount 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 dan200.computercraft.api.peripheral.IComputerAccess#mount(String, dan200.computercraft.api.filesystem.IMount)
|
||||
* @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, dan200.computercraft.api.filesystem.IWritableMount)
|
||||
* @see dan200.computercraft.api.filesystem.IMount
|
||||
* @see IWritableMount
|
||||
*/
|
||||
public static IWritableMount createSaveDirMount( World world, String subPath, long capacity )
|
||||
{
|
||||
findCC();
|
||||
if( computerCraft_createSaveDirMount != null )
|
||||
{
|
||||
try {
|
||||
return (IWritableMount)computerCraft_createSaveDirMount.invoke( null, world, subPath, capacity );
|
||||
} catch (Exception e){
|
||||
// It failed
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a file system mount to a resource folder, and returns it.<br>
|
||||
* Use in conjuction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a resource folder onto a computers file system.<br>
|
||||
* The files in this mount will be a combination of files in the specified mod jar, and resource packs that contain resources with the same domain and path.<br>
|
||||
* @param modClass A class in whose jar to look first for the resources to mount. Using your main mod class is recommended. eg: MyMod.class
|
||||
* @param domain The domain under which to look for resources. eg: "mymod"
|
||||
* @param subPath The domain under which to look for resources. eg: "mymod/lua/myfiles"
|
||||
* @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 dan200.computercraft.api.peripheral.IComputerAccess#mount(String, dan200.computercraft.api.filesystem.IMount)
|
||||
* @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, IWritableMount)
|
||||
* @see dan200.computercraft.api.filesystem.IMount
|
||||
*/
|
||||
public static IMount createResourceMount( Class modClass, String domain, String subPath )
|
||||
{
|
||||
findCC();
|
||||
if( computerCraft_createResourceMount != null )
|
||||
{
|
||||
try {
|
||||
return (IMount)computerCraft_createResourceMount.invoke( null, modClass, domain, subPath );
|
||||
} catch (Exception e){
|
||||
// It failed
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a peripheral handler to convert blocks into IPeripheral implementations.
|
||||
* @see dan200.computercraft.api.peripheral.IPeripheral
|
||||
* @see dan200.computercraft.api.peripheral.IPeripheralProvider
|
||||
*/
|
||||
public static void registerPeripheralProvider( IPeripheralProvider handler )
|
||||
{
|
||||
findCC();
|
||||
if ( computerCraft_registerPeripheralProvider != null)
|
||||
{
|
||||
try {
|
||||
computerCraft_registerPeripheralProvider.invoke( null, handler );
|
||||
} catch (Exception e){
|
||||
// It failed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @see dan200.computercraft.api.turtle.ITurtleUpgrade
|
||||
*/
|
||||
public static void registerTurtleUpgrade( ITurtleUpgrade upgrade )
|
||||
{
|
||||
if( upgrade != null )
|
||||
{
|
||||
findCC();
|
||||
if( computerCraft_registerTurtleUpgrade != null )
|
||||
{
|
||||
try {
|
||||
computerCraft_registerTurtleUpgrade.invoke( null, upgrade );
|
||||
} catch( Exception e ) {
|
||||
// It failed
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a bundled redstone handler to provide bundled redstone output for blocks
|
||||
* @see dan200.computercraft.api.redstone.IBundledRedstoneProvider
|
||||
*/
|
||||
public static void registerBundledRedstoneProvider( IBundledRedstoneProvider handler )
|
||||
{
|
||||
findCC();
|
||||
if( computerCraft_registerBundledRedstoneProvider != null )
|
||||
{
|
||||
try {
|
||||
computerCraft_registerBundledRedstoneProvider.invoke( null, handler );
|
||||
} catch (Exception e) {
|
||||
// It failed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If there is a Computer or Turtle at a certain position in the world, get it's bundled redstone output.
|
||||
* @see dan200.computercraft.api.redstone.IBundledRedstoneProvider
|
||||
* @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.
|
||||
*/
|
||||
public static int getBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side )
|
||||
{
|
||||
findCC();
|
||||
if( computerCraft_getDefaultBundledRedstoneOutput != null )
|
||||
{
|
||||
try {
|
||||
return (Integer)computerCraft_getDefaultBundledRedstoneOutput.invoke( null, world, pos, side );
|
||||
} catch (Exception e){
|
||||
// It failed
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a media handler to provide IMedia implementations for Items
|
||||
* @see dan200.computercraft.api.media.IMediaProvider
|
||||
*/
|
||||
public static void registerMediaProvider( IMediaProvider handler )
|
||||
{
|
||||
findCC();
|
||||
if( computerCraft_registerMediaProvider != null )
|
||||
{
|
||||
try {
|
||||
computerCraft_registerMediaProvider.invoke( null, handler );
|
||||
} catch (Exception e){
|
||||
// It failed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a permission handler to restrict where turtles can move or build
|
||||
* @see dan200.computercraft.api.permissions.ITurtlePermissionProvider
|
||||
*/
|
||||
public static void registerPermissionProvider( ITurtlePermissionProvider handler )
|
||||
{
|
||||
findCC();
|
||||
if( computerCraft_registerPermissionProvider != null )
|
||||
{
|
||||
try {
|
||||
computerCraft_registerPermissionProvider.invoke( null, handler );
|
||||
} catch (Exception e) {
|
||||
// It failed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The functions below here are private, and are used to interface with the non-API ComputerCraft classes.
|
||||
// Reflection is used here so you can develop your mod without decompiling ComputerCraft and including
|
||||
// it in your solution, and so your mod won't crash if ComputerCraft is installed.
|
||||
|
||||
private static void findCC()
|
||||
{
|
||||
if( !ccSearched ) {
|
||||
try {
|
||||
computerCraft = Class.forName( "dan200.computercraft.ComputerCraft" );
|
||||
computerCraft_getVersion = findCCMethod( "getVersion", new Class[]{
|
||||
} );
|
||||
computerCraft_createUniqueNumberedSaveDir = findCCMethod( "createUniqueNumberedSaveDir", new Class[]{
|
||||
World.class, String.class
|
||||
} );
|
||||
computerCraft_createSaveDirMount = findCCMethod( "createSaveDirMount", new Class[] {
|
||||
World.class, String.class, Long.TYPE
|
||||
} );
|
||||
computerCraft_createResourceMount = findCCMethod( "createResourceMount", new Class[] {
|
||||
Class.class, String.class, String.class
|
||||
} );
|
||||
computerCraft_registerPeripheralProvider = findCCMethod( "registerPeripheralProvider", new Class[] {
|
||||
IPeripheralProvider.class
|
||||
} );
|
||||
computerCraft_registerTurtleUpgrade = findCCMethod( "registerTurtleUpgrade", new Class[] {
|
||||
ITurtleUpgrade.class
|
||||
} );
|
||||
computerCraft_registerBundledRedstoneProvider = findCCMethod( "registerBundledRedstoneProvider", new Class[] {
|
||||
IBundledRedstoneProvider.class
|
||||
} );
|
||||
computerCraft_getDefaultBundledRedstoneOutput = findCCMethod( "getDefaultBundledRedstoneOutput", new Class[] {
|
||||
World.class, BlockPos.class, EnumFacing.class
|
||||
} );
|
||||
computerCraft_registerMediaProvider = findCCMethod( "registerMediaProvider", new Class[] {
|
||||
IMediaProvider.class
|
||||
} );
|
||||
computerCraft_registerPermissionProvider = findCCMethod( "registerPermissionProvider", new Class[] {
|
||||
ITurtlePermissionProvider.class
|
||||
} );
|
||||
} catch( Exception e ) {
|
||||
System.out.println( "ComputerCraftAPI: ComputerCraft not found." );
|
||||
} finally {
|
||||
ccSearched = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Method findCCMethod( String name, Class[] args )
|
||||
{
|
||||
try {
|
||||
if( computerCraft != null )
|
||||
{
|
||||
return computerCraft.getMethod( name, args );
|
||||
}
|
||||
return null;
|
||||
} catch( NoSuchMethodException e ) {
|
||||
System.out.println( "ComputerCraftAPI: ComputerCraft method " + name + " not found." );
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean ccSearched = false;
|
||||
private static Class computerCraft = null;
|
||||
private static Method computerCraft_getVersion = null;
|
||||
private static Method computerCraft_createUniqueNumberedSaveDir = null;
|
||||
private static Method computerCraft_createSaveDirMount = null;
|
||||
private static Method computerCraft_createResourceMount = null;
|
||||
private static Method computerCraft_registerPeripheralProvider = null;
|
||||
private static Method computerCraft_registerTurtleUpgrade = null;
|
||||
private static Method computerCraft_registerBundledRedstoneProvider = null;
|
||||
private static Method computerCraft_getDefaultBundledRedstoneOutput = null;
|
||||
private static Method computerCraft_registerMediaProvider = null;
|
||||
private static Method computerCraft_registerPermissionProvider = null;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Represents a read only part of a virtual filesystem that can be mounted onto a computercraft using IComputerAccess.mount().
|
||||
* Ready made implementations of this interface can be created using ComputerCraftAPI.createSaveDirMount() or ComputerCraftAPI.createResourceMount(), or you're free to implement it yourselves!
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String)
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String)
|
||||
* @see dan200.computercraft.api.peripheral.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 true if the file exists, false otherwise
|
||||
*/
|
||||
public boolean exists( 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 true if the file exists and is a directory, false otherwise
|
||||
*/
|
||||
public boolean isDirectory( 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
|
||||
*/
|
||||
public void list( String path, 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
|
||||
*/
|
||||
public long getSize( String path ) throws IOException;
|
||||
|
||||
/**
|
||||
* Opens a file with a given path, and returns an inputstream representing it's contents.
|
||||
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram"
|
||||
* @return a stream representing the contents of the file
|
||||
*/
|
||||
public InputStream openForRead( String path ) throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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;
|
||||
import java.io.OutputStream;
|
||||
|
||||
/**
|
||||
* Represents a part of a virtual filesystem that can be mounted onto a computercraft using IComputerAccess.mount() or IComputerAccess.mountWritable(), that can also be written to.
|
||||
* Ready made implementations of this interface can be created using ComputerCraftAPI.createSaveDirMount(), or you're free to implement it yourselves!
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String)
|
||||
* @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, dan200.computercraft.api.filesystem.IMount)
|
||||
* @see dan200.computercraft.api.filesystem.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"
|
||||
*/
|
||||
public void makeDirectory( 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"
|
||||
*/
|
||||
public void delete( String path ) throws IOException;
|
||||
|
||||
/**
|
||||
* Opens a file with a given path, and returns an 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
|
||||
*/
|
||||
public OutputStream openForWrite( String path ) throws IOException;
|
||||
|
||||
/**
|
||||
* Opens a file with a given path, and returns an 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
|
||||
*/
|
||||
public OutputStream openForAppend( String path ) throws IOException;
|
||||
|
||||
/**
|
||||
* Get the ammount 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 ammount of free space, in bytes.
|
||||
*/
|
||||
public long getRemainingSpace() throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.
|
||||
*/
|
||||
|
||||
@API( owner="ComputerCraft", provides="ComputerCraft|API|FileSystem", apiVersion="${version}" )
|
||||
package dan200.computercraft.api.filesystem;
|
||||
|
||||
import net.minecraftforge.fml.common.API;
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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;
|
||||
|
||||
/**
|
||||
* An interface passed to peripherals and ILuaObjects' by computers or turtles, providing methods
|
||||
* that allow the peripheral call to wait for events before returning, just like in lua.
|
||||
* This is very useful if you need to signal work to be performed on the main thread, and don't want to return
|
||||
* until the work has been completed.
|
||||
*/
|
||||
public interface ILuaContext
|
||||
{
|
||||
/**
|
||||
* Wait for an event to occur on the computercraft, suspending the thread until it arises. This method is exactly equivalent to os.pullEvent() in lua.
|
||||
* @param filter A specific event to wait for, or null to wait for any event
|
||||
* @return An object array containing the name of the event that occurred, and any event parameters
|
||||
* @throws Exception If the user presses CTRL+T to terminate the current program while pullEvent() is waiting for an event, a "Terminated" exception will be thrown here.
|
||||
* Do not attempt to common this exception, unless you wish to prevent termination, which is not recommended.
|
||||
* @throws InterruptedException If the user shuts down or reboots the computercraft while pullEvent() is waiting for an event, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state.
|
||||
*/
|
||||
public Object[] pullEvent( String filter ) throws LuaException, InterruptedException;
|
||||
|
||||
/**
|
||||
* The same as pullEvent(), 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 os.pullEventRaw() in lua.
|
||||
* @param filter A specific event to wait for, or null to wait for any event
|
||||
* @return An object array containing the name of the event that occurred, and any event parameters
|
||||
* @throws InterruptedException If the user shuts down or reboots the computercraft while pullEventRaw() is waiting for an event, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state.
|
||||
* @see #pullEvent(String)
|
||||
*/
|
||||
public Object[] pullEventRaw( String filter ) throws InterruptedException;
|
||||
|
||||
/**
|
||||
* Yield the current coroutine with some arguments until it is resumed. This method is exactly equivalent to coroutine.yield() in lua. Use pullEvent() if you wish to wait for events.
|
||||
* @param arguments An object array containing the arguments to pass to coroutine.yield()
|
||||
* @return An object array containing the return values from coroutine.yield()
|
||||
* @throws InterruptedException If the user shuts down or reboots the computercraft the coroutine is suspended, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state.
|
||||
* @see #pullEvent(String)
|
||||
*/
|
||||
public Object[] yield( Object[] arguments ) throws InterruptedException;
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
* @param task
|
||||
* @return
|
||||
*/
|
||||
public Object[] executeMainThreadTask( ILuaTask task ) throws LuaException, InterruptedException;
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
* @param task
|
||||
* @return
|
||||
*/
|
||||
public long issueMainThreadTask( ILuaTask task ) throws LuaException;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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;
|
||||
|
||||
/**
|
||||
* An interface for representing custom objects returned by IPeripheral.callMethod() calls.
|
||||
* Return objects implementing this interface to expose objects with methods to lua.
|
||||
*/
|
||||
public interface ILuaObject
|
||||
{
|
||||
/**
|
||||
* Get the names of the methods that this object implements. This works the same as IPeripheral.getMethodNames(). See that method for detailed documentation.
|
||||
* @see dan200.computercraft.api.peripheral.IPeripheral#getMethodNames()
|
||||
*/
|
||||
public String[] getMethodNames();
|
||||
|
||||
/**
|
||||
* Called when a user calls one of the methods that this object implements. This works the same as IPeripheral.callMethod(). See that method for detailed documentation.
|
||||
* @see dan200.computercraft.api.peripheral.IPeripheral#callMethod(dan200.computercraft.api.peripheral.IComputerAccess, ILuaContext, int, Object[])
|
||||
*/
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] arguments ) throws LuaException, InterruptedException;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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;
|
||||
|
||||
public interface ILuaTask
|
||||
{
|
||||
public Object[] execute() throws LuaException;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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;
|
||||
|
||||
/**
|
||||
* An exception representing an error in Lua, like that raised by the error() function
|
||||
*/
|
||||
public class LuaException extends Exception
|
||||
{
|
||||
private final int m_level;
|
||||
|
||||
public LuaException()
|
||||
{
|
||||
this( "error", 1 );
|
||||
}
|
||||
|
||||
public LuaException( String message )
|
||||
{
|
||||
this( message, 1 );
|
||||
}
|
||||
|
||||
public LuaException( String message, int level )
|
||||
{
|
||||
super( message );
|
||||
m_level = level;
|
||||
}
|
||||
|
||||
public int getLevel()
|
||||
{
|
||||
return m_level;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.
|
||||
*/
|
||||
|
||||
@API( owner="ComputerCraft", provides="ComputerCraft|API|Lua", apiVersion="${version}" )
|
||||
package dan200.computercraft.api.lua;
|
||||
|
||||
import net.minecraftforge.fml.common.API;
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.ItemStack;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
/**
|
||||
* Represents an item that can be placed in a disk drive and used by a Computer.
|
||||
* Implement this interface on your Item class to allow it to be used in the drive.
|
||||
*/
|
||||
public interface IMedia
|
||||
{
|
||||
/**
|
||||
* Get a string representing the label of this item. Will be called vi disk.getLabel() in lua.
|
||||
* @param stack The itemstack to inspect
|
||||
* @return The label. ie: "Dan's Programs"
|
||||
*/
|
||||
public String getLabel( ItemStack stack );
|
||||
|
||||
/**
|
||||
* Set a string representing the label of this item. Will be called vi disk.setLabel() in lua.
|
||||
* @param stack The 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.
|
||||
*/
|
||||
public boolean setLabel( ItemStack stack, String label );
|
||||
|
||||
/**
|
||||
* If this disk represents an item with audio (like a record), get the readable name of the audio track. ie: "Jonathon Coulton - Still Alive"
|
||||
* @param stack The itemstack to inspect.
|
||||
* @return The name, or null if this item does not represent an item with audio.
|
||||
*/
|
||||
public String getAudioTitle( ItemStack stack );
|
||||
|
||||
/**
|
||||
* If this disk represents an item with audio (like a record), get the resource name of the audio track to play.
|
||||
* @param stack The itemstack to inspect.
|
||||
* @return The name, or null if this item does not represent an item with audio.
|
||||
*/
|
||||
public String getAudioRecordName( ItemStack stack );
|
||||
|
||||
/**
|
||||
* 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 computercraft while the media is in the disk drive.
|
||||
* @param stack The itemstack to inspect.
|
||||
* @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 IMount returned also implements IWritableMount, it will mounted using mountWritable()
|
||||
* @see dan200.computercraft.api.filesystem.IMount
|
||||
* @see dan200.computercraft.api.filesystem.IWritableMount
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String, long)
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String)
|
||||
*/
|
||||
public IMount createDataMount( ItemStack stack, World world );
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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;
|
||||
|
||||
/**
|
||||
* This interface is used to provide IMedia implementations for ItemStack
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider)
|
||||
*/
|
||||
public interface IMediaProvider
|
||||
{
|
||||
/**
|
||||
* Produce an IMedia implementation from an ItemStack.
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider)
|
||||
* @return an IMedia implementation, or null if the item is not something you wish to handle
|
||||
*/
|
||||
public IMedia getMedia( ItemStack stack );
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.
|
||||
*/
|
||||
|
||||
@API( owner="ComputerCraft", provides="ComputerCraft|API|Media", apiVersion="${version}" )
|
||||
package dan200.computercraft.api.media;
|
||||
|
||||
import net.minecraftforge.fml.common.API;
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.
|
||||
*/
|
||||
|
||||
@API( owner="ComputerCraft", provides="ComputerCraft|API", apiVersion="${version}" )
|
||||
package dan200.computercraft.api;
|
||||
|
||||
import net.minecraftforge.fml.common.API;
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.filesystem.IMount;
|
||||
import dan200.computercraft.api.filesystem.IWritableMount;
|
||||
|
||||
/**
|
||||
* 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 computers' file system in a read only mode.<br>
|
||||
* @param desiredLocation The location on the computercraft's file system where you would like the mount to be mounted.
|
||||
* @param mount The mount object to mount on the computercraft. These can be obtained by calling ComputerCraftAPI.createSaveDirMount(), ComputerCraftAPI.createResourceMount() or by creating your own objects that implement the IMount interface.
|
||||
* @return The location on the computercraft'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.
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String)
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String)
|
||||
* @see #mountWritable(String, dan200.computercraft.api.filesystem.IWritableMount)
|
||||
* @see #unmount(String)
|
||||
* @see dan200.computercraft.api.filesystem.IMount
|
||||
*/
|
||||
public String mount( String desiredLocation, IMount mount );
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public String mount( String desiredLocation, IMount mount, String driveName );
|
||||
|
||||
/**
|
||||
* Mount a mount onto the computers' file system in a writable mode.<br>
|
||||
* @param desiredLocation The location on the computercraft's file system where you would like the mount to be mounted.
|
||||
* @param mount The mount object to mount on the computercraft. These can be obtained by calling ComputerCraftAPI.createSaveDirMount() or by creating your own objects that implement the IWritableMount interface.
|
||||
* @return The location on the computercraft'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.
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String)
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String)
|
||||
* @see #mount(String, IMount)
|
||||
* @see #unmount(String)
|
||||
* @see IMount
|
||||
*/
|
||||
public String mountWritable( String desiredLocation, IWritableMount mount );
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public String mountWritable( String desiredLocation, IWritableMount mount, String driveName );
|
||||
|
||||
/**
|
||||
* Unmounts a directory previously mounted onto the computers file system by mount() or mountWritable().<br>
|
||||
* 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.
|
||||
* @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 mount() or mountWritable(), as
|
||||
* indicated by their return value.
|
||||
* @see #mount(String, IMount)
|
||||
* @see #mountWritable(String, IWritableMount)
|
||||
*/
|
||||
public void unmount( String location );
|
||||
|
||||
/**
|
||||
* Returns the numerical ID of this computercraft.<br>
|
||||
* This is the same number obtained by calling os.getComputerID() or running the "id" program from lua,
|
||||
* and is guarunteed unique. This number will be positive.
|
||||
* @return The identifier.
|
||||
*/
|
||||
public int getID();
|
||||
|
||||
/**
|
||||
* Causes an event to be raised on this computercraft, which the computercraft can respond to by calling
|
||||
* os.pullEvent(). This can be used to notify the computercraft 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 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().<br>
|
||||
* You may supply null to indicate that no arguments are to be supplied.
|
||||
* @see dan200.computercraft.api.peripheral.IPeripheral#callMethod
|
||||
*/
|
||||
public void queueEvent( String event, Object[] arguments );
|
||||
|
||||
/**
|
||||
* Get a string, unique to the computercraft, by which the computercraft 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 computercraft, so that the computercraft knows from
|
||||
* which peripheral the event came.
|
||||
* @return A string unique to the computercraft, but not globally.
|
||||
*/
|
||||
public String getAttachmentName();
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.ILuaContext;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
|
||||
/**
|
||||
* The interface that defines a peripheral. See IPeripheralProvider for how to associate blocks with peripherals.
|
||||
*/
|
||||
public interface IPeripheral
|
||||
{
|
||||
/**
|
||||
* Should return a string that uniquely identifies this type of peripheral.
|
||||
* This can be queried from lua by calling peripheral.getType()
|
||||
* @return A string identifying the type of peripheral.
|
||||
*/
|
||||
public String getType();
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
public String[] getMethodNames();
|
||||
|
||||
/**
|
||||
* This is called when a lua program on an attached computercraft calls peripheral.call() with
|
||||
* one of the methods exposed by getMethodNames().<br>
|
||||
* <br>
|
||||
* 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 computercraft 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 An array of objects, representing the arguments passed into peripheral.call().<br>
|
||||
* Lua values of type "string" will be represented by Object type String.<br>
|
||||
* Lua values of type "number" will be represented by Object type Double.<br>
|
||||
* Lua values of type "boolean" will be represented by Object type Boolean.<br>
|
||||
* Lua values of any other type will be represented by a null object.<br>
|
||||
* This array will be empty if no arguments are passed.
|
||||
* @return An array of objects, representing values you wish to return to the lua program.<br>
|
||||
* Integers, Doubles, Floats, Strings, Booleans and null be converted to their corresponding lua type.<br>
|
||||
* All other types will be converted to nil.<br>
|
||||
* You may return null to indicate no values should be returned.
|
||||
* @throws Exception 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
|
||||
*/
|
||||
public Object[] callMethod( IComputerAccess computer, ILuaContext context, int method, Object[] arguments ) throws LuaException, InterruptedException;
|
||||
|
||||
/**
|
||||
* Is called when canAttachToSide has returned true, and a computercraft is attaching to the peripheral.
|
||||
* This will occur when a peripheral is placed next to an active computercraft, when a computercraft is turned on next to a peripheral,
|
||||
* or when a turtle travels into a square next to a peripheral.
|
||||
* Between calls to attach() and detach(), the attached computercraft can make method calls on the peripheral using 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.<br>
|
||||
* <br>
|
||||
* 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 computercraft that is being attached. Remember that multiple
|
||||
* computers can be attached to a peripheral at once.
|
||||
* @see #detach
|
||||
*/
|
||||
public void attach( IComputerAccess computer );
|
||||
|
||||
/**
|
||||
* Is called when a computercraft is detaching from the peripheral.
|
||||
* This will occur when a computercraft shuts down, when the peripheral is removed while attached to computers,
|
||||
* or when a turtle moves away from a square attached to a peripheral.
|
||||
* This method can be used to keep track of which computers are attached to the peripheral, or to take action when detachment
|
||||
* occurs.<br>
|
||||
* <br>
|
||||
* 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 computercraft that is being detached. Remember that multiple
|
||||
* computers can be attached to a peripheral at once.
|
||||
* @see #detach
|
||||
*/
|
||||
public void detach( IComputerAccess computer );
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public boolean equals( IPeripheral other );
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
/**
|
||||
* This interface is used to create peripheral implementations for blocks
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider)
|
||||
*/
|
||||
public interface IPeripheralProvider
|
||||
{
|
||||
/**
|
||||
* Produce an peripheral implementation from a block location.
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider)
|
||||
* @return a peripheral, or null if there is not a peripheral here you'd like to handle.
|
||||
*/
|
||||
public IPeripheral getPeripheral( World world, BlockPos pos, EnumFacing side );
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.
|
||||
*/
|
||||
|
||||
@API( owner="ComputerCraft", provides="ComputerCraft|API|Peripheral", apiVersion="${version}" )
|
||||
package dan200.computercraft.api.peripheral;
|
||||
|
||||
import net.minecraftforge.fml.common.API;
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.permissions;
|
||||
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
/**
|
||||
* This interface is used to restrict where turtles can move or build
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#registerPermissionProvider(ITurtlePermissionProvider)
|
||||
*/
|
||||
public interface ITurtlePermissionProvider
|
||||
{
|
||||
public boolean isBlockEnterable( World world, BlockPos pos );
|
||||
public boolean isBlockEditable( World world, BlockPos pos );
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.
|
||||
*/
|
||||
|
||||
@API( owner="ComputerCraft", provides="ComputerCraft|API|Permissions", apiVersion="${version}" )
|
||||
package dan200.computercraft.api.permissions;
|
||||
|
||||
import net.minecraftforge.fml.common.API;
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
/**
|
||||
* This interface is used to provide bundled redstone output for blocks
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider)
|
||||
*/
|
||||
public interface IBundledRedstoneProvider
|
||||
{
|
||||
/**
|
||||
* Produce an bundled redstone output from a block location.
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider)
|
||||
* @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
|
||||
*/
|
||||
public int getBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side );
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.
|
||||
*/
|
||||
|
||||
@API( owner="ComputerCraft", provides="ComputerCraft|API|Redstone", apiVersion="${version}" )
|
||||
package dan200.computercraft.api.redstone;
|
||||
|
||||
import net.minecraftforge.fml.common.API;
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.api.peripheral.IPeripheral;
|
||||
import net.minecraft.inventory.IInventory;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.util.Vec3;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
/**
|
||||
* 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 ITurtleUpgrade.
|
||||
*/
|
||||
public interface ITurtleAccess
|
||||
{
|
||||
/**
|
||||
* Returns the world in which the turtle resides.
|
||||
* @return the world in which the turtle resides.
|
||||
*/
|
||||
public 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.
|
||||
*/
|
||||
public BlockPos getPosition();
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public boolean teleportTo( World world, 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.
|
||||
*/
|
||||
public Vec3 getVisualPosition( float f );
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public float getVisualYaw( float f );
|
||||
|
||||
/**
|
||||
* Returns the world direction the turtle is currently facing.
|
||||
* @return the world direction the turtle is currently facing.
|
||||
*/
|
||||
public EnumFacing getDirection();
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public void setDirection( EnumFacing dir );
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public int getSelectedSlot();
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public void setSelectedSlot( int slot );
|
||||
|
||||
/**
|
||||
* Sets the colour of the turtle, as if the player had dyed it with a dye item.
|
||||
* @param dyeColour 0-15 to dye the turtle one of the 16 standard minecraft colours, or -1 to remove the dye from the turtle.
|
||||
*/
|
||||
public void setDyeColour( int dyeColour );
|
||||
|
||||
/**
|
||||
* Gets the colour the turtle has been dyed.
|
||||
* @return 0-15 if the turtle has been dyed one of the 16 standard minecraft colours, -1 if the turtle is clean.
|
||||
*/
|
||||
public int getDyeColour();
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public IInventory getInventory();
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public boolean isFuelNeeded();
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public int getFuelLevel();
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public void setFuelLevel( int fuel );
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public int getFuelLimit();
|
||||
|
||||
/**
|
||||
* Removes some fuel from the turtles fuel supply. Negative numbers can be passed in to INCREASE the fuel level of the turtle.
|
||||
* @return Whether the turtle was able to consume the ammount of fuel specified. Will return false if you supply a number
|
||||
* greater than the current fuel level of the turtle.
|
||||
*/
|
||||
public boolean consumeFuel( int fuel );
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public 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.
|
||||
* @see ITurtleCommand
|
||||
*/
|
||||
public Object[] executeCommand( ILuaContext context, ITurtleCommand command ) throws LuaException, InterruptedException;
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public void playAnimation( TurtleAnimation animation );
|
||||
|
||||
/**
|
||||
* Returns the turtle on the specified side of the turtle, if there is one.
|
||||
* @return the turtle on the specified side of the turtle, if there is one.
|
||||
*/
|
||||
public ITurtleUpgrade getUpgrade( TurtleSide side );
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public void setUpgrade( TurtleSide side, ITurtleUpgrade upgrade );
|
||||
|
||||
/**
|
||||
* Returns the peripheral created by the upgrade on the specified side of the turtle, if there is one.
|
||||
* @return the peripheral created by the upgrade on the specified side of the turtle, if there is one.
|
||||
*/
|
||||
public IPeripheral getPeripheral( TurtleSide side );
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public NBTTagCompound getUpgradeNBTData( TurtleSide side );
|
||||
|
||||
/**
|
||||
* TODO: Document me
|
||||
*/
|
||||
public void updateUpgradeNBTData( TurtleSide side );
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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 interface for objects executing custom turtle commands, used with ITurtleAccess.issueCommand
|
||||
* @see ITurtleAccess#executeCommand(dan200.computercraft.api.lua.ILuaContext,ITurtleCommand)
|
||||
*/
|
||||
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 TurtleCommandResult.success() or TurtleCommandResult.failure( errorMessage )
|
||||
* @see ITurtleAccess#executeCommand(dan200.computercraft.api.lua.ILuaContext,ITurtleCommand)
|
||||
* @see dan200.computercraft.api.turtle.TurtleCommandResult
|
||||
*/
|
||||
public TurtleCommandResult execute( ITurtleAccess turtle );
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.peripheral.IPeripheral;
|
||||
import net.minecraft.client.resources.model.IBakedModel;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.fml.relauncher.Side;
|
||||
import net.minecraftforge.fml.relauncher.SideOnly;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import javax.vecmath.Matrix4f;
|
||||
|
||||
|
||||
/**
|
||||
* The primary interface for defining an update for Turtles. A turtle update
|
||||
* can either be a new tool, or a new peripheral.
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#registerTurtleUpgrade( dan200.computercraft.api.turtle.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.
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#registerTurtleUpgrade( dan200.computercraft.api.turtle.ITurtleUpgrade )
|
||||
*/
|
||||
public ResourceLocation getUpgradeID();
|
||||
|
||||
/**
|
||||
* Gets a numerical identifier representing this type of turtle upgrade,
|
||||
* for backwards compatibility with pre-1.76 worlds. If your upgrade was
|
||||
* not released for older ComputerCraft versions, you can return -1 here.
|
||||
* The turtle will fail registration if an already used positive ID is specified.
|
||||
* @see dan200.computercraft.api.ComputerCraftAPI#registerTurtleUpgrade( dan200.computercraft.api.turtle.ITurtleUpgrade )
|
||||
*/
|
||||
public int getLegacyUpgradeID();
|
||||
|
||||
/**
|
||||
* Return a String to describe this type of turtle in turtle item names.
|
||||
* Examples of built-in adjectives are "Wireless", "Mining" and "Crafty".
|
||||
*/
|
||||
public String getUnlocalisedAdjective();
|
||||
|
||||
/**
|
||||
* Return whether this turtle adds a tool or a peripheral to the turtle.
|
||||
* @see TurtleUpgradeType for the differences between the two.
|
||||
*/
|
||||
public 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 turtle.equip()
|
||||
*/
|
||||
public 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, will have update() called once-per-tick, and 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 null if this upgrade is a Tool
|
||||
* and this method is not expected to be called.
|
||||
*/
|
||||
public IPeripheral createPeripheral( ITurtleAccess turtle, TurtleSide side );
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @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 turtle.dig()
|
||||
* or turtle.attack() lua method should return true. If true is returned, the tool will perform
|
||||
* a swinging animation. You may return null if this turtle is a Peripheral
|
||||
* and this method is not expected to be called.
|
||||
*/
|
||||
public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, TurtleVerb verb, EnumFacing direction );
|
||||
|
||||
/**
|
||||
* Called to obtain the model to be used when rendering a turtle peripheral.
|
||||
* @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, and a transformation to apply to it. Returning a transformation of null has the same effect as the identify matrix.
|
||||
*/
|
||||
@SideOnly( Side.CLIENT )
|
||||
public Pair<IBakedModel, Matrix4f> getModel( ITurtleAccess turtle, 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.
|
||||
*/
|
||||
public void update( ITurtleAccess turtle, TurtleSide side );
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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;
|
||||
|
||||
public enum TurtleAnimation
|
||||
{
|
||||
None,
|
||||
MoveForward,
|
||||
MoveBack,
|
||||
MoveUp,
|
||||
MoveDown,
|
||||
TurnLeft,
|
||||
TurnRight,
|
||||
SwingLeftTool,
|
||||
SwingRightTool,
|
||||
Wait,
|
||||
ShortWait,
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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;
|
||||
|
||||
public final class TurtleCommandResult
|
||||
{
|
||||
private static final TurtleCommandResult s_success = new TurtleCommandResult( true, null, null );
|
||||
private static final TurtleCommandResult s_emptyFailure = new TurtleCommandResult( false, null, null );
|
||||
|
||||
public static TurtleCommandResult success()
|
||||
{
|
||||
return success( null );
|
||||
}
|
||||
|
||||
public static TurtleCommandResult success( Object[] results )
|
||||
{
|
||||
if( results == null || results.length == 0 )
|
||||
{
|
||||
return s_success;
|
||||
}
|
||||
else
|
||||
{
|
||||
return new TurtleCommandResult( true, null, results );
|
||||
}
|
||||
}
|
||||
|
||||
public static TurtleCommandResult failure()
|
||||
{
|
||||
return failure( null );
|
||||
}
|
||||
|
||||
public static TurtleCommandResult failure( String errorMessage )
|
||||
{
|
||||
if( errorMessage == null )
|
||||
{
|
||||
return s_emptyFailure;
|
||||
}
|
||||
else
|
||||
{
|
||||
return new TurtleCommandResult( false, errorMessage, null );
|
||||
}
|
||||
}
|
||||
|
||||
private final boolean m_success;
|
||||
private final String m_errorMessage;
|
||||
private final Object[] m_results;
|
||||
|
||||
private TurtleCommandResult( boolean success, String errorMessage, Object[] results )
|
||||
{
|
||||
m_success = success;
|
||||
m_errorMessage = errorMessage;
|
||||
m_results = results;
|
||||
}
|
||||
|
||||
public boolean isSuccess()
|
||||
{
|
||||
return m_success;
|
||||
}
|
||||
|
||||
public String getErrorMessage()
|
||||
{
|
||||
return m_errorMessage;
|
||||
}
|
||||
|
||||
public Object[] getResults()
|
||||
{
|
||||
return m_results;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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 turtles left side (where the pickaxe usually is on a Wireless Mining Turtle)
|
||||
*/
|
||||
Left,
|
||||
|
||||
/**
|
||||
* The turtles right side (where the modem usually is on a Wireless Mining Turtle)
|
||||
*/
|
||||
Right,
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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 different types of turtle that an ITurtleUpgrade
|
||||
* implementation can add to a turtle.
|
||||
* @see ITurtleUpgrade
|
||||
*/
|
||||
public enum TurtleUpgradeType
|
||||
{
|
||||
/**
|
||||
* A tool is rendered as an item on the side of the turtle, and responds to the turtle.dig()
|
||||
* and 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 peripheral API (Such as the modem on Wireless Turtles).
|
||||
*/
|
||||
Peripheral,
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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 different actions that an ITurtleUpgrade of type
|
||||
* Tool may be called on to perform by a turtle.
|
||||
* @see ITurtleUpgrade
|
||||
* @see ITurtleUpgrade#useTool
|
||||
*/
|
||||
public enum TurtleVerb
|
||||
{
|
||||
/**
|
||||
* The turtle called turtle.dig(), turtle.digUp() or turtle.digDown()
|
||||
*/
|
||||
Dig,
|
||||
|
||||
/**
|
||||
* The turtle called turtle.attack(), turtle.attackUp() or turtle.attackDown()
|
||||
*/
|
||||
Attack,
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.
|
||||
*/
|
||||
|
||||
@API( owner="ComputerCraft", provides="ComputerCraft|API|Turtle", apiVersion="${version}" )
|
||||
package dan200.computercraft.api.turtle;
|
||||
|
||||
import net.minecraftforge.fml.common.API;
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.gui;
|
||||
|
||||
import dan200.computercraft.core.terminal.TextBuffer;
|
||||
import dan200.computercraft.shared.util.Colour;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.renderer.WorldRenderer;
|
||||
import net.minecraft.client.renderer.texture.TextureManager;
|
||||
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
public class FixedWidthFontRenderer
|
||||
{
|
||||
public static ResourceLocation font = new ResourceLocation( "computercraft", "textures/gui/termFont.png" );
|
||||
public static ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/termBackground.png" );
|
||||
|
||||
public static int FONT_HEIGHT = 9;
|
||||
public static int FONT_WIDTH = 6;
|
||||
|
||||
private TextureManager m_textureManager;
|
||||
|
||||
public FixedWidthFontRenderer( TextureManager textureManager )
|
||||
{
|
||||
m_textureManager = textureManager;
|
||||
}
|
||||
|
||||
private void drawChar( WorldRenderer renderer, double x, double y, int index, int color )
|
||||
{
|
||||
int column = index % 16;
|
||||
int row = index / 16;
|
||||
Colour colour = Colour.values()[ 15 - color ];
|
||||
renderer.pos( x, y + FONT_HEIGHT, 0.0 ).tex( (double) (column * FONT_WIDTH) / 256.0, (double) ((row + 1) * FONT_HEIGHT) / 256.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( x + FONT_WIDTH, y + FONT_HEIGHT, 0.0 ).tex( (double) ((column + 1) * FONT_WIDTH) / 256.0, (double) ((row + 1) * FONT_HEIGHT) / 256.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( x + FONT_WIDTH, y, 0.0 ).tex( (double) ((column + 1) * FONT_WIDTH) / 256.0, (double) (row * FONT_HEIGHT) / 256.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( x, y, 0.0 ).tex( (double) (column * FONT_WIDTH) / 256.0, (double) (row * FONT_HEIGHT ) / 256.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
}
|
||||
|
||||
private void drawQuad( WorldRenderer renderer, double x, double y, int color, double width )
|
||||
{
|
||||
Colour colour = Colour.values()[ 15 - color ];
|
||||
renderer.pos( x, y + FONT_HEIGHT, 0.0 ).tex( 0.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( x + width, y + FONT_HEIGHT, 0.0 ).tex( 1.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( x + width, y, 0.0 ).tex( 1.0, 0.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( x, y, 0.0 ).tex( 0.0, 0.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
}
|
||||
|
||||
private boolean isGreyScale( int colour )
|
||||
{
|
||||
return (colour == 0 || colour == 15 || colour == 7 || colour == 8);
|
||||
}
|
||||
|
||||
public void drawStringBackgroundPart( int x, int y, TextBuffer backgroundColour, double leftMarginSize, double rightMarginSize, boolean greyScale )
|
||||
{
|
||||
// Draw the quads
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
WorldRenderer renderer = tessellator.getWorldRenderer();
|
||||
renderer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR );
|
||||
if( leftMarginSize > 0.0 )
|
||||
{
|
||||
int colour1 = "0123456789abcdef".indexOf( backgroundColour.charAt( 0 ) );
|
||||
if( colour1 < 0 || (greyScale && !isGreyScale(colour1)) )
|
||||
{
|
||||
colour1 = 15;
|
||||
}
|
||||
drawQuad( renderer, x - leftMarginSize, y, colour1, leftMarginSize );
|
||||
}
|
||||
if( rightMarginSize > 0.0 )
|
||||
{
|
||||
int colour2 = "0123456789abcdef".indexOf( backgroundColour.charAt( backgroundColour.length() - 1 ) );
|
||||
if( colour2 < 0 || (greyScale && !isGreyScale(colour2)) )
|
||||
{
|
||||
colour2 = 15;
|
||||
}
|
||||
drawQuad( renderer, x + backgroundColour.length() * FONT_WIDTH, y, colour2, rightMarginSize );
|
||||
}
|
||||
for( int i = 0; i < backgroundColour.length(); i++ )
|
||||
{
|
||||
int colour = "0123456789abcdef".indexOf( backgroundColour.charAt( i ) );
|
||||
if( colour < 0 || ( greyScale && !isGreyScale( colour ) ) )
|
||||
{
|
||||
colour = 15;
|
||||
}
|
||||
drawQuad( renderer, x + i * FONT_WIDTH, y, colour, FONT_WIDTH );
|
||||
}
|
||||
tessellator.draw();
|
||||
}
|
||||
|
||||
public void drawStringTextPart( int x, int y, TextBuffer s, TextBuffer textColour, boolean greyScale )
|
||||
{
|
||||
// Draw the quads
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
WorldRenderer renderer = tessellator.getWorldRenderer();
|
||||
renderer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR );
|
||||
for( int i = 0; i < s.length(); i++ )
|
||||
{
|
||||
// Switch colour
|
||||
int colour = "0123456789abcdef".indexOf( textColour.charAt( i ) );
|
||||
if( colour < 0 || ( greyScale && !isGreyScale( colour ) ) )
|
||||
{
|
||||
colour = 0;
|
||||
}
|
||||
|
||||
// Draw char
|
||||
int index = (int)s.charAt( i );
|
||||
if( index < 0 || index > 255 )
|
||||
{
|
||||
index = (int)'?';
|
||||
}
|
||||
drawChar( renderer, x + i * FONT_WIDTH, y, index, colour );
|
||||
}
|
||||
tessellator.draw();
|
||||
}
|
||||
|
||||
public void drawString( TextBuffer s, int x, int y, TextBuffer textColour, TextBuffer backgroundColour, double leftMarginSize, double rightMarginSize, boolean greyScale )
|
||||
{
|
||||
// Draw background
|
||||
if( backgroundColour != null )
|
||||
{
|
||||
// Bind the background texture
|
||||
m_textureManager.bindTexture( background );
|
||||
|
||||
// Draw the quads
|
||||
drawStringBackgroundPart( x, y, backgroundColour, leftMarginSize, rightMarginSize, greyScale );
|
||||
}
|
||||
|
||||
// Draw text
|
||||
if( s != null && textColour != null )
|
||||
{
|
||||
// Bind the font texture
|
||||
m_textureManager.bindTexture( font );
|
||||
|
||||
// Draw the quads
|
||||
drawStringTextPart( x, y, s, textColour, greyScale );
|
||||
}
|
||||
}
|
||||
|
||||
public int getStringWidth(String s)
|
||||
{
|
||||
if(s == null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return s.length() * FONT_WIDTH;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.gui;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.client.gui.widgets.WidgetTerminal;
|
||||
import dan200.computercraft.shared.computer.blocks.TileComputer;
|
||||
import dan200.computercraft.shared.computer.core.ComputerFamily;
|
||||
import dan200.computercraft.shared.computer.core.IComputer;
|
||||
import dan200.computercraft.shared.computer.core.IComputerContainer;
|
||||
import dan200.computercraft.shared.computer.inventory.ContainerComputer;
|
||||
import net.minecraft.client.gui.inventory.GuiContainer;
|
||||
import net.minecraft.client.renderer.GlStateManager;
|
||||
import net.minecraft.inventory.Container;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.lwjgl.input.Keyboard;
|
||||
import org.lwjgl.input.Mouse;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class GuiComputer extends GuiContainer
|
||||
{
|
||||
private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/corners.png" );
|
||||
private static final ResourceLocation backgroundAdvanced = new ResourceLocation( "computercraft", "textures/gui/corners2.png" );
|
||||
private static final ResourceLocation backgroundCommand = new ResourceLocation( "computercraft", "textures/gui/cornersCommand.png" );
|
||||
|
||||
private final ComputerFamily m_family;
|
||||
private final IComputer m_computer;
|
||||
private final int m_termWidth;
|
||||
private final int m_termHeight;
|
||||
private WidgetTerminal m_terminal;
|
||||
|
||||
protected GuiComputer( Container container, ComputerFamily family, IComputer computer, int termWidth, int termHeight )
|
||||
{
|
||||
super( container );
|
||||
m_family = family;
|
||||
m_computer = computer;
|
||||
m_termWidth = termWidth;
|
||||
m_termHeight = termHeight;
|
||||
m_terminal = null;
|
||||
}
|
||||
|
||||
public GuiComputer( TileComputer computer )
|
||||
{
|
||||
this(
|
||||
new ContainerComputer( computer ),
|
||||
computer.getFamily(),
|
||||
computer.createComputer(),
|
||||
ComputerCraft.terminalWidth_computer,
|
||||
ComputerCraft.terminalHeight_computer
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initGui()
|
||||
{
|
||||
super.initGui();
|
||||
Keyboard.enableRepeatEvents( true );
|
||||
|
||||
m_terminal = new WidgetTerminal( 0, 0, m_termWidth, m_termHeight, new IComputerContainer()
|
||||
{
|
||||
@Override
|
||||
public IComputer getComputer()
|
||||
{
|
||||
return m_computer;
|
||||
}
|
||||
}, 2, 2, 2, 2 );
|
||||
m_terminal.setAllowFocusLoss( false );
|
||||
xSize = m_terminal.getWidth() + 24;
|
||||
ySize = m_terminal.getHeight() + 24;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGuiClosed()
|
||||
{
|
||||
super.onGuiClosed();
|
||||
Keyboard.enableRepeatEvents( false );
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doesGuiPauseGame()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateScreen()
|
||||
{
|
||||
super.updateScreen();
|
||||
m_terminal.update();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void keyTyped(char c, int k) throws IOException
|
||||
{
|
||||
if( k == 1 )
|
||||
{
|
||||
super.keyTyped( c, k );
|
||||
}
|
||||
else
|
||||
{
|
||||
m_terminal.keyTyped( c, k );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void mouseClicked( int x, int y, int button )
|
||||
{
|
||||
int startX = (width - m_terminal.getWidth()) / 2;
|
||||
int startY = (height - m_terminal.getHeight()) / 2;
|
||||
m_terminal.mouseClicked( x - startX, y - startY, button );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMouseInput() throws IOException
|
||||
{
|
||||
super.handleMouseInput();
|
||||
|
||||
int x = Mouse.getEventX() * width / mc.displayWidth;
|
||||
int y = height - Mouse.getEventY() * height / mc.displayHeight - 1;
|
||||
int startX = (width - m_terminal.getWidth()) / 2;
|
||||
int startY = (height - m_terminal.getHeight()) / 2;
|
||||
m_terminal.handleMouseInput( x - startX, y - startY );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleKeyboardInput() throws IOException
|
||||
{
|
||||
super.handleKeyboardInput();
|
||||
m_terminal.handleKeyboardInput();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawGuiContainerForegroundLayer(int par1, int par2)
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawGuiContainerBackgroundLayer( float var1, int var2, int var3 )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawScreen( int mouseX, int mouseY, float f )
|
||||
{
|
||||
// Work out where to draw
|
||||
int startX = (width - m_terminal.getWidth()) / 2;
|
||||
int startY = (height - m_terminal.getHeight()) / 2;
|
||||
int endX = startX + m_terminal.getWidth();
|
||||
int endY = startY + m_terminal.getHeight();
|
||||
|
||||
// Draw background
|
||||
drawDefaultBackground();
|
||||
|
||||
// Draw terminal
|
||||
m_terminal.draw( this.mc, startX, startY, mouseX, mouseY );
|
||||
|
||||
// Draw a border around the terminal
|
||||
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
|
||||
switch( m_family )
|
||||
{
|
||||
case Normal:
|
||||
default:
|
||||
{
|
||||
this.mc.getTextureManager().bindTexture( background );
|
||||
break;
|
||||
}
|
||||
case Advanced:
|
||||
{
|
||||
this.mc.getTextureManager().bindTexture( backgroundAdvanced );
|
||||
break;
|
||||
}
|
||||
case Command:
|
||||
{
|
||||
this.mc.getTextureManager().bindTexture( backgroundCommand );
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
drawTexturedModalRect(startX - 12, startY - 12, 12, 28, 12, 12);
|
||||
drawTexturedModalRect(startX - 12, endY, 12, 40, 12, 16);
|
||||
drawTexturedModalRect(endX, startY - 12, 24, 28, 12, 12);
|
||||
drawTexturedModalRect(endX, endY, 24, 40, 12, 16);
|
||||
|
||||
drawTexturedModalRect(startX, startY-12, 0, 0, endX - startX, 12);
|
||||
drawTexturedModalRect(startX, endY, 0, 12, endX - startX, 16);
|
||||
|
||||
drawTexturedModalRect(startX-12, startY, 0, 28, 12, endY - startY);
|
||||
drawTexturedModalRect(endX, startY, 36, 28, 12, endY - startY);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.gui;
|
||||
|
||||
import dan200.computercraft.shared.peripheral.diskdrive.ContainerDiskDrive;
|
||||
import dan200.computercraft.shared.peripheral.diskdrive.TileDiskDrive;
|
||||
import net.minecraft.client.gui.inventory.GuiContainer;
|
||||
import net.minecraft.client.renderer.GlStateManager;
|
||||
import net.minecraft.client.resources.I18n;
|
||||
import net.minecraft.entity.player.InventoryPlayer;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
|
||||
public class GuiDiskDrive extends GuiContainer
|
||||
{
|
||||
private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/diskdrive.png" );
|
||||
|
||||
private TileDiskDrive m_diskDrive;
|
||||
|
||||
public GuiDiskDrive( InventoryPlayer inventoryplayer, TileDiskDrive diskDrive )
|
||||
{
|
||||
super( new ContainerDiskDrive(inventoryplayer, diskDrive) );
|
||||
m_diskDrive = diskDrive;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawGuiContainerForegroundLayer(int par1, int par2)
|
||||
{
|
||||
String title = m_diskDrive.getDisplayName().getUnformattedText();
|
||||
fontRendererObj.drawString( title, (xSize - fontRendererObj.getStringWidth(title)) / 2, 6, 0x404040 );
|
||||
fontRendererObj.drawString( I18n.format("container.inventory"), 8, (ySize - 96) + 2, 0x404040 );
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawGuiContainerBackgroundLayer(float f, int i, int j)
|
||||
{
|
||||
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
|
||||
this.mc.getTextureManager().bindTexture( background );
|
||||
int l = (width - xSize) / 2;
|
||||
int i1 = (height - ySize) / 2;
|
||||
drawTexturedModalRect(l, i1, 0, 0, xSize, ySize);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.gui;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.shared.media.inventory.ContainerHeldItem;
|
||||
|
||||
public class GuiPocketComputer extends GuiComputer
|
||||
{
|
||||
public GuiPocketComputer( ContainerHeldItem container )
|
||||
{
|
||||
super(
|
||||
container,
|
||||
ComputerCraft.Items.pocketComputer.getFamily( container.getStack() ),
|
||||
ComputerCraft.Items.pocketComputer.createClientComputer( container.getStack() ),
|
||||
ComputerCraft.terminalWidth_pocketComputer,
|
||||
ComputerCraft.terminalHeight_pocketComputer
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.gui;
|
||||
|
||||
import dan200.computercraft.shared.peripheral.printer.ContainerPrinter;
|
||||
import dan200.computercraft.shared.peripheral.printer.TilePrinter;
|
||||
import net.minecraft.client.gui.inventory.GuiContainer;
|
||||
import net.minecraft.client.renderer.GlStateManager;
|
||||
import net.minecraft.client.resources.I18n;
|
||||
import net.minecraft.entity.player.InventoryPlayer;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
|
||||
public class GuiPrinter extends GuiContainer
|
||||
{
|
||||
private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/printer.png" );
|
||||
|
||||
private TilePrinter m_printer;
|
||||
private ContainerPrinter m_container;
|
||||
|
||||
public GuiPrinter(InventoryPlayer inventoryplayer, TilePrinter printer)
|
||||
{
|
||||
super(new ContainerPrinter(inventoryplayer, printer));
|
||||
m_printer = printer;
|
||||
m_container = (ContainerPrinter)inventorySlots;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawGuiContainerForegroundLayer(int par1, int par2)
|
||||
{
|
||||
String title = m_printer.getDisplayName().getUnformattedText();
|
||||
fontRendererObj.drawString( title, (xSize - fontRendererObj.getStringWidth(title)) / 2, 6, 0x404040 );
|
||||
fontRendererObj.drawString( I18n.format("container.inventory"), 8, (ySize - 96) + 2, 0x404040 );
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawGuiContainerBackgroundLayer(float f, int i, int j)
|
||||
{
|
||||
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
|
||||
this.mc.getTextureManager().bindTexture( background );
|
||||
int startX = (width - xSize) / 2;
|
||||
int startY = (height - ySize) / 2;
|
||||
drawTexturedModalRect(startX, startY, 0, 0, xSize, ySize);
|
||||
|
||||
boolean printing = m_container.isPrinting();
|
||||
if( printing )
|
||||
{
|
||||
drawTexturedModalRect(startX + 34, startY + 21, 176, 0, 25, 45);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.gui;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.core.terminal.TextBuffer;
|
||||
import dan200.computercraft.shared.media.inventory.ContainerHeldItem;
|
||||
import dan200.computercraft.shared.media.items.ItemPrintout;
|
||||
import net.minecraft.client.gui.inventory.GuiContainer;
|
||||
import net.minecraft.client.renderer.GlStateManager;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.lwjgl.input.Mouse;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class GuiPrintout extends GuiContainer
|
||||
{
|
||||
private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/printout.png" );
|
||||
|
||||
private static final int xSize = 172;
|
||||
private static final int ySize = 209;
|
||||
|
||||
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 )
|
||||
{
|
||||
super( container );
|
||||
m_book = (ItemPrintout.getType( container.getStack() ) == ItemPrintout.Type.Book);
|
||||
|
||||
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_pages = Math.max( m_text.length / ItemPrintout.LINES_PER_PAGE, 1 );
|
||||
m_page = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initGui()
|
||||
{
|
||||
super.initGui();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGuiClosed()
|
||||
{
|
||||
super.onGuiClosed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doesGuiPauseGame()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateScreen()
|
||||
{
|
||||
super.updateScreen();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void keyTyped(char c, int k) throws IOException
|
||||
{
|
||||
super.keyTyped( c, k );
|
||||
|
||||
if( k == 205 )
|
||||
{
|
||||
// Right
|
||||
if( m_page < m_pages - 1 )
|
||||
{
|
||||
m_page = m_page + 1;
|
||||
}
|
||||
}
|
||||
else if( k == 203 )
|
||||
{
|
||||
// Left
|
||||
if( m_page > 0 )
|
||||
{
|
||||
m_page = m_page - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMouseInput() throws IOException
|
||||
{
|
||||
super.handleMouseInput();
|
||||
|
||||
int mouseWheelChange = Mouse.getEventDWheel();
|
||||
if (mouseWheelChange < 0)
|
||||
{
|
||||
// Up
|
||||
if( m_page < m_pages - 1 )
|
||||
{
|
||||
m_page = m_page + 1;
|
||||
}
|
||||
}
|
||||
else if (mouseWheelChange > 0)
|
||||
{
|
||||
// Down
|
||||
if( m_page > 0 )
|
||||
{
|
||||
m_page = m_page - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawGuiContainerForegroundLayer( int par1, int par2 )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawGuiContainerBackgroundLayer( float var1, int var2, int var3 )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawScreen(int mouseX, int mouseY, float f)
|
||||
{
|
||||
// Draw background
|
||||
drawDefaultBackground();
|
||||
|
||||
// Draw the printout
|
||||
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
|
||||
this.mc.getTextureManager().bindTexture( background );
|
||||
|
||||
int startY = (height - ySize) / 2;
|
||||
//int startX = (width - xSize) / 2 - (m_page * 8);
|
||||
int startX = (width - (xSize + (m_pages - 1)*8)) / 2;
|
||||
|
||||
if( m_book )
|
||||
{
|
||||
// Border
|
||||
drawTexturedModalRect( startX - 8, startY - 8, xSize + 48, 0, 12, ySize + 24);
|
||||
drawTexturedModalRect( startX + xSize + (m_pages - 1)*8 - 4, startY - 8, xSize + 48 + 12, 0, 12, ySize + 24);
|
||||
|
||||
drawTexturedModalRect( startX, startY - 8, 0, ySize, xSize, 12);
|
||||
drawTexturedModalRect( startX, startY + ySize - 4, 0, ySize + 12, xSize, 12);
|
||||
for( int n=1; n<m_pages; ++n )
|
||||
{
|
||||
drawTexturedModalRect( startX + xSize + (n-1)*8, startY - 8, 0, ySize, 8, 12);
|
||||
drawTexturedModalRect( startX + xSize + (n-1)*8, startY + ySize - 4, 0, ySize + 12, 8, 12);
|
||||
}
|
||||
}
|
||||
|
||||
// Left half
|
||||
if( m_page == 0 )
|
||||
{
|
||||
drawTexturedModalRect( startX, startY, 24, 0, xSize / 2, ySize);
|
||||
drawTexturedModalRect( startX, startY, 0, 0, 12, ySize);
|
||||
}
|
||||
else
|
||||
{
|
||||
drawTexturedModalRect( startX, startY, 0, 0, 12, ySize);
|
||||
for( int n=1; n<m_page; ++n )
|
||||
{
|
||||
drawTexturedModalRect( startX + n*8, startY, 12, 0, 12, ySize);
|
||||
}
|
||||
drawTexturedModalRect( startX + m_page*8, startY, 24, 0, xSize / 2, ySize);
|
||||
}
|
||||
|
||||
// Right half
|
||||
if( m_page == (m_pages - 1) )
|
||||
{
|
||||
drawTexturedModalRect( startX + m_page*8 + xSize/2, startY, 24 + xSize / 2, 0, xSize / 2, ySize);
|
||||
drawTexturedModalRect( startX + m_page*8 + (xSize - 12), startY, 24 + xSize + 12, 0, 12, ySize);
|
||||
}
|
||||
else
|
||||
{
|
||||
drawTexturedModalRect( startX + (m_pages - 1)*8 + (xSize - 12), startY, 24 + xSize + 12, 0, 12, ySize);
|
||||
for( int n=m_pages-2; n>=m_page; --n )
|
||||
{
|
||||
drawTexturedModalRect( startX + n*8 + (xSize - 12), startY, 24 + xSize, 0, 12, ySize);
|
||||
}
|
||||
drawTexturedModalRect( startX + m_page*8 + xSize/2, startY, 24 + xSize / 2, 0, xSize / 2, ySize);
|
||||
}
|
||||
|
||||
// Draw the text
|
||||
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer)ComputerCraft.getFixedWidthFontRenderer();
|
||||
int x = startX + m_page * 8 + 13;
|
||||
int y = startY + 11;
|
||||
for( int line=0; line<ItemPrintout.LINES_PER_PAGE; ++line )
|
||||
{
|
||||
int lineIdx = ItemPrintout.LINES_PER_PAGE * m_page + line;
|
||||
if( lineIdx >= 0 && lineIdx < m_text.length )
|
||||
{
|
||||
fontRenderer.drawString( m_text[lineIdx], x, y, m_colours[lineIdx], null, 0, 0, false );
|
||||
}
|
||||
y = y + FixedWidthFontRenderer.FONT_HEIGHT;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.gui;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.api.turtle.ITurtleAccess;
|
||||
import dan200.computercraft.client.gui.widgets.WidgetTerminal;
|
||||
import dan200.computercraft.shared.computer.core.ComputerFamily;
|
||||
import dan200.computercraft.shared.computer.core.IComputer;
|
||||
import dan200.computercraft.shared.computer.core.IComputerContainer;
|
||||
import dan200.computercraft.shared.turtle.blocks.TileTurtle;
|
||||
import dan200.computercraft.shared.turtle.inventory.ContainerTurtle;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.inventory.GuiContainer;
|
||||
import net.minecraft.client.renderer.GlStateManager;
|
||||
import net.minecraft.entity.player.InventoryPlayer;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraft.world.World;
|
||||
import org.lwjgl.input.Keyboard;
|
||||
import org.lwjgl.input.Mouse;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class GuiTurtle extends GuiContainer
|
||||
{
|
||||
private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/turtle.png" );
|
||||
private static final ResourceLocation backgroundAdvanced = new ResourceLocation( "computercraft", "textures/gui/turtle2.png" );
|
||||
|
||||
protected World m_world;
|
||||
protected ContainerTurtle m_container;
|
||||
|
||||
protected final ComputerFamily m_family;
|
||||
protected final ITurtleAccess m_turtle;
|
||||
protected final IComputer m_computer;
|
||||
protected WidgetTerminal m_terminalGui;
|
||||
|
||||
public GuiTurtle( World world, InventoryPlayer inventoryplayer, TileTurtle turtle )
|
||||
{
|
||||
this( world, turtle, new ContainerTurtle( inventoryplayer, turtle.getAccess() ) );
|
||||
}
|
||||
|
||||
protected GuiTurtle( World world, TileTurtle turtle, ContainerTurtle container )
|
||||
{
|
||||
super( container );
|
||||
|
||||
m_world = world;
|
||||
m_container = container;
|
||||
m_family = turtle.getFamily();
|
||||
m_turtle = turtle.getAccess();
|
||||
m_computer = turtle.createComputer();
|
||||
|
||||
xSize = 254;
|
||||
ySize = 217;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initGui()
|
||||
{
|
||||
super.initGui();
|
||||
Keyboard.enableRepeatEvents(true);
|
||||
m_terminalGui = new WidgetTerminal(
|
||||
( width - xSize ) / 2 + 8,
|
||||
( height - ySize ) / 2 + 8,
|
||||
ComputerCraft.terminalWidth_turtle,
|
||||
ComputerCraft.terminalHeight_turtle,
|
||||
new IComputerContainer()
|
||||
{
|
||||
@Override
|
||||
public IComputer getComputer()
|
||||
{
|
||||
return m_computer;
|
||||
}
|
||||
},
|
||||
2, 2, 2, 2
|
||||
);
|
||||
m_terminalGui.setAllowFocusLoss( false );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGuiClosed()
|
||||
{
|
||||
super.onGuiClosed();
|
||||
Keyboard.enableRepeatEvents(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateScreen()
|
||||
{
|
||||
super.updateScreen();
|
||||
m_terminalGui.update();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void keyTyped(char c, int k) throws IOException
|
||||
{
|
||||
if( k == 1 )
|
||||
{
|
||||
super.keyTyped( c, k );
|
||||
}
|
||||
else
|
||||
{
|
||||
m_terminalGui.keyTyped( c, k );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void mouseClicked(int x, int y, int button) throws IOException
|
||||
{
|
||||
super.mouseClicked( x, y, button );
|
||||
m_terminalGui.mouseClicked( x, y, button );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMouseInput() throws IOException
|
||||
{
|
||||
super.handleMouseInput();
|
||||
int x = Mouse.getEventX() * this.width / mc.displayWidth;
|
||||
int y = this.height - Mouse.getEventY() * this.height / mc.displayHeight - 1;
|
||||
m_terminalGui.handleMouseInput( x, y );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleKeyboardInput() throws IOException
|
||||
{
|
||||
super.handleKeyboardInput();
|
||||
m_terminalGui.handleKeyboardInput();
|
||||
}
|
||||
|
||||
protected void drawSelectionSlot( boolean advanced )
|
||||
{
|
||||
int x = (width - xSize) / 2;
|
||||
int y = (height - ySize) / 2;
|
||||
|
||||
// Draw selection slot
|
||||
int slot = m_container.getSelectedSlot();
|
||||
if( slot >= 0 )
|
||||
{
|
||||
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
|
||||
int slotX = (slot%4);
|
||||
int slotY = (slot/4);
|
||||
this.mc.getTextureManager().bindTexture( advanced ? backgroundAdvanced : background );
|
||||
drawTexturedModalRect(x + m_container.m_turtleInvStartX - 2 + slotX * 18, y + m_container.m_playerInvStartY - 2 + slotY * 18, 0, 217, 24, 24);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawGuiContainerBackgroundLayer( float f, int mouseX, int mouseY )
|
||||
{
|
||||
// Draw term
|
||||
boolean advanced = (m_family == ComputerFamily.Advanced);
|
||||
m_terminalGui.draw( Minecraft.getMinecraft(), 0, 0, mouseX, mouseY );
|
||||
|
||||
// Draw border/inventory
|
||||
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
|
||||
this.mc.getTextureManager().bindTexture( advanced ? backgroundAdvanced : background );
|
||||
int x = (width - xSize) / 2;
|
||||
int y = (height - ySize) / 2;
|
||||
drawTexturedModalRect(x, y, 0, 0, xSize, ySize);
|
||||
|
||||
drawSelectionSlot( advanced );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.gui.widgets;
|
||||
|
||||
public class MousePos
|
||||
{
|
||||
public int x;
|
||||
public int y;
|
||||
|
||||
public MousePos( int x, int y )
|
||||
{
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.gui.widgets;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.audio.PositionedSoundRecord;
|
||||
import net.minecraft.client.gui.FontRenderer;
|
||||
import net.minecraft.client.gui.Gui;
|
||||
import net.minecraft.client.renderer.GlStateManager;
|
||||
import net.minecraft.client.renderer.OpenGlHelper;
|
||||
import net.minecraft.client.renderer.RenderHelper;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.renderer.entity.RenderItem;
|
||||
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
import org.lwjgl.opengl.GL12;
|
||||
|
||||
public abstract class Widget extends Gui
|
||||
{
|
||||
private WidgetContainer m_parent;
|
||||
private boolean m_visible;
|
||||
private int m_xPosition;
|
||||
private int m_yPosition;
|
||||
private int m_width;
|
||||
private int m_height;
|
||||
|
||||
protected Widget( int x, int y, int width, int height )
|
||||
{
|
||||
m_parent = null;
|
||||
m_visible = true;
|
||||
m_xPosition = x;
|
||||
m_yPosition = y;
|
||||
m_width = width;
|
||||
m_height = height;
|
||||
}
|
||||
|
||||
public WidgetContainer getRoot()
|
||||
{
|
||||
if( m_parent != null )
|
||||
{
|
||||
return m_parent.getRoot();
|
||||
}
|
||||
else if( this instanceof WidgetContainer )
|
||||
{
|
||||
return (WidgetContainer)this;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public WidgetContainer getParent()
|
||||
{
|
||||
return m_parent;
|
||||
}
|
||||
|
||||
public void setParent( WidgetContainer parent )
|
||||
{
|
||||
m_parent = parent;
|
||||
}
|
||||
|
||||
public boolean isObscured()
|
||||
{
|
||||
if( m_parent != null )
|
||||
{
|
||||
Widget parentModalWidget = m_parent.getModalWidget();
|
||||
if( parentModalWidget == null )
|
||||
{
|
||||
return m_parent.isObscured();
|
||||
}
|
||||
else
|
||||
{
|
||||
return (parentModalWidget != this);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isVisible()
|
||||
{
|
||||
return m_visible && (m_parent == null || m_parent.isVisible());
|
||||
}
|
||||
|
||||
public void setVisible( boolean visible )
|
||||
{
|
||||
m_visible = visible;
|
||||
}
|
||||
|
||||
public int getXPosition()
|
||||
{
|
||||
return m_xPosition;
|
||||
}
|
||||
|
||||
public int getYPosition()
|
||||
{
|
||||
return m_yPosition;
|
||||
}
|
||||
|
||||
public int getAbsoluteXPosition()
|
||||
{
|
||||
return m_xPosition + (m_parent != null ? m_parent.getAbsoluteXPosition() : 0);
|
||||
}
|
||||
|
||||
public int getAbsoluteYPosition()
|
||||
{
|
||||
return m_yPosition + (m_parent != null ? m_parent.getAbsoluteYPosition() : 0);
|
||||
}
|
||||
|
||||
public int getWidth()
|
||||
{
|
||||
return m_width;
|
||||
}
|
||||
|
||||
public int getHeight()
|
||||
{
|
||||
return m_height;
|
||||
}
|
||||
|
||||
public void setPosition( int x, int y )
|
||||
{
|
||||
m_xPosition = x;
|
||||
m_yPosition = y;
|
||||
}
|
||||
|
||||
public void resize( int width, int height )
|
||||
{
|
||||
m_width = width;
|
||||
m_height = height;
|
||||
}
|
||||
|
||||
public void update()
|
||||
{
|
||||
}
|
||||
|
||||
public void draw( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY )
|
||||
{
|
||||
}
|
||||
|
||||
public void drawForeground( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY )
|
||||
{
|
||||
}
|
||||
|
||||
public void modifyMousePosition( MousePos pos )
|
||||
{
|
||||
}
|
||||
|
||||
public void handleMouseInput( int mouseX, int mouseY )
|
||||
{
|
||||
}
|
||||
|
||||
public void handleKeyboardInput()
|
||||
{
|
||||
}
|
||||
|
||||
public void mouseClicked( int mouseX, int mouseY, int mouseButton )
|
||||
{
|
||||
}
|
||||
|
||||
public void keyTyped( char c, int k )
|
||||
{
|
||||
}
|
||||
|
||||
public boolean suppressItemTooltips( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean suppressKeyPress( char c, int k )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
protected void drawFullImage( int x, int y, int w, int h )
|
||||
{
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
tessellator.getWorldRenderer().begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX );
|
||||
tessellator.getWorldRenderer().pos( (double) ( x + 0 ), (double) ( y + h ), (double) this.zLevel ).tex( 0.0, 1.0 ).endVertex();
|
||||
tessellator.getWorldRenderer().pos( (double) ( x + w ), (double) ( y + h ), (double) this.zLevel ).tex( 1.0, 1.0 ).endVertex();
|
||||
tessellator.getWorldRenderer().pos( (double) ( x + w ), (double) ( y + 0 ), (double) this.zLevel ).tex( 1.0, 0.0 ).endVertex();
|
||||
tessellator.getWorldRenderer().pos( (double) ( x + 0 ), (double) ( y + 0 ), (double) this.zLevel ).tex( 0.0, 0.0 ).endVertex();
|
||||
tessellator.draw();
|
||||
}
|
||||
|
||||
protected void drawT3( int x, int y, int w, int h, int u, int v, int uw, int vh )
|
||||
{
|
||||
int partW = uw / 3;
|
||||
|
||||
// Draw first bit
|
||||
super.drawTexturedModalRect( x, y, u, v, partW, vh );
|
||||
|
||||
// Draw middle bits
|
||||
int middleBits = Math.max( (w - 2 * partW) / partW, 0 );
|
||||
for( int j=0; j<middleBits; ++j )
|
||||
{
|
||||
super.drawTexturedModalRect( x + (j + 1) * partW, y, u + partW, v, partW, vh );
|
||||
}
|
||||
|
||||
// Draw end bit
|
||||
int endW = w - (middleBits + 1) * partW;
|
||||
super.drawTexturedModalRect( x + w - endW, y, u + uw - endW, v, endW, vh );
|
||||
}
|
||||
|
||||
protected void drawT9( int x, int y, int w, int h, int u, int v, int uw, int vh )
|
||||
{
|
||||
int partH = vh / 3;
|
||||
|
||||
// Draw first row
|
||||
drawT3( x, y, w, partH, u, v, uw, partH );
|
||||
|
||||
// Draw middle rows
|
||||
int middleBits = Math.max( (h - 2 * partH) / partH, 0 );
|
||||
for( int j=0; j<middleBits; ++j )
|
||||
{
|
||||
drawT3( x, y + ( j + 1 ) * partH, w, partH, u, v + partH, uw, partH );
|
||||
}
|
||||
|
||||
// Draw end row
|
||||
int endH = h - (middleBits + 1) * partH;
|
||||
drawT3( x, y + h - endH, w, endH, u, v + vh - endH, uw, endH );
|
||||
}
|
||||
|
||||
protected void drawInsetBorder( int x, int y, int w, int h )
|
||||
{
|
||||
// Draw border
|
||||
try
|
||||
{
|
||||
drawVerticalLine( x, y - 1, y + h - 1, 0xff363636 );
|
||||
drawVerticalLine( x + w - 1, y, y + h, 0xffffffff );
|
||||
drawHorizontalLine( x, x + w - 2, y, 0xff363636 );
|
||||
drawHorizontalLine( x + 1, x + w - 1, y + h - 1, 0xffffffff );
|
||||
drawHorizontalLine( x, x, y + h - 1, 0xff8a8a8a );
|
||||
drawHorizontalLine( x + w - 1, x + w - 1, y, 0xff8a8a8a );
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
|
||||
}
|
||||
}
|
||||
|
||||
protected void drawFlatBorder( int x, int y, int w, int h, int colour )
|
||||
{
|
||||
// Draw border
|
||||
colour = colour | 0xff000000;
|
||||
try
|
||||
{
|
||||
drawVerticalLine( x, y - 1, y + h - 1, colour );
|
||||
drawVerticalLine( x + w - 1, y, y + h, colour );
|
||||
drawHorizontalLine( x, x + w - 2, y, colour );
|
||||
drawHorizontalLine( x + 1, x + w - 1, y + h - 1, colour );
|
||||
drawHorizontalLine( x, x, y + h - 1, colour );
|
||||
drawHorizontalLine( x + w - 1, x + w - 1, y, colour );
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
|
||||
}
|
||||
}
|
||||
|
||||
protected void drawTooltip( String line, int x, int y )
|
||||
{
|
||||
drawTooltip( new String[] { line }, x, y );
|
||||
}
|
||||
|
||||
protected void drawTooltip( String[] lines, int x, int y )
|
||||
{
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
FontRenderer fontRenderer = mc.fontRendererObj;
|
||||
|
||||
int width = 0;
|
||||
for( int i=0; i<lines.length; ++i )
|
||||
{
|
||||
String line = lines[i];
|
||||
width = Math.max( fontRenderer.getStringWidth( line ), width );
|
||||
}
|
||||
int startX = x + 12;
|
||||
int startY = y - 12;
|
||||
if( startX + width + 4 > mc.currentScreen.width )
|
||||
{
|
||||
startX -= width + 24;
|
||||
if( startX < 24 )
|
||||
{
|
||||
startX = 24;
|
||||
}
|
||||
}
|
||||
|
||||
float oldZLevel = this.zLevel;
|
||||
try
|
||||
{
|
||||
this.zLevel = 300.0F;
|
||||
|
||||
int height = 10 * lines.length - 2;
|
||||
int j1 = -267386864;
|
||||
this.drawGradientRect( startX - 3, startY - 4, startX + width + 3, startY - 3, j1, j1 );
|
||||
this.drawGradientRect( startX - 3, startY + height + 3, startX + width + 3, startY + height + 4, j1, j1 );
|
||||
this.drawGradientRect( startX - 3, startY - 3, startX + width + 3, startY + height + 3, j1, j1 );
|
||||
this.drawGradientRect( startX - 4, startY - 3, startX - 3, startY + height + 3, j1, j1 );
|
||||
|
||||
this.drawGradientRect( startX + width + 3, startY - 3, startX + width + 4, startY + height + 3, j1, j1 );
|
||||
int k1 = 1347420415;
|
||||
int l1 = ( k1 & 16711422 ) >> 1 | k1 & -16777216;
|
||||
this.drawGradientRect( startX - 3, startY - 3 + 1, startX - 3 + 1, startY + height + 3 - 1, k1, l1 );
|
||||
this.drawGradientRect( startX + width + 2, startY - 3 + 1, startX + width + 3, startY + height + 3 - 1, k1, l1 );
|
||||
this.drawGradientRect( startX - 3, startY - 3, startX + width + 3, startY - 3 + 1, k1, k1 );
|
||||
this.drawGradientRect( startX - 3, startY + height + 2, startX + width + 3, startY + height + 3, l1, l1 );
|
||||
|
||||
GlStateManager.disableDepth();
|
||||
try
|
||||
{
|
||||
for( int i = 0; i < lines.length; ++i )
|
||||
{
|
||||
String line = lines[ i ];
|
||||
fontRenderer.drawStringWithShadow( line, startX, startY + i * 10, 0xffffffff );
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
|
||||
GlStateManager.enableDepth();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.zLevel = oldZLevel;
|
||||
}
|
||||
}
|
||||
|
||||
protected void drawItemStack( int x, int y, ItemStack stack )
|
||||
{
|
||||
if( stack != null )
|
||||
{
|
||||
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
|
||||
GlStateManager.enableLighting();
|
||||
GlStateManager.enableRescaleNormal();
|
||||
RenderHelper.enableGUIStandardItemLighting();
|
||||
OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f );
|
||||
try
|
||||
{
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
RenderItem renderItem = mc.getRenderItem();
|
||||
if( renderItem != null )
|
||||
{
|
||||
renderItem.renderItemAndEffectIntoGUI( stack, x, y );
|
||||
renderItem.renderItemOverlayIntoGUI( mc.fontRendererObj, stack, x, y, null );
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
RenderHelper.disableStandardItemLighting();
|
||||
GlStateManager.disableRescaleNormal();
|
||||
GlStateManager.disableLighting();
|
||||
GlStateManager.enableBlend();
|
||||
GlStateManager.blendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA );
|
||||
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void drawString( String s, int x, int y, int color )
|
||||
{
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
try
|
||||
{
|
||||
mc.fontRendererObj.drawString( s, x, y, color );
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
|
||||
}
|
||||
}
|
||||
|
||||
protected int getStringWidth( String s )
|
||||
{
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
return mc.fontRendererObj.getStringWidth( s );
|
||||
}
|
||||
|
||||
protected void playClickSound()
|
||||
{
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
mc.getSoundHandler().playSound( PositionedSoundRecord.create( new ResourceLocation( "gui.button.press" ), 1.0F ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
|
||||
package dan200.computercraft.client.gui.widgets;
|
||||
|
||||
import dan200.computercraft.client.gui.widgets.Widget;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.GlStateManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class WidgetContainer extends Widget
|
||||
{
|
||||
private ArrayList<Widget> m_widgets;
|
||||
private Widget m_modalWidget;
|
||||
|
||||
public WidgetContainer( int x, int y, int w, int h )
|
||||
{
|
||||
super( x, y, w, h );
|
||||
m_widgets = new ArrayList<Widget>();
|
||||
m_modalWidget = null;
|
||||
}
|
||||
|
||||
public void addWidget( Widget widget )
|
||||
{
|
||||
m_widgets.add( widget );
|
||||
widget.setParent( this );
|
||||
}
|
||||
|
||||
public void setModalWidget( Widget widget )
|
||||
{
|
||||
m_modalWidget = widget;
|
||||
if( widget != null )
|
||||
{
|
||||
widget.setParent( this );
|
||||
}
|
||||
}
|
||||
|
||||
public Widget getModalWidget()
|
||||
{
|
||||
return m_modalWidget;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update()
|
||||
{
|
||||
for( int i=0; i<m_widgets.size(); ++i )
|
||||
{
|
||||
m_widgets.get( i ).update();
|
||||
}
|
||||
if( m_modalWidget != null )
|
||||
{
|
||||
m_modalWidget.update();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY )
|
||||
{
|
||||
for( int i=0; i<m_widgets.size(); ++i )
|
||||
{
|
||||
Widget widget = m_widgets.get( i );
|
||||
if( widget.isVisible() )
|
||||
{
|
||||
widget.draw(
|
||||
mc,
|
||||
xOrigin + getXPosition(),
|
||||
yOrigin + getYPosition(),
|
||||
(m_modalWidget == null) ? (mouseX - getXPosition()) : -99,
|
||||
(m_modalWidget == null) ? (mouseY - getYPosition()) : -99
|
||||
);
|
||||
}
|
||||
}
|
||||
if( m_modalWidget != null )
|
||||
{
|
||||
if( m_modalWidget.isVisible() )
|
||||
{
|
||||
GlStateManager.pushMatrix();
|
||||
try
|
||||
{
|
||||
GlStateManager.translate( 0.0f, 0.0f, 200.0f );
|
||||
m_modalWidget.draw(
|
||||
mc,
|
||||
xOrigin + getXPosition(),
|
||||
yOrigin + getYPosition(),
|
||||
mouseX - getXPosition(),
|
||||
mouseY - getYPosition()
|
||||
);
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.popMatrix();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawForeground( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY )
|
||||
{
|
||||
for( int i=0; i<m_widgets.size(); ++i )
|
||||
{
|
||||
Widget widget = m_widgets.get( i );
|
||||
if( widget.isVisible() )
|
||||
{
|
||||
widget.drawForeground(
|
||||
mc,
|
||||
xOrigin + getXPosition(),
|
||||
yOrigin + getYPosition(),
|
||||
(m_modalWidget == null) ? (mouseX - getXPosition()) : -99,
|
||||
(m_modalWidget == null) ? (mouseY - getYPosition()) : -99
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if( m_modalWidget != null )
|
||||
{
|
||||
if( m_modalWidget.isVisible() )
|
||||
{
|
||||
GlStateManager.pushMatrix();
|
||||
try
|
||||
{
|
||||
GlStateManager.translate( 0.0f, 0.0f, 200.0f );
|
||||
m_modalWidget.drawForeground(
|
||||
mc,
|
||||
xOrigin + getXPosition(),
|
||||
yOrigin + getYPosition(),
|
||||
mouseX - getXPosition(),
|
||||
mouseY - getYPosition()
|
||||
);
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.popMatrix();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void modifyMousePosition( MousePos pos )
|
||||
{
|
||||
pos.x -= getXPosition();
|
||||
pos.y -= getYPosition();
|
||||
if( m_modalWidget == null )
|
||||
{
|
||||
for( int i = 0; i < m_widgets.size(); ++i )
|
||||
{
|
||||
Widget widget = m_widgets.get( i );
|
||||
if( widget.isVisible() )
|
||||
{
|
||||
widget.modifyMousePosition( pos );
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if( m_modalWidget.isVisible() )
|
||||
{
|
||||
m_modalWidget.modifyMousePosition( pos );
|
||||
}
|
||||
}
|
||||
pos.x += getXPosition();
|
||||
pos.y += getYPosition();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean suppressItemTooltips( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY )
|
||||
{
|
||||
if( m_modalWidget == null )
|
||||
{
|
||||
for( int i = 0; i < m_widgets.size(); ++i )
|
||||
{
|
||||
Widget widget = m_widgets.get( i );
|
||||
if( widget.isVisible() )
|
||||
{
|
||||
if( widget.suppressItemTooltips(
|
||||
mc,
|
||||
xOrigin + getXPosition(),
|
||||
yOrigin + getYPosition(),
|
||||
mouseX - getXPosition(),
|
||||
mouseY - getYPosition()
|
||||
) )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if( m_modalWidget.isVisible() && m_modalWidget.suppressItemTooltips(
|
||||
mc,
|
||||
xOrigin + getXPosition(),
|
||||
yOrigin + getYPosition(),
|
||||
mouseX - getXPosition(),
|
||||
mouseY - getYPosition()
|
||||
) )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean suppressKeyPress( char c, int k )
|
||||
{
|
||||
if( m_modalWidget == null )
|
||||
{
|
||||
for( int i = 0; i < m_widgets.size(); ++i )
|
||||
{
|
||||
Widget widget = m_widgets.get( i );
|
||||
if( widget.isVisible() )
|
||||
{
|
||||
if( widget.suppressKeyPress( c, k ) )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if( m_modalWidget.isVisible() )
|
||||
{
|
||||
if( m_modalWidget.suppressKeyPress( c, k ) )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMouseInput( int mouseX, int mouseY )
|
||||
{
|
||||
if( m_modalWidget == null )
|
||||
{
|
||||
for( int i = 0; i < m_widgets.size(); ++i )
|
||||
{
|
||||
Widget widget = m_widgets.get( i );
|
||||
if( widget.isVisible() )
|
||||
{
|
||||
widget.handleMouseInput(
|
||||
mouseX - getXPosition(),
|
||||
mouseY - getYPosition()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if( m_modalWidget.isVisible() )
|
||||
{
|
||||
m_modalWidget.handleMouseInput(
|
||||
mouseX - getXPosition(),
|
||||
mouseY - getYPosition()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleKeyboardInput()
|
||||
{
|
||||
if( m_modalWidget == null )
|
||||
{
|
||||
for( int i = 0; i < m_widgets.size(); ++i )
|
||||
{
|
||||
Widget widget = m_widgets.get( i );
|
||||
if( widget.isVisible() )
|
||||
{
|
||||
widget.handleKeyboardInput();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if( m_modalWidget.isVisible() )
|
||||
{
|
||||
m_modalWidget.handleKeyboardInput();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mouseClicked( int mouseX, int mouseY, int mouseButton )
|
||||
{
|
||||
if( m_modalWidget == null )
|
||||
{
|
||||
for( int i = 0; i < m_widgets.size(); ++i )
|
||||
{
|
||||
Widget widget = m_widgets.get( i );
|
||||
if( widget.isVisible() )
|
||||
{
|
||||
widget.mouseClicked(
|
||||
mouseX - getXPosition(),
|
||||
mouseY - getYPosition(),
|
||||
mouseButton
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if( m_modalWidget.isVisible() )
|
||||
{
|
||||
m_modalWidget.mouseClicked(
|
||||
mouseX - getXPosition(),
|
||||
mouseY - getYPosition(),
|
||||
mouseButton
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void keyTyped( char c, int k )
|
||||
{
|
||||
if( m_modalWidget == null )
|
||||
{
|
||||
for( int i = 0; i < m_widgets.size(); ++i )
|
||||
{
|
||||
Widget widget = m_widgets.get( i );
|
||||
if( widget.isVisible() )
|
||||
{
|
||||
widget.keyTyped( c, k );
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if( m_modalWidget.isVisible() )
|
||||
{
|
||||
m_modalWidget.keyTyped( c, k );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.gui.widgets;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.client.gui.FixedWidthFontRenderer;
|
||||
import dan200.computercraft.core.terminal.Terminal;
|
||||
import dan200.computercraft.core.terminal.TextBuffer;
|
||||
import dan200.computercraft.shared.computer.core.IComputer;
|
||||
import dan200.computercraft.shared.computer.core.IComputerContainer;
|
||||
import dan200.computercraft.shared.util.Colour;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiScreen;
|
||||
import net.minecraft.client.renderer.GlStateManager;
|
||||
import net.minecraft.util.ChatAllowedCharacters;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.lwjgl.input.Keyboard;
|
||||
import org.lwjgl.input.Mouse;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class WidgetTerminal extends Widget
|
||||
{
|
||||
private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/termBackground.png" );
|
||||
private static float TERMINATE_TIME = 0.5f;
|
||||
|
||||
private IComputerContainer m_computer;
|
||||
|
||||
private float m_terminateTimer;
|
||||
private float m_rebootTimer;
|
||||
private float m_shutdownTimer;
|
||||
|
||||
private int m_lastClickButton;
|
||||
private int m_lastClickX;
|
||||
private int m_lastClickY;
|
||||
|
||||
private boolean m_focus;
|
||||
private boolean m_allowFocusLoss;
|
||||
private boolean m_locked;
|
||||
|
||||
private int m_leftMargin;
|
||||
private int m_rightMargin;
|
||||
private int m_topMargin;
|
||||
private int m_bottomMargin;
|
||||
|
||||
private ArrayList<Integer> m_keysDown;
|
||||
|
||||
public WidgetTerminal( int x, int y, int termWidth, int termHeight, IComputerContainer computer, int leftMargin, int rightMargin, int topMargin, int bottomMargin )
|
||||
{
|
||||
super(
|
||||
x, y,
|
||||
leftMargin + rightMargin + termWidth * FixedWidthFontRenderer.FONT_WIDTH,
|
||||
topMargin + bottomMargin + termHeight * FixedWidthFontRenderer.FONT_HEIGHT
|
||||
);
|
||||
|
||||
m_computer = computer;
|
||||
m_terminateTimer = 0.0f;
|
||||
m_rebootTimer = 0.0f;
|
||||
m_shutdownTimer = 0.0f;
|
||||
|
||||
m_lastClickButton = -1;
|
||||
m_lastClickX = -1;
|
||||
m_lastClickY = -1;
|
||||
|
||||
m_focus = false;
|
||||
m_allowFocusLoss = true;
|
||||
m_locked = false;
|
||||
|
||||
m_leftMargin = leftMargin;
|
||||
m_rightMargin = rightMargin;
|
||||
m_topMargin = topMargin;
|
||||
m_bottomMargin = bottomMargin;
|
||||
|
||||
m_keysDown = new ArrayList<Integer>();
|
||||
}
|
||||
|
||||
public void setAllowFocusLoss( boolean allowFocusLoss )
|
||||
{
|
||||
m_allowFocusLoss = allowFocusLoss;
|
||||
m_focus = m_focus || !allowFocusLoss;
|
||||
}
|
||||
|
||||
public void setLocked( boolean locked )
|
||||
{
|
||||
m_locked = locked;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void keyTyped( char ch, int key )
|
||||
{
|
||||
if( m_focus && !m_locked )
|
||||
{
|
||||
// Ctrl+V for paste
|
||||
if( ch == 22 )
|
||||
{
|
||||
String clipboard = GuiScreen.getClipboardString();
|
||||
if( clipboard != null )
|
||||
{
|
||||
// Clip to the first occurance 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 = ChatAllowedCharacters.filterAllowedCharacters( clipboard );
|
||||
|
||||
if( !clipboard.isEmpty() )
|
||||
{
|
||||
// Clip to 512 characters
|
||||
if( clipboard.length() > 512 )
|
||||
{
|
||||
clipboard = clipboard.substring( 0, 512 );
|
||||
}
|
||||
|
||||
// Queue the "paste" event
|
||||
queueEvent( "paste", new Object[]{
|
||||
clipboard
|
||||
} );
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Regular keys normally
|
||||
if( m_terminateTimer <= 0.0f && m_rebootTimer <= 0.0f && m_shutdownTimer <= 0.0f )
|
||||
{
|
||||
boolean repeat = Keyboard.isRepeatEvent();
|
||||
if( key > 0 )
|
||||
{
|
||||
if( !repeat )
|
||||
{
|
||||
m_keysDown.add( key );
|
||||
}
|
||||
|
||||
// Queue the "key" event
|
||||
queueEvent( "key", new Object[]{
|
||||
key, repeat
|
||||
} );
|
||||
}
|
||||
|
||||
if( (ch >= 32 && ch <= 126) || (ch >= 160 && ch <= 255) ) // printable chars in byte range
|
||||
{
|
||||
// Queue the "char" event
|
||||
queueEvent( "char", new Object[]{
|
||||
Character.toString( ch )
|
||||
} );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mouseClicked( int mouseX, int mouseY, int button )
|
||||
{
|
||||
if( mouseX >= getXPosition() && mouseX < getXPosition() + getWidth() &&
|
||||
mouseY >= getYPosition() && mouseY < getYPosition() + getHeight() )
|
||||
{
|
||||
if( !m_focus && button == 0)
|
||||
{
|
||||
m_focus = true;
|
||||
}
|
||||
|
||||
if( m_focus )
|
||||
{
|
||||
IComputer computer = m_computer.getComputer();
|
||||
if( !m_locked && computer != null && computer.isColour() && button >= 0 && button <= 2 )
|
||||
{
|
||||
Terminal term = computer.getTerminal();
|
||||
if( term != null )
|
||||
{
|
||||
int charX = ( mouseX - ( getXPosition() + m_leftMargin ) ) / FixedWidthFontRenderer.FONT_WIDTH;
|
||||
int charY = ( mouseY - ( getYPosition() + m_topMargin ) ) / FixedWidthFontRenderer.FONT_HEIGHT;
|
||||
charX = Math.min( Math.max( charX, 0 ), term.getWidth() - 1 );
|
||||
charY = Math.min( Math.max( charY, 0 ), term.getHeight() - 1 );
|
||||
|
||||
computer.queueEvent( "mouse_click", new Object[]{
|
||||
button + 1, charX + 1, charY + 1
|
||||
} );
|
||||
|
||||
m_lastClickButton = button;
|
||||
m_lastClickX = charX;
|
||||
m_lastClickY = charY;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if( m_focus && button == 0 && m_allowFocusLoss )
|
||||
{
|
||||
m_focus = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleKeyboardInput()
|
||||
{
|
||||
for( int i=m_keysDown.size()-1; i>=0; --i )
|
||||
{
|
||||
int key = m_keysDown.get( i );
|
||||
if( !Keyboard.isKeyDown( key ) )
|
||||
{
|
||||
m_keysDown.remove( i );
|
||||
if( m_focus && !m_locked )
|
||||
{
|
||||
// Queue the "key_up" event
|
||||
queueEvent( "key_up", new Object[]{
|
||||
key
|
||||
} );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMouseInput( int mouseX, int mouseY )
|
||||
{
|
||||
IComputer computer = m_computer.getComputer();
|
||||
if( mouseX >= getXPosition() && mouseX < getXPosition() + getWidth() &&
|
||||
mouseY >= getYPosition() && mouseY < getYPosition() + getHeight() &&
|
||||
computer != null && computer.isColour() )
|
||||
{
|
||||
Terminal term = computer.getTerminal();
|
||||
if( term != null )
|
||||
{
|
||||
int charX = ( mouseX - (getXPosition() + m_leftMargin)) / FixedWidthFontRenderer.FONT_WIDTH;
|
||||
int charY = ( mouseY - (getYPosition() + m_topMargin)) / FixedWidthFontRenderer.FONT_HEIGHT;
|
||||
charX = Math.min( Math.max( charX, 0 ), term.getWidth() - 1 );
|
||||
charY = Math.min( Math.max( charY, 0 ), term.getHeight() - 1 );
|
||||
|
||||
if( m_lastClickButton >= 0 && !Mouse.isButtonDown( m_lastClickButton ) )
|
||||
{
|
||||
if( m_focus && !m_locked )
|
||||
{
|
||||
computer.queueEvent( "mouse_up", new Object[]{
|
||||
m_lastClickButton + 1, charX + 1, charY + 1
|
||||
} );
|
||||
}
|
||||
m_lastClickButton = -1;
|
||||
}
|
||||
|
||||
int wheelChange = Mouse.getEventDWheel();
|
||||
if( wheelChange == 0 && m_lastClickButton == -1 )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if( m_focus && !m_locked )
|
||||
{
|
||||
if( wheelChange < 0 )
|
||||
{
|
||||
computer.queueEvent( "mouse_scroll", new Object[]{
|
||||
1, charX + 1, charY + 1
|
||||
} );
|
||||
}
|
||||
else if( wheelChange > 0 )
|
||||
{
|
||||
computer.queueEvent( "mouse_scroll", new Object[]{
|
||||
-1, charX + 1, charY + 1
|
||||
} );
|
||||
}
|
||||
|
||||
if( m_lastClickButton >= 0 && ( charX != m_lastClickX || charY != m_lastClickY ) )
|
||||
{
|
||||
computer.queueEvent( "mouse_drag", new Object[]{
|
||||
m_lastClickButton + 1, charX + 1, charY + 1
|
||||
} );
|
||||
m_lastClickX = charX;
|
||||
m_lastClickY = charY;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update()
|
||||
{
|
||||
// Handle special keys
|
||||
if( m_focus && !m_locked && (Keyboard.isKeyDown( 29 ) || Keyboard.isKeyDown( 157 )) )
|
||||
{
|
||||
// Ctrl+T for terminate
|
||||
if( Keyboard.isKeyDown( 20 ) )
|
||||
{
|
||||
if( m_terminateTimer < TERMINATE_TIME )
|
||||
{
|
||||
m_terminateTimer = m_terminateTimer + 0.05f;
|
||||
if( m_terminateTimer >= TERMINATE_TIME )
|
||||
{
|
||||
queueEvent( "terminate" );
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_terminateTimer = 0.0f;
|
||||
}
|
||||
|
||||
// Ctrl+R for reboot
|
||||
if( Keyboard.isKeyDown(19) )
|
||||
{
|
||||
if( m_rebootTimer < TERMINATE_TIME )
|
||||
{
|
||||
m_rebootTimer = m_rebootTimer + 0.05f;
|
||||
if( m_rebootTimer >= TERMINATE_TIME )
|
||||
{
|
||||
IComputer computer = m_computer.getComputer();
|
||||
if( computer != null )
|
||||
{
|
||||
computer.reboot();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_rebootTimer = 0.0f;
|
||||
}
|
||||
|
||||
// Ctrl+S for shutdown
|
||||
if( Keyboard.isKeyDown(31) )
|
||||
{
|
||||
if( m_shutdownTimer < TERMINATE_TIME )
|
||||
{
|
||||
m_shutdownTimer = m_shutdownTimer + 0.05f;
|
||||
if( m_shutdownTimer >= TERMINATE_TIME )
|
||||
{
|
||||
IComputer computer = m_computer.getComputer();
|
||||
if( computer != null )
|
||||
{
|
||||
computer.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_shutdownTimer = 0.0f;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_terminateTimer = 0.0f;
|
||||
m_rebootTimer = 0.0f;
|
||||
m_shutdownTimer = 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY )
|
||||
{
|
||||
int startX = xOrigin + getXPosition();
|
||||
int startY = yOrigin + getYPosition();
|
||||
|
||||
// Draw the screen contents
|
||||
IComputer computer = m_computer.getComputer();
|
||||
Terminal terminal = (computer != null) ? computer.getTerminal() : null;
|
||||
if( terminal != null )
|
||||
{
|
||||
// Draw the terminal
|
||||
boolean greyscale = !computer.isColour();
|
||||
synchronized( terminal )
|
||||
{
|
||||
// Get the data from the terminal first
|
||||
// Unfortunately we have to keep the lock for the whole of drawing, so the text doesn't change under us.
|
||||
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer)ComputerCraft.getFixedWidthFontRenderer();
|
||||
boolean tblink = m_focus && terminal.getCursorBlink() && ComputerCraft.getGlobalCursorBlink();
|
||||
int tw = terminal.getWidth();
|
||||
int th = terminal.getHeight();
|
||||
int tx = terminal.getCursorX();
|
||||
int ty = terminal.getCursorY();
|
||||
|
||||
int x = startX + m_leftMargin;
|
||||
int y = startY + m_topMargin;
|
||||
|
||||
// Draw margins
|
||||
TextBuffer emptyLine = new TextBuffer( ' ', tw );
|
||||
if( m_topMargin > 0 )
|
||||
{
|
||||
fontRenderer.drawString( emptyLine, x, startY, terminal.getTextColourLine( 0 ), terminal.getBackgroundColourLine( 0 ), m_leftMargin, m_rightMargin, greyscale );
|
||||
}
|
||||
if( m_bottomMargin > 0 )
|
||||
{
|
||||
fontRenderer.drawString( emptyLine, x, startY + 2 * m_bottomMargin + ( th - 1 ) * FixedWidthFontRenderer.FONT_HEIGHT, terminal.getTextColourLine( th - 1 ), terminal.getBackgroundColourLine( th - 1 ), m_leftMargin, m_rightMargin, greyscale );
|
||||
}
|
||||
|
||||
// Draw lines
|
||||
for( int line=0; line<th; ++line )
|
||||
{
|
||||
TextBuffer text = terminal.getLine(line);
|
||||
TextBuffer colour = terminal.getTextColourLine( line );
|
||||
TextBuffer backgroundColour = terminal.getBackgroundColourLine( line );
|
||||
fontRenderer.drawString( text, x, y, colour, backgroundColour, m_leftMargin, m_rightMargin, greyscale );
|
||||
if( tblink && ty == line )
|
||||
{
|
||||
if( tx >= 0 && tx < tw )
|
||||
{
|
||||
TextBuffer cursor = new TextBuffer( '_', 1 );
|
||||
TextBuffer cursorColour = new TextBuffer( "0123456789abcdef".charAt( terminal.getTextColour() ), 1 );
|
||||
fontRenderer.drawString(
|
||||
cursor,
|
||||
x + FixedWidthFontRenderer.FONT_WIDTH * tx,
|
||||
y,
|
||||
cursorColour, null,
|
||||
0, 0,
|
||||
greyscale
|
||||
);
|
||||
}
|
||||
}
|
||||
y = y + FixedWidthFontRenderer.FONT_HEIGHT;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Draw a black background
|
||||
mc.getTextureManager().bindTexture( background );
|
||||
Colour black = Colour.Black;
|
||||
GlStateManager.color( black.getR(), black.getG(), black.getB(), 1.0f );
|
||||
try
|
||||
{
|
||||
drawTexturedModalRect( startX, startY, 0, 0, getWidth(), getHeight() );
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean suppressKeyPress( char c, int k )
|
||||
{
|
||||
if( m_focus )
|
||||
{
|
||||
return k != 1; // escape
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void queueEvent( String event )
|
||||
{
|
||||
IComputer computer = m_computer.getComputer();
|
||||
if( computer != null )
|
||||
{
|
||||
computer.queueEvent( event );
|
||||
}
|
||||
}
|
||||
|
||||
private void queueEvent( String event, Object[] args )
|
||||
{
|
||||
IComputer computer = m_computer.getComputer();
|
||||
if( computer != null )
|
||||
{
|
||||
computer.queueEvent( event, args );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.proxy;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.client.render.TileEntityTurtleRenderer;
|
||||
import dan200.computercraft.client.render.TurtleSmartItemModel;
|
||||
import dan200.computercraft.shared.proxy.CCTurtleProxyCommon;
|
||||
import dan200.computercraft.shared.turtle.blocks.TileTurtle;
|
||||
import dan200.computercraft.shared.turtle.core.TurtleBrain;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.ItemMeshDefinition;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
|
||||
import net.minecraft.client.resources.IResourceManager;
|
||||
import net.minecraft.client.resources.SimpleReloadableResourceManager;
|
||||
import net.minecraft.client.resources.model.IBakedModel;
|
||||
import net.minecraft.client.resources.model.ModelBakery;
|
||||
import net.minecraft.client.resources.model.ModelResourceLocation;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.client.event.ModelBakeEvent;
|
||||
import net.minecraftforge.client.event.TextureStitchEvent;
|
||||
import net.minecraftforge.client.model.IModel;
|
||||
import net.minecraftforge.client.model.ISmartItemModel;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.fml.client.registry.ClientRegistry;
|
||||
import net.minecraftforge.fml.common.FMLCommonHandler;
|
||||
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.gameevent.TickEvent;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class CCTurtleProxyClient extends CCTurtleProxyCommon
|
||||
{
|
||||
public CCTurtleProxyClient()
|
||||
{
|
||||
}
|
||||
|
||||
// IComputerCraftProxy implementation
|
||||
|
||||
@Override
|
||||
public void init()
|
||||
{
|
||||
super.init();
|
||||
|
||||
// Register item models
|
||||
ItemMeshDefinition turtleMeshDefinition = new ItemMeshDefinition()
|
||||
{
|
||||
private ModelResourceLocation turtle_dynamic = new ModelResourceLocation( "computercraft:turtle_dynamic", "inventory" );
|
||||
|
||||
@Override
|
||||
public ModelResourceLocation getModelLocation( ItemStack stack )
|
||||
{
|
||||
return turtle_dynamic;
|
||||
}
|
||||
};
|
||||
String[] turtleModelNames = new String[] {
|
||||
"turtle_dynamic",
|
||||
"CC-Turtle", "CC-TurtleAdvanced",
|
||||
"turtle_black", "turtle_red", "turtle_green", "turtle_brown",
|
||||
"turtle_blue", "turtle_purple", "turtle_cyan", "turtle_lightGrey",
|
||||
"turtle_grey", "turtle_pink", "turtle_lime", "turtle_yellow",
|
||||
"turtle_lightBlue", "turtle_magenta", "turtle_orange", "turtle_white",
|
||||
"turtle_elf_overlay"
|
||||
};
|
||||
registerItemModel( ComputerCraft.Blocks.turtle, turtleMeshDefinition, turtleModelNames );
|
||||
registerItemModel( ComputerCraft.Blocks.turtleExpanded, turtleMeshDefinition, turtleModelNames );
|
||||
registerItemModel( ComputerCraft.Blocks.turtleAdvanced, turtleMeshDefinition, turtleModelNames );
|
||||
|
||||
// Setup renderers
|
||||
ClientRegistry.bindTileEntitySpecialRenderer( TileTurtle.class, new TileEntityTurtleRenderer() );
|
||||
|
||||
// Setup client forge handlers
|
||||
registerForgeHandlers();
|
||||
}
|
||||
|
||||
private void registerItemModel( Block block, ItemMeshDefinition definition, String[] names )
|
||||
{
|
||||
registerItemModel( Item.getItemFromBlock( block ), definition, names );
|
||||
}
|
||||
|
||||
private void registerItemModel( Item item, ItemMeshDefinition definition, String[] names )
|
||||
{
|
||||
for( int i=0; i<names.length; ++i )
|
||||
{
|
||||
ModelBakery.addVariantName( item, "computercraft:" + names[ i ] );
|
||||
}
|
||||
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register( item, definition );
|
||||
}
|
||||
|
||||
private void registerForgeHandlers()
|
||||
{
|
||||
ForgeHandlers handlers = new ForgeHandlers();
|
||||
MinecraftForge.EVENT_BUS.register( handlers );
|
||||
}
|
||||
|
||||
public class ForgeHandlers
|
||||
{
|
||||
private TurtleSmartItemModel m_turtleSmartItemModel;
|
||||
|
||||
public ForgeHandlers()
|
||||
{
|
||||
m_turtleSmartItemModel = new TurtleSmartItemModel();
|
||||
IResourceManager resourceManager = Minecraft.getMinecraft().getResourceManager();
|
||||
if( resourceManager instanceof SimpleReloadableResourceManager )
|
||||
{
|
||||
SimpleReloadableResourceManager reloadableResourceManager = (SimpleReloadableResourceManager)resourceManager;
|
||||
reloadableResourceManager.registerReloadListener( m_turtleSmartItemModel );
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onTick( TickEvent.ClientTickEvent event )
|
||||
{
|
||||
if( event.phase == TickEvent.Phase.END )
|
||||
{
|
||||
TurtleBrain.cleanupBrains();
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onTextureStitchEvent( TextureStitchEvent.Pre event )
|
||||
{
|
||||
event.map.registerSprite( new ResourceLocation( "computercraft", "blocks/craftyUpgrade" ) );
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onModelBakeEvent( ModelBakeEvent event )
|
||||
{
|
||||
loadModel( event, "turtle_modem_off_left" );
|
||||
loadModel( event, "turtle_modem_on_left" );
|
||||
loadModel( event, "turtle_modem_off_right" );
|
||||
loadModel( event, "turtle_modem_on_right" );
|
||||
loadModel( event, "turtle_crafting_table_left" );
|
||||
loadModel( event, "turtle_crafting_table_right" );
|
||||
loadModel( event, "advanced_turtle_modem_off_left" );
|
||||
loadModel( event, "advanced_turtle_modem_on_left" );
|
||||
loadModel( event, "advanced_turtle_modem_off_right" );
|
||||
loadModel( event, "advanced_turtle_modem_on_right" );
|
||||
loadSmartModel( event, "turtle_dynamic", m_turtleSmartItemModel );
|
||||
}
|
||||
|
||||
private void loadModel( ModelBakeEvent event, String name )
|
||||
{
|
||||
try
|
||||
{
|
||||
IModel model = event.modelLoader.getModel(
|
||||
new ResourceLocation( "computercraft", "block/" + name )
|
||||
);
|
||||
IBakedModel bakedModel = model.bake(
|
||||
model.getDefaultState(),
|
||||
DefaultVertexFormats.ITEM,
|
||||
new Function<ResourceLocation, TextureAtlasSprite>()
|
||||
{
|
||||
@Override
|
||||
public TextureAtlasSprite apply( ResourceLocation location )
|
||||
{
|
||||
return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite( location.toString() );
|
||||
}
|
||||
}
|
||||
);
|
||||
event.modelRegistry.putObject(
|
||||
new ModelResourceLocation( "computercraft:" + name, "inventory" ),
|
||||
bakedModel
|
||||
);
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
System.out.println( "Could not load model: name" );
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void loadSmartModel( ModelBakeEvent event, String name, ISmartItemModel smartModel )
|
||||
{
|
||||
event.modelRegistry.putObject(
|
||||
new ModelResourceLocation( "computercraft:" + name, "inventory" ),
|
||||
smartModel
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.shared.computer.blocks.TileComputer;
|
||||
import dan200.computercraft.shared.computer.core.ClientComputer;
|
||||
import dan200.computercraft.shared.computer.core.ComputerFamily;
|
||||
import dan200.computercraft.shared.computer.items.ItemComputer;
|
||||
import dan200.computercraft.shared.media.inventory.ContainerHeldItem;
|
||||
import dan200.computercraft.shared.media.items.ItemPrintout;
|
||||
import dan200.computercraft.shared.network.ComputerCraftPacket;
|
||||
import dan200.computercraft.shared.peripheral.diskdrive.TileDiskDrive;
|
||||
import dan200.computercraft.shared.peripheral.monitor.TileMonitor;
|
||||
import dan200.computercraft.shared.peripheral.printer.TilePrinter;
|
||||
import dan200.computercraft.shared.pocket.items.ItemPocketComputer;
|
||||
import dan200.computercraft.shared.proxy.ComputerCraftProxyCommon;
|
||||
import dan200.computercraft.shared.turtle.blocks.TileTurtle;
|
||||
import dan200.computercraft.shared.turtle.entity.TurtleVisionCamera;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.ItemMeshDefinition;
|
||||
import net.minecraft.client.resources.model.ModelBakery;
|
||||
import net.minecraft.client.resources.model.ModelResourceLocation;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.entity.player.InventoryPlayer;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.IThreadListener;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraftforge.client.event.RenderGameOverlayEvent;
|
||||
import net.minecraftforge.client.event.RenderHandEvent;
|
||||
import net.minecraftforge.client.event.RenderPlayerEvent;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.fml.client.FMLClientHandler;
|
||||
import net.minecraftforge.fml.client.registry.ClientRegistry;
|
||||
import net.minecraftforge.fml.common.FMLCommonHandler;
|
||||
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
|
||||
import net.minecraftforge.fml.common.gameevent.TickEvent;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
|
||||
{
|
||||
private long m_tick;
|
||||
private long m_renderFrame;
|
||||
private FixedWidthFontRenderer m_fixedWidthFontRenderer;
|
||||
|
||||
public ComputerCraftProxyClient()
|
||||
{
|
||||
}
|
||||
|
||||
// IComputerCraftProxy implementation
|
||||
|
||||
@Override
|
||||
public void init()
|
||||
{
|
||||
super.init();
|
||||
m_tick = 0;
|
||||
m_renderFrame = 0;
|
||||
|
||||
// Load textures
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
m_fixedWidthFontRenderer = new FixedWidthFontRenderer( mc.getTextureManager() );
|
||||
|
||||
// Register item models
|
||||
registerItemModel( ComputerCraft.Blocks.computer, new ItemMeshDefinition()
|
||||
{
|
||||
private ModelResourceLocation computer = new ModelResourceLocation( "computercraft:CC-Computer", "inventory" );
|
||||
private ModelResourceLocation advanced_computer = new ModelResourceLocation( "computercraft:advanced_computer", "inventory" );
|
||||
|
||||
@Override
|
||||
public ModelResourceLocation getModelLocation( ItemStack stack )
|
||||
{
|
||||
ItemComputer itemComputer = (ItemComputer) stack.getItem();
|
||||
ComputerFamily family = itemComputer.getFamily( stack.getItemDamage() );
|
||||
return ( family == ComputerFamily.Advanced ) ? advanced_computer : computer;
|
||||
}
|
||||
}, new String[]{ "CC-Computer", "advanced_computer" } );
|
||||
registerItemModel( ComputerCraft.Blocks.peripheral, 0, "CC-Peripheral" );
|
||||
registerItemModel( ComputerCraft.Blocks.peripheral, 1, "wireless_modem" );
|
||||
registerItemModel( ComputerCraft.Blocks.peripheral, 2, "monitor" );
|
||||
registerItemModel( ComputerCraft.Blocks.peripheral, 3, "printer" );
|
||||
registerItemModel( ComputerCraft.Blocks.peripheral, 4, "advanced_monitor" );
|
||||
registerItemModel( ComputerCraft.Blocks.cable, 0, "CC-Cable" );
|
||||
registerItemModel( ComputerCraft.Blocks.cable, 1, "wired_modem" );
|
||||
registerItemModel( ComputerCraft.Blocks.commandComputer, "command_computer" );
|
||||
registerItemModel( ComputerCraft.Blocks.advancedModem, "advanced_modem" );
|
||||
|
||||
registerItemModel( ComputerCraft.Items.disk, "disk" );
|
||||
registerItemModel( ComputerCraft.Items.diskExpanded, "diskExpanded" );
|
||||
registerItemModel( ComputerCraft.Items.treasureDisk, "treasureDisk" );
|
||||
registerItemModel( ComputerCraft.Items.printout, 0, "printout" );
|
||||
registerItemModel( ComputerCraft.Items.printout, 1, "pages" );
|
||||
registerItemModel( ComputerCraft.Items.printout, 2, "book" );
|
||||
registerItemModel( ComputerCraft.Items.pocketComputer, new ItemMeshDefinition()
|
||||
{
|
||||
private ModelResourceLocation pocket_computer_off = new ModelResourceLocation( "computercraft:pocketComputer", "inventory" );
|
||||
private ModelResourceLocation pocket_computer_on = new ModelResourceLocation( "computercraft:pocket_computer_on", "inventory" );
|
||||
private ModelResourceLocation pocket_computer_blinking = new ModelResourceLocation( "computercraft:pocket_computer_blinking", "inventory" );
|
||||
private ModelResourceLocation pocket_computer_on_modem_on = new ModelResourceLocation( "computercraft:pocket_computer_on_modem_on", "inventory" );
|
||||
private ModelResourceLocation pocket_computer_blinking_modem_on = new ModelResourceLocation( "computercraft:pocket_computer_blinking_modem_on", "inventory" );
|
||||
private ModelResourceLocation advanced_pocket_computer_off = new ModelResourceLocation( "computercraft:advanced_pocket_computer_off", "inventory" );
|
||||
private ModelResourceLocation advanced_pocket_computer_on = new ModelResourceLocation( "computercraft:advanced_pocket_computer_on", "inventory" );
|
||||
private ModelResourceLocation advanced_pocket_computer_blinking = new ModelResourceLocation( "computercraft:advanced_pocket_computer_blinking", "inventory" );
|
||||
private ModelResourceLocation advanced_pocket_computer_on_modem_on = new ModelResourceLocation( "computercraft:advanced_pocket_computer_on_modem_on", "inventory" );
|
||||
private ModelResourceLocation advanced_pocket_computer_blinking_modem_on = new ModelResourceLocation( "computercraft:advanced_pocket_computer_blinking_modem_on", "inventory" );
|
||||
|
||||
@Override
|
||||
public ModelResourceLocation getModelLocation( ItemStack stack )
|
||||
{
|
||||
ItemPocketComputer itemPocketComputer = (ItemPocketComputer)stack.getItem();
|
||||
boolean modemOn = itemPocketComputer.getModemState( stack );
|
||||
switch( itemPocketComputer.getFamily( stack ) )
|
||||
{
|
||||
case Advanced:
|
||||
{
|
||||
switch( itemPocketComputer.getState( stack ) )
|
||||
{
|
||||
case Off:
|
||||
default:
|
||||
{
|
||||
return advanced_pocket_computer_off;
|
||||
}
|
||||
case On:
|
||||
{
|
||||
return modemOn ? advanced_pocket_computer_on_modem_on : advanced_pocket_computer_on;
|
||||
}
|
||||
case Blinking:
|
||||
{
|
||||
return modemOn ? advanced_pocket_computer_blinking_modem_on : advanced_pocket_computer_blinking;
|
||||
}
|
||||
}
|
||||
}
|
||||
case Normal:
|
||||
default:
|
||||
{
|
||||
switch( itemPocketComputer.getState( stack ) )
|
||||
{
|
||||
case Off:
|
||||
default:
|
||||
{
|
||||
return pocket_computer_off;
|
||||
}
|
||||
case On:
|
||||
{
|
||||
return modemOn ? pocket_computer_on_modem_on : pocket_computer_on;
|
||||
}
|
||||
case Blinking:
|
||||
{
|
||||
return modemOn ? pocket_computer_blinking_modem_on : pocket_computer_blinking;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, new String[] {
|
||||
"pocketComputer", "pocket_computer_on", "pocket_computer_blinking", "pocket_computer_on_modem_on", "pocket_computer_blinking_modem_on",
|
||||
"advanced_pocket_computer_off", "advanced_pocket_computer_on", "advanced_pocket_computer_blinking", "advanced_pocket_computer_on_modem_on", "advanced_pocket_computer_blinking_modem_on",
|
||||
} );
|
||||
|
||||
// Setup renderers
|
||||
ClientRegistry.bindTileEntitySpecialRenderer( TileMonitor.class, new TileEntityMonitorRenderer() );
|
||||
|
||||
// Setup client forge handlers
|
||||
registerForgeHandlers();
|
||||
}
|
||||
|
||||
private void registerItemModel( Block block, int damage, String name )
|
||||
{
|
||||
registerItemModel( Item.getItemFromBlock( block ), damage, name );
|
||||
}
|
||||
|
||||
private void registerItemModel( Item item, int damage, String name )
|
||||
{
|
||||
name = "computercraft:" + name;
|
||||
ModelResourceLocation res = new ModelResourceLocation( name, "inventory" );
|
||||
ModelBakery.addVariantName( item, name );
|
||||
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register( item, damage, res );
|
||||
}
|
||||
|
||||
private void registerItemModel( Block block, String name )
|
||||
{
|
||||
registerItemModel( Item.getItemFromBlock( block ), name );
|
||||
}
|
||||
|
||||
private void registerItemModel( Item item, String name )
|
||||
{
|
||||
name = "computercraft:" + name;
|
||||
final ModelResourceLocation res = new ModelResourceLocation( name, "inventory" );
|
||||
ModelBakery.addVariantName( item, name );
|
||||
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register( item, new ItemMeshDefinition()
|
||||
{
|
||||
@Override
|
||||
public ModelResourceLocation getModelLocation( ItemStack stack )
|
||||
{
|
||||
return res;
|
||||
}
|
||||
} );
|
||||
}
|
||||
|
||||
private void registerItemModel( Block block, ItemMeshDefinition definition, String[] names )
|
||||
{
|
||||
registerItemModel( Item.getItemFromBlock( block ), definition, names );
|
||||
}
|
||||
|
||||
private void registerItemModel( Item item, ItemMeshDefinition definition, String[] names )
|
||||
{
|
||||
for( int i=0; i<names.length; ++i )
|
||||
{
|
||||
ModelBakery.addVariantName( item, "computercraft:" + names[i] );
|
||||
}
|
||||
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register( item, definition );
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClient()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getGlobalCursorBlink()
|
||||
{
|
||||
return ( m_tick / 8) % 2 == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getRenderFrame()
|
||||
{
|
||||
return m_renderFrame;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteDisplayLists( int list, int range )
|
||||
{
|
||||
GL11.glDeleteLists( list, range );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getFixedWidthFontRenderer()
|
||||
{
|
||||
return m_fixedWidthFontRenderer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRecordInfo( ItemStack recordStack )
|
||||
{
|
||||
List info = new ArrayList(1);
|
||||
recordStack.getItem().addInformation( recordStack, null, info, false );
|
||||
if( info.size() > 0 ) {
|
||||
return info.get(0).toString();
|
||||
} else {
|
||||
return super.getRecordInfo( recordStack );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void playRecord( String record, String recordInfo, World world, BlockPos pos )
|
||||
{
|
||||
Minecraft mc = FMLClientHandler.instance().getClient();
|
||||
world.playRecord( pos, record );
|
||||
if( record != null )
|
||||
{
|
||||
mc.ingameGUI.setRecordPlayingMessage( recordInfo );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getDiskDriveGUI( InventoryPlayer inventory, TileDiskDrive drive )
|
||||
{
|
||||
return new GuiDiskDrive( inventory, drive );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getComputerGUI( TileComputer computer )
|
||||
{
|
||||
return new GuiComputer( computer );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrinterGUI( InventoryPlayer inventory, TilePrinter printer )
|
||||
{
|
||||
return new GuiPrinter( inventory, printer );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getTurtleGUI( InventoryPlayer inventory, TileTurtle turtle )
|
||||
{
|
||||
return new GuiTurtle( turtle.getWorld(), inventory, turtle );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrintoutGUI( InventoryPlayer inventory )
|
||||
{
|
||||
ContainerHeldItem container = new ContainerHeldItem( inventory );
|
||||
if( container.getStack() != null && container.getStack().getItem() instanceof ItemPrintout )
|
||||
{
|
||||
return new GuiPrintout( container );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPocketComputerGUI( InventoryPlayer inventory )
|
||||
{
|
||||
ContainerHeldItem container = new ContainerHeldItem( inventory );
|
||||
if( container.getStack() != null && container.getStack().getItem() instanceof ItemPocketComputer )
|
||||
{
|
||||
return new GuiPocketComputer( container );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getWorldDir( World world )
|
||||
{
|
||||
return new File( ComputerCraft.getBaseDir(), "saves/" + world.getSaveHandler().getWorldDirectoryName() );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handlePacket( final ComputerCraftPacket packet, final EntityPlayer player )
|
||||
{
|
||||
switch( packet.m_packetType )
|
||||
{
|
||||
case ComputerCraftPacket.ComputerChanged:
|
||||
case ComputerCraftPacket.ComputerDeleted:
|
||||
{
|
||||
// Packet from Server to Client
|
||||
IThreadListener listener = Minecraft.getMinecraft();
|
||||
if( listener != null )
|
||||
{
|
||||
if( listener.isCallingFromMinecraftThread() )
|
||||
{
|
||||
processPacket( packet, player );
|
||||
}
|
||||
else
|
||||
{
|
||||
listener.addScheduledTask( new Runnable()
|
||||
{
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
processPacket( packet, player );
|
||||
}
|
||||
} );
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
{
|
||||
// Packet from Client to Server
|
||||
super.handlePacket( packet, player );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processPacket( ComputerCraftPacket packet, EntityPlayer player )
|
||||
{
|
||||
switch( packet.m_packetType )
|
||||
{
|
||||
///////////////////////////////////
|
||||
// Packets from Server to Client //
|
||||
///////////////////////////////////
|
||||
case ComputerCraftPacket.ComputerChanged:
|
||||
{
|
||||
int instanceID = packet.m_dataInt[ 0 ];
|
||||
if( !ComputerCraft.clientComputerRegistry.contains( instanceID ) )
|
||||
{
|
||||
ComputerCraft.clientComputerRegistry.add( instanceID, new ClientComputer( instanceID ) );
|
||||
}
|
||||
ComputerCraft.clientComputerRegistry.get( instanceID ).handlePacket( packet, (EntityPlayer) player );
|
||||
break;
|
||||
}
|
||||
case ComputerCraftPacket.ComputerDeleted:
|
||||
{
|
||||
int instanceID = packet.m_dataInt[ 0 ];
|
||||
if( ComputerCraft.clientComputerRegistry.contains( instanceID ) )
|
||||
{
|
||||
ComputerCraft.clientComputerRegistry.remove( instanceID );
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void registerForgeHandlers()
|
||||
{
|
||||
ForgeHandlers handlers = new ForgeHandlers();
|
||||
FMLCommonHandler.instance().bus().register( handlers );
|
||||
MinecraftForge.EVENT_BUS.register( handlers );
|
||||
}
|
||||
|
||||
public class ForgeHandlers
|
||||
{
|
||||
public ForgeHandlers()
|
||||
{
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onRenderHand( RenderHandEvent event )
|
||||
{
|
||||
// Don't draw the player arm when in turtle vision
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
if( mc.getRenderViewEntity() instanceof TurtleVisionCamera )
|
||||
{
|
||||
event.setCanceled( true );
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onRenderPlayer( RenderPlayerEvent.Pre event )
|
||||
{
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
if( event.entityPlayer.isUser() && mc.getRenderViewEntity() instanceof TurtleVisionCamera )
|
||||
{
|
||||
// HACK: Force the 'livingPlayer' variable to the player, this ensures the entity is drawn
|
||||
event.renderer.getRenderManager().livingPlayer = event.entityPlayer;
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onRenderPlayer( RenderPlayerEvent.Post event )
|
||||
{
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
if( event.entityPlayer.isUser() && mc.getRenderViewEntity() instanceof TurtleVisionCamera )
|
||||
{
|
||||
// HACK: Restore the 'livingPlayer' variable to what it was before the RenderPlayerEvent.Pre hack
|
||||
event.renderer.getRenderManager().livingPlayer = mc.getRenderViewEntity();
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onPreRenderGameOverlay( RenderGameOverlayEvent.Pre event )
|
||||
{
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
if( mc.getRenderViewEntity() instanceof TurtleVisionCamera )
|
||||
{
|
||||
switch( event.type )
|
||||
{
|
||||
case HELMET:
|
||||
case PORTAL:
|
||||
//case CROSSHAIRS:
|
||||
case BOSSHEALTH:
|
||||
case ARMOR:
|
||||
case HEALTH:
|
||||
case FOOD:
|
||||
case AIR:
|
||||
case HOTBAR:
|
||||
case EXPERIENCE:
|
||||
case HEALTHMOUNT:
|
||||
case JUMPBAR:
|
||||
{
|
||||
event.setCanceled( true );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onTick( TickEvent.ClientTickEvent event )
|
||||
{
|
||||
if( event.phase == TickEvent.Phase.START )
|
||||
{
|
||||
m_tick++;
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onRenderTick( TickEvent.RenderTickEvent event )
|
||||
{
|
||||
if( event.phase == TickEvent.Phase.START )
|
||||
{
|
||||
m_renderFrame++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.render;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.client.gui.FixedWidthFontRenderer;
|
||||
import dan200.computercraft.core.terminal.Terminal;
|
||||
import dan200.computercraft.core.terminal.TextBuffer;
|
||||
import dan200.computercraft.shared.common.ClientTerminal;
|
||||
import dan200.computercraft.shared.common.ITerminal;
|
||||
import dan200.computercraft.shared.peripheral.monitor.TileMonitor;
|
||||
import dan200.computercraft.shared.util.Colour;
|
||||
import dan200.computercraft.shared.util.DirectionUtil;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.GlStateManager;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.renderer.WorldRenderer;
|
||||
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
|
||||
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.client.MinecraftForgeClient;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMonitor>
|
||||
{
|
||||
public TileEntityMonitorRenderer()
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderTileEntityAt( TileMonitor tileEntity, double posX, double posY, double posZ, float f, int i )
|
||||
{
|
||||
if( tileEntity != null )
|
||||
{
|
||||
renderMonitorAt( tileEntity, posX, posY, posZ, f, i );
|
||||
}
|
||||
}
|
||||
|
||||
private void renderMonitorAt( TileMonitor monitor, double posX, double posY, double posZ, float f, int i )
|
||||
{
|
||||
// Render from the origin monitor
|
||||
TileMonitor origin = monitor.getOrigin();
|
||||
if( origin == null )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure each monitor is rendered only once
|
||||
long renderFrame = ComputerCraft.getRenderFrame();
|
||||
if( origin.m_lastRenderFrame == renderFrame )
|
||||
{
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
origin.m_lastRenderFrame = renderFrame;
|
||||
}
|
||||
|
||||
boolean redraw = origin.pollChanged();
|
||||
BlockPos monitorPos = monitor.getPos();
|
||||
BlockPos originPos = origin.getPos();
|
||||
posX += originPos.getX() - monitorPos.getX();
|
||||
posY += originPos.getY() - monitorPos.getY();
|
||||
posZ += originPos.getZ() - monitorPos.getZ();
|
||||
|
||||
// Determine orientation
|
||||
EnumFacing dir = origin.getDirection();
|
||||
EnumFacing front = origin.getFront();
|
||||
float yaw = DirectionUtil.toYawAngle( dir );
|
||||
float pitch = DirectionUtil.toPitchAngle( front );
|
||||
|
||||
GlStateManager.pushMatrix();
|
||||
try
|
||||
{
|
||||
// Setup initial transform
|
||||
GlStateManager.translate( posX + 0.5, posY + 0.5, posZ + 0.5 );
|
||||
GlStateManager.rotate( -yaw, 0.0f, 1.0f, 0.0f );
|
||||
GlStateManager.rotate( pitch, 1.0f, 0.0f, 0.0f );
|
||||
GlStateManager.translate(
|
||||
-0.5 + TileMonitor.RENDER_BORDER + TileMonitor.RENDER_MARGIN,
|
||||
((double)origin.getHeight() - 0.5) - (TileMonitor.RENDER_BORDER + TileMonitor.RENDER_MARGIN),
|
||||
0.5
|
||||
);
|
||||
double xSize = (double)origin.getWidth() - 2.0 * ( TileMonitor.RENDER_MARGIN + TileMonitor.RENDER_BORDER );
|
||||
double ySize = (double)origin.getHeight() - 2.0 * ( TileMonitor.RENDER_MARGIN + TileMonitor.RENDER_BORDER );
|
||||
|
||||
// Get renderers
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
WorldRenderer renderer = tessellator.getWorldRenderer();
|
||||
|
||||
// Get terminal
|
||||
ClientTerminal clientTerminal = (ClientTerminal)origin.getTerminal();
|
||||
Terminal terminal = (clientTerminal != null) ? clientTerminal.getTerminal() : null;
|
||||
redraw = redraw || (clientTerminal != null && clientTerminal.hasTerminalChanged());
|
||||
|
||||
// Draw the contents
|
||||
GlStateManager.depthMask( false );
|
||||
GlStateManager.disableLighting();
|
||||
try
|
||||
{
|
||||
if( terminal != null )
|
||||
{
|
||||
// Allocate display lists
|
||||
if( origin.m_renderDisplayList < 0 )
|
||||
{
|
||||
origin.m_renderDisplayList = GL11.glGenLists( 3 );
|
||||
redraw = true;
|
||||
}
|
||||
|
||||
// Draw a terminal
|
||||
boolean greyscale = !clientTerminal.isColour();
|
||||
int width = terminal.getWidth();
|
||||
int height = terminal.getHeight();
|
||||
int cursorX = terminal.getCursorX();
|
||||
int cursorY = terminal.getCursorY();
|
||||
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer)ComputerCraft.getFixedWidthFontRenderer();
|
||||
|
||||
GlStateManager.pushMatrix();
|
||||
try
|
||||
{
|
||||
double xScale = xSize / (double) ( width * FixedWidthFontRenderer.FONT_WIDTH );
|
||||
double yScale = ySize / (double) ( height * FixedWidthFontRenderer.FONT_HEIGHT );
|
||||
GlStateManager.scale( xScale, -yScale, 1.0 );
|
||||
|
||||
// Draw background
|
||||
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.background );
|
||||
if( redraw )
|
||||
{
|
||||
// Build background display list
|
||||
GL11.glNewList( origin.m_renderDisplayList, GL11.GL_COMPILE );
|
||||
try
|
||||
{
|
||||
double marginXSize = TileMonitor.RENDER_MARGIN / xScale;
|
||||
double marginYSize = TileMonitor.RENDER_MARGIN / yScale;
|
||||
double marginSquash = marginYSize / (double) FixedWidthFontRenderer.FONT_HEIGHT;
|
||||
|
||||
// Top and bottom margins
|
||||
GL11.glPushMatrix();
|
||||
try
|
||||
{
|
||||
GL11.glScaled( 1.0, marginSquash, 1.0 );
|
||||
GL11.glTranslated( 0.0, -marginYSize / marginSquash, 0.0 );
|
||||
fontRenderer.drawStringBackgroundPart( 0, 0, terminal.getBackgroundColourLine( 0 ), marginXSize, marginXSize, greyscale );
|
||||
GL11.glTranslated( 0.0, ( marginYSize + height * FixedWidthFontRenderer.FONT_HEIGHT ) / marginSquash, 0.0 );
|
||||
fontRenderer.drawStringBackgroundPart( 0, 0, terminal.getBackgroundColourLine( height - 1 ), marginXSize, marginXSize, greyscale );
|
||||
}
|
||||
finally
|
||||
{
|
||||
GL11.glPopMatrix();
|
||||
}
|
||||
|
||||
// Backgrounds
|
||||
for( int y = 0; y < height; ++y )
|
||||
{
|
||||
fontRenderer.drawStringBackgroundPart(
|
||||
0, FixedWidthFontRenderer.FONT_HEIGHT * y,
|
||||
terminal.getBackgroundColourLine( y ),
|
||||
marginXSize, marginXSize,
|
||||
greyscale
|
||||
);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
GL11.glEndList();
|
||||
}
|
||||
}
|
||||
GlStateManager.callList( origin.m_renderDisplayList );
|
||||
|
||||
// Draw text
|
||||
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.font );
|
||||
if( redraw )
|
||||
{
|
||||
// Build text display list
|
||||
GL11.glNewList( origin.m_renderDisplayList + 1, GL11.GL_COMPILE );
|
||||
try
|
||||
{
|
||||
// Lines
|
||||
for( int y = 0; y < height; ++y )
|
||||
{
|
||||
fontRenderer.drawStringTextPart(
|
||||
0, FixedWidthFontRenderer.FONT_HEIGHT * y,
|
||||
terminal.getLine( y ),
|
||||
terminal.getTextColourLine( y ),
|
||||
greyscale
|
||||
);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
GL11.glEndList();
|
||||
}
|
||||
}
|
||||
GlStateManager.callList( origin.m_renderDisplayList + 1 );
|
||||
|
||||
// Draw cursor
|
||||
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.font );
|
||||
if( redraw )
|
||||
{
|
||||
// Build cursor display list
|
||||
GL11.glNewList( origin.m_renderDisplayList + 2, GL11.GL_COMPILE );
|
||||
try
|
||||
{
|
||||
// Cursor
|
||||
if( terminal.getCursorBlink() && cursorX >= 0 && cursorX < width && cursorY >= 0 && cursorY < height )
|
||||
{
|
||||
TextBuffer cursor = new TextBuffer( "_" );
|
||||
TextBuffer cursorColour = new TextBuffer( "0123456789abcdef".charAt( terminal.getTextColour() ), 1 );
|
||||
fontRenderer.drawString(
|
||||
cursor,
|
||||
FixedWidthFontRenderer.FONT_WIDTH * cursorX,
|
||||
FixedWidthFontRenderer.FONT_HEIGHT * cursorY,
|
||||
cursorColour, null,
|
||||
0, 0,
|
||||
greyscale
|
||||
);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
GL11.glEndList();
|
||||
}
|
||||
}
|
||||
if( ComputerCraft.getGlobalCursorBlink() )
|
||||
{
|
||||
GlStateManager.callList( origin.m_renderDisplayList + 2 );
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.popMatrix();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Draw a big black quad
|
||||
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.background );
|
||||
renderer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR );
|
||||
Colour colour = Colour.Black;
|
||||
renderer.pos( -TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 0.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( xSize + TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 1.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( xSize + TileMonitor.RENDER_MARGIN, TileMonitor.RENDER_MARGIN, 0.0D ).tex( 1.0, 0.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( -TileMonitor.RENDER_MARGIN, TileMonitor.RENDER_MARGIN, 0.0D ).tex( 0.0, 0.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( -TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 0.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
tessellator.draw();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.depthMask( true );
|
||||
GlStateManager.enableLighting();
|
||||
}
|
||||
|
||||
// Draw the depth blocker
|
||||
GlStateManager.colorMask( false, false, false, false );
|
||||
try
|
||||
{
|
||||
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.background );
|
||||
renderer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR );
|
||||
Colour colour = Colour.Black;
|
||||
renderer.pos( -TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 0.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( xSize + TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 1.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( xSize + TileMonitor.RENDER_MARGIN, TileMonitor.RENDER_MARGIN, 0.0D ).tex( 1.0, 0.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( -TileMonitor.RENDER_MARGIN, TileMonitor.RENDER_MARGIN, 0.0D ).tex( 0.0, 0.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
renderer.pos( -TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 0.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
|
||||
tessellator.draw();
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.colorMask( true, true, true, true );
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
|
||||
GlStateManager.popMatrix();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.render;
|
||||
|
||||
import dan200.computercraft.api.turtle.ITurtleUpgrade;
|
||||
import dan200.computercraft.api.turtle.TurtleSide;
|
||||
import dan200.computercraft.shared.computer.core.ComputerFamily;
|
||||
import dan200.computercraft.shared.computer.core.IComputer;
|
||||
import dan200.computercraft.shared.turtle.blocks.TileTurtle;
|
||||
import dan200.computercraft.shared.turtle.entity.TurtleVisionCamera;
|
||||
import dan200.computercraft.shared.util.Colour;
|
||||
import dan200.computercraft.shared.util.Holiday;
|
||||
import dan200.computercraft.shared.util.HolidayUtil;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.FontRenderer;
|
||||
import net.minecraft.client.renderer.GlStateManager;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.renderer.WorldRenderer;
|
||||
import net.minecraft.client.renderer.block.model.BakedQuad;
|
||||
import net.minecraft.client.renderer.entity.RenderManager;
|
||||
import net.minecraft.client.renderer.texture.TextureMap;
|
||||
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
|
||||
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
|
||||
import net.minecraft.client.resources.model.IBakedModel;
|
||||
import net.minecraft.client.resources.model.ModelManager;
|
||||
import net.minecraft.client.resources.model.ModelResourceLocation;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.util.*;
|
||||
import net.minecraftforge.client.ForgeHooksClient;
|
||||
import net.minecraftforge.client.model.IFlexibleBakedModel;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import javax.vecmath.Matrix4f;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurtle>
|
||||
{
|
||||
private static ModelResourceLocation NORMAL_TURTLE_MODEL = new ModelResourceLocation( "computercraft:CC-Turtle", "inventory" );
|
||||
private static ModelResourceLocation ADVANCED_TURTLE_MODEL = new ModelResourceLocation( "computercraft:CC-TurtleAdvanced", "inventory" );
|
||||
private static ModelResourceLocation[] COLOUR_TURTLE_MODELS = new ModelResourceLocation[] {
|
||||
new ModelResourceLocation( "computercraft:turtle_black", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_red", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_green", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_brown", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_blue", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_purple", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_cyan", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_lightGrey", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_grey", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_pink", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_lime", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_yellow", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_lightBlue", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_magenta", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_orange", "inventory" ),
|
||||
new ModelResourceLocation( "computercraft:turtle_white", "inventory" ),
|
||||
};
|
||||
private static ModelResourceLocation BEGINNER_TURTLE_MODEL = new ModelResourceLocation( "computercraftedu:CC-TurtleJunior", "inventory" );
|
||||
private static ModelResourceLocation[] BEGINNER_TURTLE_COLOUR_MODELS = new ModelResourceLocation[] {
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_black", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_red", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_green", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_brown", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_blue", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_purple", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_cyan", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_lightGrey", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_grey", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_pink", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_lime", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_yellow", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_lightBlue", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_magenta", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_orange", "inventory" ),
|
||||
new ModelResourceLocation( "computercraftedu:turtleJunior_white", "inventory" ),
|
||||
};
|
||||
private static ModelResourceLocation ELF_OVERLAY_MODEL = new ModelResourceLocation( "computercraft:turtle_elf_overlay", "inventory" );
|
||||
|
||||
public TileEntityTurtleRenderer()
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderTileEntityAt( TileTurtle tileEntity, double posX, double posY, double posZ, float f, int i )
|
||||
{
|
||||
if( tileEntity != null )
|
||||
{
|
||||
// Check the turtle isn't first person
|
||||
Entity viewEntity = Minecraft.getMinecraft().getRenderViewEntity();
|
||||
if( viewEntity != null && viewEntity instanceof TurtleVisionCamera )
|
||||
{
|
||||
TurtleVisionCamera camera = (TurtleVisionCamera)viewEntity;
|
||||
if( camera.getTurtle() == tileEntity.getAccess() )
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Render the turtle
|
||||
renderTurtleAt( tileEntity, posX, posY, posZ, f, i );
|
||||
}
|
||||
}
|
||||
|
||||
public static ModelResourceLocation getTurtleModel( ComputerFamily family, Colour colour )
|
||||
{
|
||||
switch( family )
|
||||
{
|
||||
case Normal:
|
||||
default:
|
||||
{
|
||||
if( colour != null )
|
||||
{
|
||||
return COLOUR_TURTLE_MODELS[ colour.ordinal() ];
|
||||
}
|
||||
else
|
||||
{
|
||||
return NORMAL_TURTLE_MODEL;
|
||||
}
|
||||
}
|
||||
case Advanced:
|
||||
{
|
||||
if( colour != null )
|
||||
{
|
||||
return COLOUR_TURTLE_MODELS[ colour.ordinal() ];
|
||||
}
|
||||
else
|
||||
{
|
||||
return ADVANCED_TURTLE_MODEL;
|
||||
}
|
||||
}
|
||||
case Beginners:
|
||||
{
|
||||
if( colour != null )
|
||||
{
|
||||
return BEGINNER_TURTLE_COLOUR_MODELS[ colour.ordinal() ];
|
||||
}
|
||||
else
|
||||
{
|
||||
return BEGINNER_TURTLE_MODEL;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static ModelResourceLocation getTurtleOverlayModel( ComputerFamily family, ResourceLocation overlay, boolean christmas )
|
||||
{
|
||||
if( overlay != null )
|
||||
{
|
||||
return new ModelResourceLocation( overlay, "inventory" );
|
||||
}
|
||||
else if( christmas && family != ComputerFamily.Beginners )
|
||||
{
|
||||
return ELF_OVERLAY_MODEL;
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void renderTurtleAt( TileTurtle turtle, double posX, double posY, double posZ, float f, int i )
|
||||
{
|
||||
GlStateManager.pushMatrix();
|
||||
try
|
||||
{
|
||||
// Setup the transform
|
||||
Vec3 offset;
|
||||
float yaw;
|
||||
if( turtle != null )
|
||||
{
|
||||
offset = turtle.getRenderOffset( f );
|
||||
yaw = turtle.getRenderYaw( f );
|
||||
}
|
||||
else
|
||||
{
|
||||
offset = new Vec3( 0.0, 0.0, 0.0 );
|
||||
yaw = 0.0f;
|
||||
}
|
||||
GlStateManager.translate( posX + offset.xCoord, posY + offset.yCoord, posZ + offset.zCoord );
|
||||
|
||||
// Render the label
|
||||
IComputer computer = (turtle != null) ? turtle.getComputer() : null;
|
||||
String label = (computer != null) ? computer.getLabel() : null;
|
||||
if( label != null )
|
||||
{
|
||||
renderLabel( turtle.getAccess().getPosition(), label );
|
||||
}
|
||||
|
||||
// Render the turtle
|
||||
GlStateManager.translate( 0.5f, 0.0f, 0.5f );
|
||||
GlStateManager.rotate( 180.0f - yaw, 0.0f, 1.0f, 0.0f );
|
||||
GlStateManager.translate( -0.5f, 0.0f, -0.5f );
|
||||
|
||||
// Render the turtle
|
||||
Colour colour;
|
||||
ComputerFamily family;
|
||||
ResourceLocation overlay;
|
||||
if( turtle != null )
|
||||
{
|
||||
colour = turtle.getColour();
|
||||
family = turtle.getFamily();
|
||||
overlay = turtle.getOverlay();
|
||||
}
|
||||
else
|
||||
{
|
||||
colour = null;
|
||||
family = ComputerFamily.Normal;
|
||||
overlay = null;
|
||||
}
|
||||
renderModel( getTurtleModel( family, colour ) );
|
||||
|
||||
// Render the overlay
|
||||
ModelResourceLocation overlayModel = getTurtleOverlayModel(
|
||||
family,
|
||||
overlay,
|
||||
HolidayUtil.getCurrentHoliday() == Holiday.Christmas
|
||||
);
|
||||
if( overlayModel != null )
|
||||
{
|
||||
GlStateManager.disableCull();
|
||||
GlStateManager.enableBlend();
|
||||
GlStateManager.blendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA );
|
||||
try
|
||||
{
|
||||
renderModel( overlayModel );
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.disableBlend();
|
||||
GlStateManager.enableCull();
|
||||
}
|
||||
}
|
||||
|
||||
// Render the upgrades
|
||||
if( turtle != null )
|
||||
{
|
||||
renderUpgrade( turtle, TurtleSide.Left, f );
|
||||
renderUpgrade( turtle, TurtleSide.Right, f );
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.popMatrix();
|
||||
}
|
||||
}
|
||||
|
||||
private void renderUpgrade( TileTurtle turtle, TurtleSide side, float f )
|
||||
{
|
||||
ITurtleUpgrade upgrade = turtle.getUpgrade( side );
|
||||
if( upgrade != null )
|
||||
{
|
||||
GlStateManager.pushMatrix();
|
||||
try
|
||||
{
|
||||
float toolAngle = turtle.getToolRenderAngle( side, f );
|
||||
GlStateManager.translate( 0.0f, 0.5f, 0.5f );
|
||||
GlStateManager.rotate( -toolAngle, 1.0f, 0.0f, 0.0f );
|
||||
GlStateManager.translate( 0.0f, -0.5f, -0.5f );
|
||||
|
||||
Pair<IBakedModel, Matrix4f> pair = upgrade.getModel( turtle.getAccess(), side );
|
||||
if( pair != null )
|
||||
{
|
||||
if( pair.getRight() != null )
|
||||
{
|
||||
ForgeHooksClient.multiplyCurrentGlMatrix( pair.getRight() );
|
||||
}
|
||||
if( pair.getLeft() != null )
|
||||
{
|
||||
renderModel( pair.getLeft() );
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.popMatrix();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void renderModel( ModelResourceLocation modelLocation )
|
||||
{
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
ModelManager modelManager = mc.getRenderItem().getItemModelMesher().getModelManager();
|
||||
renderModel( modelManager.getModel( modelLocation ) );
|
||||
}
|
||||
|
||||
private void renderModel( IBakedModel model )
|
||||
{
|
||||
if( model instanceof IFlexibleBakedModel )
|
||||
{
|
||||
renderModel( (IFlexibleBakedModel) model );
|
||||
}
|
||||
else
|
||||
{
|
||||
renderModel( new IFlexibleBakedModel.Wrapper( model, DefaultVertexFormats.ITEM ) );
|
||||
}
|
||||
}
|
||||
|
||||
private void renderModel( IFlexibleBakedModel model )
|
||||
{
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
WorldRenderer renderer = tessellator.getWorldRenderer();
|
||||
mc.getTextureManager().bindTexture( TextureMap.locationBlocksTexture );
|
||||
renderer.begin( GL11.GL_QUADS, model.getFormat() );
|
||||
for( EnumFacing facing : EnumFacing.VALUES )
|
||||
{
|
||||
renderQuads( renderer, model.getFaceQuads( facing ) );
|
||||
}
|
||||
renderQuads( renderer, model.getGeneralQuads() );
|
||||
tessellator.draw();
|
||||
}
|
||||
|
||||
private void renderQuads( WorldRenderer renderer, List quads )
|
||||
{
|
||||
int color = 0xFFFFFFFF;
|
||||
Iterator it = quads.iterator();
|
||||
while( it.hasNext() )
|
||||
{
|
||||
BakedQuad quad = (BakedQuad)it.next();
|
||||
net.minecraftforge.client.model.pipeline.LightUtil.renderQuadColor( renderer, quad, color );
|
||||
}
|
||||
}
|
||||
|
||||
private void renderLabel( BlockPos position, String label )
|
||||
{
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
MovingObjectPosition mop = mc.objectMouseOver;
|
||||
if( mop != null && mop.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK && mop.getBlockPos().equals( position ) )
|
||||
{
|
||||
RenderManager renderManager = mc.getRenderManager();
|
||||
FontRenderer fontrenderer = renderManager.getFontRenderer();
|
||||
float scale = 0.016666668F * 1.6f;
|
||||
|
||||
GlStateManager.pushMatrix();
|
||||
GlStateManager.disableLighting();
|
||||
GlStateManager.enableBlend();
|
||||
GlStateManager.blendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA );
|
||||
try
|
||||
{
|
||||
GlStateManager.translate( 0.5f, 1.25f, 0.5f );
|
||||
GlStateManager.rotate( -renderManager.playerViewY, 0.0F, 1.0F, 0.0F );
|
||||
GlStateManager.rotate( renderManager.playerViewX, 1.0F, 0.0F, 0.0F );
|
||||
GlStateManager.scale( -scale, -scale, scale );
|
||||
|
||||
int yOffset = 0;
|
||||
int xOffset = fontrenderer.getStringWidth( label ) / 2;
|
||||
|
||||
// Draw background
|
||||
GlStateManager.depthMask( false );
|
||||
GlStateManager.disableDepth();
|
||||
try
|
||||
{
|
||||
// Quad
|
||||
GlStateManager.disableTexture2D();
|
||||
try
|
||||
{
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
WorldRenderer renderer = tessellator.getWorldRenderer();
|
||||
renderer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR );
|
||||
renderer.pos( (double) ( -xOffset - 1 ), (double) ( -1 + yOffset ), 0.0D ).color( 0.0F, 0.0F, 0.0F, 0.25F ).endVertex();
|
||||
renderer.pos( (double) ( -xOffset - 1 ), (double) ( 8 + yOffset ), 0.0D ).color( 0.0F, 0.0F, 0.0F, 0.25F ).endVertex();
|
||||
renderer.pos( (double) ( xOffset + 1 ), (double) ( 8 + yOffset ), 0.0D ).color( 0.0F, 0.0F, 0.0F, 0.25F ).endVertex();
|
||||
renderer.pos( (double) ( xOffset + 1 ), (double) ( -1 + yOffset ), 0.0D ).color( 0.0F, 0.0F, 0.0F, 0.25F ).endVertex();
|
||||
tessellator.draw();
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.enableTexture2D();
|
||||
}
|
||||
|
||||
// Text
|
||||
fontrenderer.drawString( label, -fontrenderer.getStringWidth( label ) / 2, yOffset, 0x20ffffff );
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.enableDepth();
|
||||
GlStateManager.depthMask( true );
|
||||
}
|
||||
|
||||
// Draw foreground text
|
||||
fontrenderer.drawString( label, -fontrenderer.getStringWidth( label ) / 2, yOffset, -1 );
|
||||
}
|
||||
finally
|
||||
{
|
||||
GlStateManager.disableBlend();
|
||||
GlStateManager.enableLighting();
|
||||
GlStateManager.popMatrix();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package dan200.computercraft.client.render;
|
||||
|
||||
import net.minecraft.client.renderer.block.model.BakedQuad;
|
||||
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
|
||||
import net.minecraft.client.renderer.vertex.VertexFormat;
|
||||
import net.minecraft.client.renderer.vertex.VertexFormatElement;
|
||||
import net.minecraft.client.resources.model.IBakedModel;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraftforge.client.model.IFlexibleBakedModel;
|
||||
|
||||
import javax.vecmath.Matrix4f;
|
||||
import javax.vecmath.Point3f;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class TurtleMultiModel implements IFlexibleBakedModel
|
||||
{
|
||||
private IFlexibleBakedModel m_baseModel;
|
||||
private IFlexibleBakedModel m_overlayModel;
|
||||
private IFlexibleBakedModel m_leftUpgradeModel;
|
||||
private IFlexibleBakedModel m_rightUpgradeModel;
|
||||
|
||||
private List<BakedQuad> m_generalQuads;
|
||||
private List<BakedQuad>[] m_faceQuads;
|
||||
|
||||
public TurtleMultiModel( IBakedModel baseModel, IBakedModel overlayModel, IBakedModel leftUpgradeModel, Matrix4f leftUpgradeTransform, IBakedModel rightUpgradeModel, Matrix4f rightUpgradeTransform )
|
||||
{
|
||||
// Get the models
|
||||
m_baseModel = makeFlexible( baseModel );
|
||||
m_overlayModel = makeFlexible( overlayModel );
|
||||
m_leftUpgradeModel = makeFlexible( leftUpgradeModel );
|
||||
m_rightUpgradeModel = makeFlexible( rightUpgradeModel );
|
||||
|
||||
// Bake the quads
|
||||
m_generalQuads = new ArrayList<BakedQuad>();
|
||||
m_generalQuads.addAll( m_baseModel.getGeneralQuads() );
|
||||
if( m_overlayModel != null )
|
||||
{
|
||||
m_generalQuads.addAll( m_overlayModel.getGeneralQuads() );
|
||||
}
|
||||
if( m_leftUpgradeModel != null )
|
||||
{
|
||||
m_generalQuads.addAll( transformQuads( m_leftUpgradeModel.getFormat(), m_leftUpgradeModel.getGeneralQuads(), leftUpgradeTransform ) );
|
||||
}
|
||||
if( m_rightUpgradeModel != null )
|
||||
{
|
||||
m_generalQuads.addAll( transformQuads( m_rightUpgradeModel.getFormat(), m_rightUpgradeModel.getGeneralQuads(), rightUpgradeTransform ) );
|
||||
}
|
||||
|
||||
m_faceQuads = new List[ EnumFacing.VALUES.length ];
|
||||
for( EnumFacing facing : EnumFacing.VALUES )
|
||||
{
|
||||
List<BakedQuad> faces = new ArrayList<BakedQuad>();
|
||||
faces.addAll( m_baseModel.getFaceQuads( facing ) );
|
||||
if( m_overlayModel != null )
|
||||
{
|
||||
faces.addAll( m_overlayModel.getFaceQuads( facing ) );
|
||||
}
|
||||
if( m_leftUpgradeModel != null )
|
||||
{
|
||||
faces.addAll( transformQuads( m_leftUpgradeModel.getFormat(), m_leftUpgradeModel.getFaceQuads( facing ), leftUpgradeTransform ) );
|
||||
}
|
||||
if( m_rightUpgradeModel != null )
|
||||
{
|
||||
faces.addAll( transformQuads( m_rightUpgradeModel.getFormat(), m_rightUpgradeModel.getFaceQuads( facing ), rightUpgradeTransform ) );
|
||||
}
|
||||
m_faceQuads[ facing.getIndex() ] = faces;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BakedQuad> getFaceQuads( EnumFacing side )
|
||||
{
|
||||
return m_faceQuads[ side.getIndex() ];
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BakedQuad> getGeneralQuads()
|
||||
{
|
||||
return m_generalQuads;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAmbientOcclusion()
|
||||
{
|
||||
return m_baseModel.isAmbientOcclusion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGui3d()
|
||||
{
|
||||
return m_baseModel.isGui3d();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isBuiltInRenderer()
|
||||
{
|
||||
return m_baseModel.isBuiltInRenderer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TextureAtlasSprite getParticleTexture()
|
||||
{
|
||||
return m_baseModel.getParticleTexture();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemCameraTransforms getItemCameraTransforms()
|
||||
{
|
||||
return m_baseModel.getItemCameraTransforms();
|
||||
}
|
||||
|
||||
@Override
|
||||
public VertexFormat getFormat()
|
||||
{
|
||||
return m_baseModel.getFormat();
|
||||
}
|
||||
|
||||
private List<BakedQuad> transformQuads( VertexFormat format, List<BakedQuad> input, Matrix4f transform )
|
||||
{
|
||||
if( transform == null || input.size() == 0 )
|
||||
{
|
||||
return input;
|
||||
}
|
||||
else
|
||||
{
|
||||
List<BakedQuad> output = new ArrayList<BakedQuad>( input.size() );
|
||||
for( int i=0; i<input.size(); ++i )
|
||||
{
|
||||
BakedQuad quad = input.get( i );
|
||||
output.add( transformQuad( format, quad, transform ) );
|
||||
}
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
||||
private BakedQuad transformQuad( VertexFormat format, BakedQuad quad, Matrix4f transform )
|
||||
{
|
||||
int[] vertexData = quad.getVertexData().clone();
|
||||
BakedQuad copy = new BakedQuad( vertexData, quad.getTintIndex(), quad.getFace() );
|
||||
int offset = 0;
|
||||
for( int i=0; i<format.getElementCount(); ++i ) // For each vertex element
|
||||
{
|
||||
VertexFormatElement element = format.getElement( i );
|
||||
if( element.isPositionElement() &&
|
||||
element.getType() == VertexFormatElement.EnumType.FLOAT &&
|
||||
element.getElementCount() == 3 ) // When we find a position element
|
||||
{
|
||||
for( int j=0; j<4; ++j ) // For each corner of the quad
|
||||
{
|
||||
int start = offset + j * format.getNextOffset();
|
||||
if( (start % 4) == 0 )
|
||||
{
|
||||
start = start / 4;
|
||||
|
||||
// Extract the position
|
||||
Point3f pos = new Point3f(
|
||||
Float.intBitsToFloat( vertexData[ start ] ),
|
||||
Float.intBitsToFloat( vertexData[ start + 1 ] ),
|
||||
Float.intBitsToFloat( vertexData[ start + 2 ] )
|
||||
);
|
||||
|
||||
// Transform the position
|
||||
transform.transform( pos );
|
||||
|
||||
// Insert the position
|
||||
vertexData[ start ] = Float.floatToRawIntBits( pos.x );
|
||||
vertexData[ start + 1 ] = Float.floatToRawIntBits( pos.y );
|
||||
vertexData[ start + 2 ] = Float.floatToRawIntBits( pos.z );
|
||||
}
|
||||
}
|
||||
}
|
||||
offset += element.getSize();
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
private IFlexibleBakedModel makeFlexible( IBakedModel model )
|
||||
{
|
||||
if( model == null )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
else if( model instanceof IFlexibleBakedModel )
|
||||
{
|
||||
return (IFlexibleBakedModel)model;
|
||||
}
|
||||
else
|
||||
{
|
||||
return new IFlexibleBakedModel.Wrapper( model, DefaultVertexFormats.ITEM );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.turtle.ITurtleUpgrade;
|
||||
import dan200.computercraft.api.turtle.TurtleSide;
|
||||
import dan200.computercraft.shared.computer.core.ComputerFamily;
|
||||
import dan200.computercraft.shared.turtle.items.ItemTurtleBase;
|
||||
import dan200.computercraft.shared.turtle.items.TurtleItemFactory;
|
||||
import dan200.computercraft.shared.util.Colour;
|
||||
import dan200.computercraft.shared.util.Holiday;
|
||||
import dan200.computercraft.shared.util.HolidayUtil;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.resources.IResourceManager;
|
||||
import net.minecraft.client.resources.IResourceManagerReloadListener;
|
||||
import net.minecraft.client.resources.model.IBakedModel;
|
||||
import net.minecraft.client.resources.model.ModelManager;
|
||||
import net.minecraft.client.resources.model.ModelResourceLocation;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.client.model.ISmartItemModel;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import javax.vecmath.Matrix4f;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
public class TurtleSmartItemModel implements ISmartItemModel, IResourceManagerReloadListener
|
||||
{
|
||||
private static class TurtleModelCombination
|
||||
{
|
||||
public final ComputerFamily m_family;
|
||||
public final Colour m_colour;
|
||||
public final ITurtleUpgrade m_leftUpgrade;
|
||||
public final ITurtleUpgrade m_rightUpgrade;
|
||||
public final ResourceLocation m_overlay;
|
||||
public final boolean m_christmas;
|
||||
|
||||
public TurtleModelCombination( ComputerFamily family, Colour colour, ITurtleUpgrade leftUpgrade, ITurtleUpgrade rightUpgrade, ResourceLocation overlay, boolean christmas )
|
||||
{
|
||||
m_family = family;
|
||||
m_colour = colour;
|
||||
m_leftUpgrade = leftUpgrade;
|
||||
m_rightUpgrade = rightUpgrade;
|
||||
m_overlay = overlay;
|
||||
m_christmas = christmas;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals( Object other )
|
||||
{
|
||||
if( other == this ) {
|
||||
return true;
|
||||
}
|
||||
if( other instanceof TurtleModelCombination ) {
|
||||
TurtleModelCombination otherCombo = (TurtleModelCombination)other;
|
||||
if( otherCombo.m_family == m_family &&
|
||||
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 )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode()
|
||||
{
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + m_family.hashCode();
|
||||
result = prime * result + (m_colour != null ? m_colour.hashCode() : 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);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private ItemStack m_defaultItem;
|
||||
private HashMap<TurtleModelCombination, IBakedModel> m_cachedModels;
|
||||
|
||||
public TurtleSmartItemModel()
|
||||
{
|
||||
m_defaultItem = TurtleItemFactory.create( -1, null, null, ComputerFamily.Normal, null, null, 0, null );
|
||||
m_cachedModels = new HashMap<TurtleModelCombination, IBakedModel>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResourceManagerReload( IResourceManager resourceManager )
|
||||
{
|
||||
m_cachedModels.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBakedModel handleItemState( ItemStack stack )
|
||||
{
|
||||
ItemTurtleBase turtle = (ItemTurtleBase) stack.getItem();
|
||||
ComputerFamily family = turtle.getFamily( stack );
|
||||
Colour colour = turtle.getColour( stack );
|
||||
ITurtleUpgrade leftUpgrade = turtle.getUpgrade( stack, TurtleSide.Left );
|
||||
ITurtleUpgrade rightUpgrade = turtle.getUpgrade( stack, TurtleSide.Right );
|
||||
ResourceLocation overlay = turtle.getOverlay( stack );
|
||||
boolean christmas = HolidayUtil.getCurrentHoliday() == Holiday.Christmas;
|
||||
TurtleModelCombination combo = new TurtleModelCombination( family, colour, leftUpgrade, rightUpgrade, overlay, christmas );
|
||||
if( m_cachedModels.containsKey( combo ) )
|
||||
{
|
||||
return m_cachedModels.get( combo );
|
||||
}
|
||||
else
|
||||
{
|
||||
IBakedModel model = buildModel( combo );
|
||||
m_cachedModels.put( combo, model );
|
||||
return model;
|
||||
}
|
||||
}
|
||||
|
||||
private IBakedModel buildModel( TurtleModelCombination combo )
|
||||
{
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
ModelManager modelManager = mc.getRenderItem().getItemModelMesher().getModelManager();
|
||||
ModelResourceLocation baseModelLocation = TileEntityTurtleRenderer.getTurtleModel( combo.m_family, combo.m_colour );
|
||||
ModelResourceLocation overlayModelLocation = TileEntityTurtleRenderer.getTurtleOverlayModel( combo.m_family, combo.m_overlay, combo.m_christmas );
|
||||
IBakedModel baseModel = modelManager.getModel( baseModelLocation );
|
||||
IBakedModel overlayModel = (overlayModelLocation != null) ? modelManager.getModel( baseModelLocation ) : null;
|
||||
Pair<IBakedModel, Matrix4f> leftModel = (combo.m_leftUpgrade != null) ? combo.m_leftUpgrade.getModel( null, TurtleSide.Left ) : null;
|
||||
Pair<IBakedModel, Matrix4f> rightModel = (combo.m_rightUpgrade != null) ? combo.m_rightUpgrade.getModel( null, TurtleSide.Right ) : null;
|
||||
if( leftModel != null && rightModel != null )
|
||||
{
|
||||
return new TurtleMultiModel( baseModel, overlayModel, leftModel.getLeft(), leftModel.getRight(), rightModel.getLeft(), rightModel.getRight() );
|
||||
}
|
||||
else if( leftModel != null )
|
||||
{
|
||||
return new TurtleMultiModel( baseModel, overlayModel, leftModel.getLeft(), leftModel.getRight(), null, null );
|
||||
}
|
||||
else if( rightModel != null )
|
||||
{
|
||||
return new TurtleMultiModel( baseModel, overlayModel, null, null, rightModel.getLeft(), rightModel.getRight() );
|
||||
}
|
||||
else if( overlayModel != null )
|
||||
{
|
||||
return new TurtleMultiModel( baseModel, overlayModel, null, null, null, null );
|
||||
}
|
||||
else
|
||||
{
|
||||
return baseModel;
|
||||
}
|
||||
}
|
||||
|
||||
// These should not be called:
|
||||
|
||||
@Override
|
||||
public List getFaceQuads( EnumFacing facing )
|
||||
{
|
||||
return getDefaultModel().getFaceQuads( facing );
|
||||
}
|
||||
|
||||
@Override
|
||||
public List getGeneralQuads()
|
||||
{
|
||||
return getDefaultModel().getGeneralQuads();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAmbientOcclusion()
|
||||
{
|
||||
return getDefaultModel().isAmbientOcclusion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGui3d()
|
||||
{
|
||||
return getDefaultModel().isGui3d();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isBuiltInRenderer()
|
||||
{
|
||||
return getDefaultModel().isBuiltInRenderer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TextureAtlasSprite getParticleTexture()
|
||||
{
|
||||
return getDefaultModel().getParticleTexture();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemCameraTransforms getItemCameraTransforms()
|
||||
{
|
||||
return getDefaultModel().getItemCameraTransforms();
|
||||
}
|
||||
|
||||
private IBakedModel getDefaultModel()
|
||||
{
|
||||
return handleItemState( m_defaultItem );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
|
||||
// Contributed by Nia
|
||||
// Based on LuaBit (http://luaforge.net/projects/bit)
|
||||
|
||||
public class BitAPI implements ILuaAPI
|
||||
{
|
||||
private static final int BNOT = 0;
|
||||
private static final int BAND = 1;
|
||||
private static final int BOR = 2;
|
||||
private static final int BXOR = 3;
|
||||
private static final int BRSHIFT = 4;
|
||||
private static final int BLSHIFT = 5;
|
||||
private static final int BLOGIC_RSHIFT = 6;
|
||||
|
||||
private static int checkInt( Object o, int count ) throws LuaException
|
||||
{
|
||||
if( o instanceof Number )
|
||||
{
|
||||
return (int)(((Number)o).longValue());
|
||||
}
|
||||
else
|
||||
{
|
||||
if( count == 2 )
|
||||
{
|
||||
throw new LuaException( "Expected number, number" );
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new LuaException( "Expected number" );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public BitAPI( IAPIEnvironment _environment )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"bit"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startup( )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void advance( double _dt )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown( )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames() {
|
||||
return new String[] {
|
||||
"bnot", "band", "bor", "bxor",
|
||||
"brshift", "blshift", "blogic_rshift"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException
|
||||
{
|
||||
Object a = args.length>0?args[0]:null;
|
||||
Object b = args.length>1?args[1]:null;
|
||||
|
||||
int ret = 0;
|
||||
switch(method) {
|
||||
case BNOT:
|
||||
ret = ~checkInt(a, 1);
|
||||
break;
|
||||
case BAND:
|
||||
ret = checkInt(a, 2) & checkInt(b, 2);
|
||||
break;
|
||||
case BOR:
|
||||
ret = checkInt(a, 2) | checkInt(b, 2);
|
||||
break;
|
||||
case BXOR:
|
||||
ret = checkInt(a, 2) ^ checkInt(b, 2);
|
||||
break;
|
||||
case BRSHIFT:
|
||||
ret = checkInt(a, 2) >> checkInt(b, 2);
|
||||
break;
|
||||
case BLSHIFT:
|
||||
ret = checkInt(a, 2) << checkInt(b, 2);
|
||||
break;
|
||||
case BLOGIC_RSHIFT:
|
||||
ret = checkInt(a, 2) >>> checkInt(b, 2);
|
||||
break;
|
||||
}
|
||||
|
||||
return new Object[]{ ret&0xFFFFFFFFL };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.ILuaObject;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.core.terminal.TextBuffer;
|
||||
|
||||
public class BufferAPI implements ILuaAPI
|
||||
{
|
||||
private static class BufferLuaObject implements ILuaObject
|
||||
{
|
||||
private TextBuffer m_buffer;
|
||||
|
||||
public BufferLuaObject( TextBuffer buffer )
|
||||
{
|
||||
m_buffer = buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"len",
|
||||
"tostring",
|
||||
"read",
|
||||
"write",
|
||||
"fill"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] arguments ) throws LuaException, InterruptedException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// len
|
||||
return new Object[] { m_buffer.length() };
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// tostring
|
||||
return new Object[] { m_buffer.toString() };
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// read
|
||||
int start = 0;
|
||||
if( arguments.length >= 1 && (arguments[0] != null) )
|
||||
{
|
||||
if( !(arguments[0] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected number" );
|
||||
}
|
||||
start = ((Number)arguments[1]).intValue() - 1;
|
||||
}
|
||||
int end = m_buffer.length();
|
||||
if( arguments.length >= 2 && (arguments[1] != null) )
|
||||
{
|
||||
if( !(arguments[1] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected number, number" );
|
||||
}
|
||||
end = ((Number)arguments[1]).intValue();
|
||||
}
|
||||
return new Object[] { m_buffer.read( start, end ) };
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
// write
|
||||
if( arguments.length < 1 || !(arguments[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String text = (String)(arguments[0]);
|
||||
int start = 0;
|
||||
if( arguments.length >= 2 && (arguments[1] != null) )
|
||||
{
|
||||
if( !(arguments[1] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected string, number" );
|
||||
}
|
||||
start = ((Number)arguments[1]).intValue() - 1;
|
||||
}
|
||||
int end = start + text.length();
|
||||
if( arguments.length >= 3 && (arguments[2] != null) )
|
||||
{
|
||||
if( !(arguments[2] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected string, number, number" );
|
||||
}
|
||||
end = ((Number)arguments[2]).intValue();
|
||||
}
|
||||
m_buffer.write( text, start, end );
|
||||
return null;
|
||||
}
|
||||
case 4:
|
||||
{
|
||||
// fill
|
||||
if( arguments.length < 1 || !(arguments[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String text = (String)(arguments[0]);
|
||||
int start = 0;
|
||||
if( arguments.length >= 2 && (arguments[1] != null) )
|
||||
{
|
||||
if( !(arguments[1] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected string, number" );
|
||||
}
|
||||
start = ((Number)arguments[1]).intValue() - 1;
|
||||
}
|
||||
int end = m_buffer.length();
|
||||
if( arguments.length >= 3 && (arguments[2] != null) )
|
||||
{
|
||||
if( !(arguments[2] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected string, number, number" );
|
||||
}
|
||||
end = ((Number)arguments[2]).intValue();
|
||||
}
|
||||
m_buffer.fill( text, start, end );
|
||||
return null;
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public BufferAPI( IAPIEnvironment _env )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"buffer"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startup()
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void advance( double _dt )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown()
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"new"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] arguments ) throws LuaException, InterruptedException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
if( arguments.length < 1 || !(arguments[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String text = (String)(arguments[0]);
|
||||
int repetitions = 1;
|
||||
if( arguments.length >= 2 && arguments[1] != null )
|
||||
{
|
||||
if( !(arguments[1] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected string, number" );
|
||||
}
|
||||
repetitions = ((Number)arguments[1]).intValue();
|
||||
if( repetitions < 0 )
|
||||
{
|
||||
throw new LuaException( "Expected positive number" );
|
||||
}
|
||||
}
|
||||
TextBuffer buffer = new TextBuffer( text, repetitions );
|
||||
return new Object[] { new BufferLuaObject( buffer ) };
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,630 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.ILuaObject;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.core.filesystem.FileSystem;
|
||||
import dan200.computercraft.core.filesystem.FileSystemException;
|
||||
import dan200.computercraft.core.filesystem.IMountedFileBinary;
|
||||
import dan200.computercraft.core.filesystem.IMountedFileNormal;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class FSAPI implements ILuaAPI
|
||||
{
|
||||
private IAPIEnvironment m_env;
|
||||
private FileSystem m_fileSystem;
|
||||
|
||||
public FSAPI( IAPIEnvironment _env )
|
||||
{
|
||||
m_env = _env;
|
||||
m_fileSystem = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"fs"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startup( )
|
||||
{
|
||||
m_fileSystem = m_env.getFileSystem();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void advance( double _dt )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown( )
|
||||
{
|
||||
m_fileSystem = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"list",
|
||||
"combine",
|
||||
"getName",
|
||||
"getSize",
|
||||
"exists",
|
||||
"isDir",
|
||||
"isReadOnly",
|
||||
"makeDir",
|
||||
"move",
|
||||
"copy",
|
||||
"delete",
|
||||
"open",
|
||||
"getDrive",
|
||||
"getFreeSpace",
|
||||
"find",
|
||||
"getDir",
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// list
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
try {
|
||||
String[] results = m_fileSystem.list( path );
|
||||
Map<Object,Object> table = new HashMap<Object,Object>();
|
||||
for(int i=0; i<results.length; ++i ) {
|
||||
table.put( i+1, results[i] );
|
||||
}
|
||||
return new Object[] { table };
|
||||
}
|
||||
catch( FileSystemException e )
|
||||
{
|
||||
throw new LuaException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// combine
|
||||
if( args.length != 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string, string" );
|
||||
}
|
||||
String pathA = (String)args[0];
|
||||
String pathB = (String)args[1];
|
||||
return new Object[] { m_fileSystem.combine( pathA, pathB ) };
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// getName
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
return new Object[]{ m_fileSystem.getName( path ) };
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
// getSize
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
try
|
||||
{
|
||||
return new Object[]{ m_fileSystem.getSize( path ) };
|
||||
}
|
||||
catch( FileSystemException e )
|
||||
{
|
||||
throw new LuaException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
case 4:
|
||||
{
|
||||
// exists
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
try {
|
||||
return new Object[]{ m_fileSystem.exists( path ) };
|
||||
} catch( FileSystemException e ) {
|
||||
return new Object[]{ false };
|
||||
}
|
||||
}
|
||||
case 5:
|
||||
{
|
||||
// isDir
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
try {
|
||||
return new Object[]{ m_fileSystem.isDir( path ) };
|
||||
} catch( FileSystemException e ) {
|
||||
return new Object[]{ false };
|
||||
}
|
||||
}
|
||||
case 6:
|
||||
{
|
||||
// isReadOnly
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
try {
|
||||
return new Object[]{ m_fileSystem.isReadOnly( path ) };
|
||||
} catch( FileSystemException e ) {
|
||||
return new Object[]{ false };
|
||||
}
|
||||
}
|
||||
case 7:
|
||||
{
|
||||
// makeDir
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
try {
|
||||
m_fileSystem.makeDir( path );
|
||||
return null;
|
||||
} catch( FileSystemException e ) {
|
||||
throw new LuaException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
case 8:
|
||||
{
|
||||
// move
|
||||
if( args.length != 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string, string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
String dest = (String)args[1];
|
||||
try {
|
||||
m_fileSystem.move( path, dest );
|
||||
return null;
|
||||
} catch( FileSystemException e ) {
|
||||
throw new LuaException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
case 9:
|
||||
{
|
||||
// copy
|
||||
if( args.length != 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string, string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
String dest = (String)args[1];
|
||||
try {
|
||||
m_fileSystem.copy( path, dest );
|
||||
return null;
|
||||
} catch( FileSystemException e ) {
|
||||
throw new LuaException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
case 10:
|
||||
{
|
||||
// delete
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
try {
|
||||
m_fileSystem.delete( path );
|
||||
return null;
|
||||
} catch( FileSystemException e ) {
|
||||
throw new LuaException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
case 11:
|
||||
{
|
||||
// open
|
||||
if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string, string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
String mode = (String)args[1];
|
||||
try {
|
||||
if( mode.equals( "r" ) ) {
|
||||
// Open the file for reading, then create a wrapper around the reader
|
||||
IMountedFileNormal reader = m_fileSystem.openForRead( path );
|
||||
return wrapBufferedReader( reader );
|
||||
|
||||
} else if( mode.equals( "w" ) ) {
|
||||
// Open the file for writing, then create a wrapper around the writer
|
||||
IMountedFileNormal writer = m_fileSystem.openForWrite( path, false );
|
||||
return wrapBufferedWriter( writer );
|
||||
|
||||
} else if( mode.equals( "a" ) ) {
|
||||
// Open the file for appending, then create a wrapper around the writer
|
||||
IMountedFileNormal writer = m_fileSystem.openForWrite( path, true );
|
||||
return wrapBufferedWriter( writer );
|
||||
|
||||
} else if( mode.equals( "rb" ) ) {
|
||||
// Open the file for binary reading, then create a wrapper around the reader
|
||||
IMountedFileBinary reader = m_fileSystem.openForBinaryRead( path );
|
||||
return wrapInputStream( reader );
|
||||
|
||||
} else if( mode.equals( "wb" ) ) {
|
||||
// Open the file for binary writing, then create a wrapper around the writer
|
||||
IMountedFileBinary writer = m_fileSystem.openForBinaryWrite( path, false );
|
||||
return wrapOutputStream( writer );
|
||||
|
||||
} else if( mode.equals( "ab" ) ) {
|
||||
// Open the file for binary appending, then create a wrapper around the reader
|
||||
IMountedFileBinary writer = m_fileSystem.openForBinaryWrite( path, true );
|
||||
return wrapOutputStream( writer );
|
||||
|
||||
} else {
|
||||
throw new LuaException( "Unsupported mode" );
|
||||
|
||||
}
|
||||
} catch( FileSystemException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
case 12:
|
||||
{
|
||||
// getDrive
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
try {
|
||||
if( !m_fileSystem.exists( path ) )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return new Object[]{ m_fileSystem.getMountLabel( path ) };
|
||||
} catch( FileSystemException e ) {
|
||||
throw new LuaException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
case 13:
|
||||
{
|
||||
// getFreeSpace
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
try {
|
||||
long freeSpace = m_fileSystem.getFreeSpace( path );
|
||||
if( freeSpace >= 0 )
|
||||
{
|
||||
return new Object[]{ freeSpace };
|
||||
}
|
||||
return new Object[]{ "unlimited" };
|
||||
} catch( FileSystemException e ) {
|
||||
throw new LuaException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
case 14:
|
||||
{
|
||||
// find
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
try {
|
||||
String[] results = m_fileSystem.find( path );
|
||||
Map<Object,Object> table = new HashMap<Object,Object>();
|
||||
for(int i=0; i<results.length; ++i ) {
|
||||
table.put( i+1, results[i] );
|
||||
}
|
||||
return new Object[] { table };
|
||||
} catch( FileSystemException e ) {
|
||||
throw new LuaException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
case 15:
|
||||
{
|
||||
// getDir
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String path = (String)args[0];
|
||||
return new Object[]{ m_fileSystem.getDirectory( path ) };
|
||||
}
|
||||
default:
|
||||
{
|
||||
assert( false );
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Object[] wrapBufferedReader( final IMountedFileNormal reader )
|
||||
{
|
||||
return new Object[] { new ILuaObject() {
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"readLine",
|
||||
"readAll",
|
||||
"close"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// readLine
|
||||
try {
|
||||
String line = reader.readLine();
|
||||
if( line != null ) {
|
||||
return new Object[] { line };
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} catch( IOException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// readAll
|
||||
try {
|
||||
StringBuilder result = new StringBuilder( "" );
|
||||
String line = reader.readLine();
|
||||
while( line != null ) {
|
||||
result.append( line );
|
||||
line = reader.readLine();
|
||||
if( line != null ) {
|
||||
result.append( "\n" );
|
||||
}
|
||||
}
|
||||
return new Object[] { result.toString() };
|
||||
} catch( IOException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// close
|
||||
try {
|
||||
reader.close();
|
||||
return null;
|
||||
} catch( IOException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
} };
|
||||
}
|
||||
|
||||
private static Object[] wrapBufferedWriter( final IMountedFileNormal writer )
|
||||
{
|
||||
return new Object[] { new ILuaObject() {
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"write",
|
||||
"writeLine",
|
||||
"close",
|
||||
"flush"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// write
|
||||
String text;
|
||||
if( args.length > 0 && args[0] != null ) {
|
||||
text = args[0].toString();
|
||||
} else {
|
||||
text = "";
|
||||
}
|
||||
try {
|
||||
writer.write( text, 0, text.length(), false );
|
||||
return null;
|
||||
} catch( IOException e ) {
|
||||
throw new LuaException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// writeLine
|
||||
String text;
|
||||
if( args.length > 0 && args[0] != null ) {
|
||||
text = args[0].toString();
|
||||
} else {
|
||||
text = "";
|
||||
}
|
||||
try {
|
||||
writer.write( text, 0, text.length(), true );
|
||||
return null;
|
||||
} catch( IOException e ) {
|
||||
throw new LuaException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// close
|
||||
try {
|
||||
writer.close();
|
||||
return null;
|
||||
} catch( IOException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
try {
|
||||
writer.flush();
|
||||
return null;
|
||||
} catch ( IOException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
default:
|
||||
{
|
||||
assert( false );
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
} };
|
||||
}
|
||||
|
||||
private static Object[] wrapInputStream( final IMountedFileBinary reader )
|
||||
{
|
||||
|
||||
return new Object[] { new ILuaObject() {
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames() {
|
||||
return new String[] {
|
||||
"read",
|
||||
"close"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] args) throws LuaException {
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// read
|
||||
try {
|
||||
int b = reader.read();
|
||||
if( b != -1 ) {
|
||||
return new Object[] { b };
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} catch( IOException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
//close
|
||||
try {
|
||||
reader.close();
|
||||
return null;
|
||||
} catch( IOException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
default:
|
||||
{
|
||||
assert( false );
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
private static Object[] wrapOutputStream( final IMountedFileBinary writer )
|
||||
{
|
||||
|
||||
return new Object[] { new ILuaObject() {
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames() {
|
||||
return new String[] {
|
||||
"write",
|
||||
"close",
|
||||
"flush"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] args) throws LuaException {
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// write
|
||||
try {
|
||||
if( args.length > 0 && args[0] instanceof Number )
|
||||
{
|
||||
int number = ((Number)args[0]).intValue();
|
||||
writer.write( number );
|
||||
}
|
||||
return null;
|
||||
} catch( IOException e ) {
|
||||
throw new LuaException(e.getMessage());
|
||||
}
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
//close
|
||||
try {
|
||||
writer.close();
|
||||
return null;
|
||||
} catch( IOException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
try {
|
||||
writer.flush();
|
||||
return null;
|
||||
} catch ( IOException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
default:
|
||||
{
|
||||
assert( false );
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.ILuaObject;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
public class HTTPAPI implements ILuaAPI
|
||||
{
|
||||
private IAPIEnvironment m_apiEnvironment;
|
||||
private List<HTTPRequest> m_httpRequests;
|
||||
|
||||
public HTTPAPI( IAPIEnvironment environment )
|
||||
{
|
||||
m_apiEnvironment = environment;
|
||||
m_httpRequests = new ArrayList<HTTPRequest>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"http"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startup( )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void advance( double _dt )
|
||||
{
|
||||
// Wait for all of our http requests
|
||||
synchronized( m_httpRequests )
|
||||
{
|
||||
Iterator<HTTPRequest> it = m_httpRequests.iterator();
|
||||
while( it.hasNext() ) {
|
||||
final HTTPRequest h = it.next();
|
||||
if( h.isComplete() ) {
|
||||
final String url = h.getURL();
|
||||
if( h.wasSuccessful() ) {
|
||||
// Queue the "http_success" event
|
||||
final BufferedReader contents = h.getContents();
|
||||
final int responseCode = h.getResponseCode();
|
||||
final Object result = wrapBufferedReader( contents, responseCode );
|
||||
m_apiEnvironment.queueEvent( "http_success", new Object[] { url, result } );
|
||||
} else {
|
||||
// Queue the "http_failure" event
|
||||
m_apiEnvironment.queueEvent( "http_failure", new Object[] { url, "Could not connect" } );
|
||||
}
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ILuaObject wrapBufferedReader( final BufferedReader reader, final int responseCode )
|
||||
{
|
||||
return new ILuaObject() {
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"readLine",
|
||||
"readAll",
|
||||
"close",
|
||||
"getResponseCode"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// readLine
|
||||
try {
|
||||
String line = reader.readLine();
|
||||
if( line != null ) {
|
||||
return new Object[] { line };
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} catch( IOException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// readAll
|
||||
try {
|
||||
StringBuilder result = new StringBuilder( "" );
|
||||
String line = reader.readLine();
|
||||
while( line != null ) {
|
||||
result.append( line );
|
||||
line = reader.readLine();
|
||||
if( line != null ) {
|
||||
result.append( "\n" );
|
||||
}
|
||||
}
|
||||
return new Object[] { result.toString() };
|
||||
} catch( IOException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// close
|
||||
try {
|
||||
reader.close();
|
||||
return null;
|
||||
} catch( IOException e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
// getResponseCode
|
||||
return new Object[] { responseCode };
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown( )
|
||||
{
|
||||
synchronized( m_httpRequests )
|
||||
{
|
||||
Iterator<HTTPRequest> it = m_httpRequests.iterator();
|
||||
while( it.hasNext() ) {
|
||||
HTTPRequest r = it.next();
|
||||
r.cancel();
|
||||
}
|
||||
m_httpRequests.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"request",
|
||||
"checkURL"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// request
|
||||
// Get URL
|
||||
if( args.length < 1 || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String urlString = args[0].toString();
|
||||
|
||||
// Get POST
|
||||
String postString = null;
|
||||
if( args.length >= 2 && args[1] instanceof String )
|
||||
{
|
||||
postString = args[1].toString();
|
||||
}
|
||||
|
||||
// Get Headers
|
||||
Map<String, String> headers = null;
|
||||
if( args.length >= 3 && args[2] instanceof Map )
|
||||
{
|
||||
Map table = (Map)args[2];
|
||||
headers = new HashMap<String, String>( table.size() );
|
||||
for( Object key : table.keySet() )
|
||||
{
|
||||
Object value = table.get( key );
|
||||
if( key instanceof String && value instanceof String )
|
||||
{
|
||||
headers.put( (String)key, (String)value );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make the request
|
||||
try
|
||||
{
|
||||
HTTPRequest request = new HTTPRequest( urlString, postString, headers );
|
||||
synchronized( m_httpRequests )
|
||||
{
|
||||
m_httpRequests.add( request );
|
||||
}
|
||||
return new Object[] { true };
|
||||
}
|
||||
catch( HTTPRequestException e )
|
||||
{
|
||||
return new Object[] { false, e.getMessage() };
|
||||
}
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// checkURL
|
||||
// Get URL
|
||||
if( args.length < 1 || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String urlString = args[0].toString();
|
||||
|
||||
// Check URL
|
||||
try
|
||||
{
|
||||
HTTPRequest.checkURL( urlString );
|
||||
return new Object[] { true };
|
||||
}
|
||||
catch( HTTPRequestException e )
|
||||
{
|
||||
return new Object[] { false, e.getMessage() };
|
||||
}
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
class HTTPRequestException extends Exception {
|
||||
public HTTPRequestException( String s ) {
|
||||
super( s );
|
||||
}
|
||||
}
|
||||
|
||||
public class HTTPRequest
|
||||
{
|
||||
public static URL checkURL( String urlString ) throws HTTPRequestException
|
||||
{
|
||||
URL url;
|
||||
try
|
||||
{
|
||||
url = new URL( urlString );
|
||||
}
|
||||
catch( MalformedURLException e )
|
||||
{
|
||||
throw new HTTPRequestException( "URL malformed" );
|
||||
}
|
||||
|
||||
// Validate the URL
|
||||
String protocol = url.getProtocol().toLowerCase();
|
||||
if( !protocol.equals("http") && !protocol.equals("https") )
|
||||
{
|
||||
throw new HTTPRequestException( "URL not http" );
|
||||
}
|
||||
|
||||
// Compare the URL to the whitelist
|
||||
boolean allowed = false;
|
||||
String whitelistString = ComputerCraft.http_whitelist;
|
||||
String[] allowedURLs = whitelistString.split( ";" );
|
||||
for( int i=0; i<allowedURLs.length; ++i )
|
||||
{
|
||||
String allowedURL = allowedURLs[i];
|
||||
Pattern allowedURLPattern = Pattern.compile( "^\\Q" + allowedURL.replaceAll( "\\*", "\\\\E.*\\\\Q" ) + "\\E$" );
|
||||
if( allowedURLPattern.matcher( url.getHost() ).matches() )
|
||||
{
|
||||
allowed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if( !allowed )
|
||||
{
|
||||
throw new HTTPRequestException( "Domain not permitted" );
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
public HTTPRequest( String url, final String postText, final Map<String, String> headers ) throws HTTPRequestException
|
||||
{
|
||||
// Parse the URL
|
||||
m_urlString = url;
|
||||
m_url = checkURL( m_urlString );
|
||||
|
||||
// Start the thread
|
||||
m_cancelled = false;
|
||||
m_complete = false;
|
||||
m_success = false;
|
||||
m_result = null;
|
||||
m_responseCode = -1;
|
||||
|
||||
Thread thread = new Thread( new Runnable() {
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Connect to the URL
|
||||
HttpURLConnection connection = (HttpURLConnection)m_url.openConnection();
|
||||
|
||||
if( postText != null )
|
||||
{
|
||||
connection.setRequestMethod( "POST" );
|
||||
connection.setDoOutput( true );
|
||||
}
|
||||
else
|
||||
{
|
||||
connection.setRequestMethod( "GET" );
|
||||
}
|
||||
|
||||
// Set headers
|
||||
connection.setRequestProperty( "accept-charset", "UTF-8" );
|
||||
if( postText != null )
|
||||
{
|
||||
connection.setRequestProperty( "content-type", "application/x-www-form-urlencoded; charset=utf-8" );
|
||||
connection.setRequestProperty( "content-encoding", "UTF-8" );
|
||||
}
|
||||
if( headers != null )
|
||||
{
|
||||
for( Map.Entry<String, String> header : headers.entrySet() )
|
||||
{
|
||||
connection.setRequestProperty( header.getKey(), header.getValue() );
|
||||
}
|
||||
}
|
||||
|
||||
// Send POST text
|
||||
if( postText != null )
|
||||
{
|
||||
OutputStream os = connection.getOutputStream();
|
||||
OutputStreamWriter osw;
|
||||
try
|
||||
{
|
||||
osw = new OutputStreamWriter( os, "UTF-8" );
|
||||
}
|
||||
catch( UnsupportedEncodingException e )
|
||||
{
|
||||
osw = new OutputStreamWriter( os );
|
||||
}
|
||||
BufferedWriter writer = new BufferedWriter( osw );
|
||||
writer.write( postText, 0, postText.length() );
|
||||
writer.close();
|
||||
}
|
||||
|
||||
// Read response
|
||||
InputStream is = connection.getInputStream();
|
||||
InputStreamReader isr;
|
||||
try
|
||||
{
|
||||
String contentEncoding = connection.getContentEncoding();
|
||||
if( contentEncoding != null )
|
||||
{
|
||||
try
|
||||
{
|
||||
isr = new InputStreamReader( is, contentEncoding );
|
||||
}
|
||||
catch( UnsupportedEncodingException e )
|
||||
{
|
||||
isr = new InputStreamReader( is, "UTF-8" );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
isr = new InputStreamReader( is, "UTF-8" );
|
||||
}
|
||||
}
|
||||
catch( UnsupportedEncodingException e )
|
||||
{
|
||||
isr = new InputStreamReader( is );
|
||||
}
|
||||
|
||||
// Download the contents
|
||||
BufferedReader reader = new BufferedReader( isr );
|
||||
StringBuilder result = new StringBuilder();
|
||||
while( true )
|
||||
{
|
||||
synchronized( m_lock )
|
||||
{
|
||||
if( m_cancelled )
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
String line = reader.readLine();
|
||||
if( line == null )
|
||||
{
|
||||
break;
|
||||
}
|
||||
result.append( line );
|
||||
result.append( '\n' );
|
||||
}
|
||||
reader.close();
|
||||
|
||||
synchronized( m_lock )
|
||||
{
|
||||
if( m_cancelled )
|
||||
{
|
||||
// We cancelled
|
||||
m_complete = true;
|
||||
m_success = false;
|
||||
m_result = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
// We completed
|
||||
m_complete = true;
|
||||
m_success = true;
|
||||
m_result = result.toString();
|
||||
m_responseCode = connection.getResponseCode();
|
||||
}
|
||||
}
|
||||
|
||||
connection.disconnect(); // disconnect
|
||||
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
synchronized( m_lock )
|
||||
{
|
||||
// There was an error
|
||||
m_complete = true;
|
||||
m_success = false;
|
||||
m_result = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
} );
|
||||
|
||||
thread.start();
|
||||
}
|
||||
|
||||
public String getURL() {
|
||||
return m_urlString;
|
||||
}
|
||||
|
||||
public void cancel()
|
||||
{
|
||||
synchronized(m_lock) {
|
||||
m_cancelled = true;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isComplete()
|
||||
{
|
||||
synchronized(m_lock) {
|
||||
return m_complete;
|
||||
}
|
||||
}
|
||||
|
||||
public int getResponseCode() {
|
||||
synchronized(m_lock) {
|
||||
return m_responseCode;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean wasSuccessful()
|
||||
{
|
||||
synchronized(m_lock) {
|
||||
return m_success;
|
||||
}
|
||||
}
|
||||
|
||||
public BufferedReader getContents()
|
||||
{
|
||||
String result = null;
|
||||
synchronized(m_lock) {
|
||||
result = m_result;
|
||||
}
|
||||
|
||||
if( result != null ) {
|
||||
return new BufferedReader( new StringReader( result ) );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Object m_lock = new Object();
|
||||
private URL m_url;
|
||||
private final String m_urlString;
|
||||
|
||||
private boolean m_complete;
|
||||
private boolean m_cancelled;
|
||||
private boolean m_success;
|
||||
private String m_result;
|
||||
private int m_responseCode;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.core.computer.Computer;
|
||||
import dan200.computercraft.core.computer.IComputerEnvironment;
|
||||
import dan200.computercraft.core.filesystem.FileSystem;
|
||||
import dan200.computercraft.core.terminal.Terminal;
|
||||
|
||||
public interface IAPIEnvironment
|
||||
{
|
||||
public static interface IPeripheralChangeListener
|
||||
{
|
||||
public void onPeripheralChanged( int side, IPeripheral newPeripheral );
|
||||
}
|
||||
|
||||
public Computer getComputer();
|
||||
public int getComputerID();
|
||||
public IComputerEnvironment getComputerEnvironment();
|
||||
public Terminal getTerminal();
|
||||
public FileSystem getFileSystem();
|
||||
|
||||
public void shutdown();
|
||||
public void reboot();
|
||||
public void queueEvent( String event, Object[] args );
|
||||
|
||||
public void setOutput( int side, int output );
|
||||
public int getOutput( int side );
|
||||
public int getInput( int side );
|
||||
|
||||
public void setBundledOutput( int side, int output );
|
||||
public int getBundledOutput( int side );
|
||||
public int getBundledInput( int side );
|
||||
|
||||
public void setPeripheralChangeListener( IPeripheralChangeListener listener );
|
||||
public IPeripheral getPeripheral( int side );
|
||||
|
||||
public String getLabel();
|
||||
public void setLabel( String label );
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
import dan200.computercraft.api.lua.ILuaObject;
|
||||
|
||||
public interface ILuaAPI extends ILuaObject
|
||||
{
|
||||
public String[] getNames();
|
||||
|
||||
public void startup(); // LT
|
||||
public void advance( double _dt ); // MT
|
||||
public void shutdown(); // LT
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
public class OSAPI implements ILuaAPI
|
||||
{
|
||||
private IAPIEnvironment m_apiEnvironment;
|
||||
|
||||
private final Map<Integer, Timer> m_timers;
|
||||
private final Map<Integer, Alarm> m_alarms;
|
||||
private int m_clock;
|
||||
private double m_time;
|
||||
private int m_day;
|
||||
|
||||
private int m_nextTimerToken;
|
||||
private int m_nextAlarmToken;
|
||||
|
||||
private static class Timer
|
||||
{
|
||||
public int m_ticksLeft;
|
||||
|
||||
public Timer( int ticksLeft )
|
||||
{
|
||||
m_ticksLeft = ticksLeft;
|
||||
}
|
||||
}
|
||||
|
||||
private class Alarm implements Comparable<Alarm>
|
||||
{
|
||||
public final double m_time;
|
||||
public final int m_day;
|
||||
|
||||
public Alarm( double time, int day )
|
||||
{
|
||||
m_time = time;
|
||||
m_day = day;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo( Alarm o )
|
||||
{
|
||||
double t = (double)m_day * 24.0 + m_time;
|
||||
double ot = (double)m_day * 24.0 + m_time;
|
||||
if( t < ot ) {
|
||||
return -1;
|
||||
} else if( t > ot ) {
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public OSAPI( IAPIEnvironment environment )
|
||||
{
|
||||
m_apiEnvironment = environment;
|
||||
m_nextTimerToken = 0;
|
||||
m_nextAlarmToken = 0;
|
||||
m_timers = new HashMap<Integer, Timer>();
|
||||
m_alarms = new HashMap<Integer, Alarm>();
|
||||
}
|
||||
|
||||
// ILuaAPI implementation
|
||||
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"os"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startup()
|
||||
{
|
||||
m_time = m_apiEnvironment.getComputerEnvironment().getTimeOfDay();
|
||||
m_day = m_apiEnvironment.getComputerEnvironment().getDay();
|
||||
m_clock = 0;
|
||||
|
||||
synchronized( m_timers )
|
||||
{
|
||||
m_timers.clear();
|
||||
}
|
||||
|
||||
synchronized( m_alarms )
|
||||
{
|
||||
m_alarms.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void advance( double dt )
|
||||
{
|
||||
synchronized( m_timers )
|
||||
{
|
||||
// Update the clock
|
||||
m_clock++;
|
||||
|
||||
// Countdown all of our active timers
|
||||
Iterator<Map.Entry<Integer, Timer>> it = m_timers.entrySet().iterator();
|
||||
while( it.hasNext() )
|
||||
{
|
||||
Map.Entry<Integer, Timer> entry = it.next();
|
||||
Timer timer = entry.getValue();
|
||||
timer.m_ticksLeft = timer.m_ticksLeft - 1;
|
||||
if( timer.m_ticksLeft <= 0 )
|
||||
{
|
||||
// Queue the "timer" event
|
||||
queueLuaEvent( "timer", new Object[] { entry.getKey() } );
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for all of our alarms
|
||||
synchronized( m_alarms )
|
||||
{
|
||||
double previousTime = m_time;
|
||||
int previousDay = m_day;
|
||||
double time = m_apiEnvironment.getComputerEnvironment().getTimeOfDay();
|
||||
int day = m_apiEnvironment.getComputerEnvironment().getDay();
|
||||
|
||||
if( time > previousTime || day > previousDay )
|
||||
{
|
||||
double now = (double)m_day * 24.0 + m_time;
|
||||
Iterator<Map.Entry<Integer, Alarm>> it = m_alarms.entrySet().iterator();
|
||||
while( it.hasNext() )
|
||||
{
|
||||
Map.Entry<Integer, Alarm> entry = it.next();
|
||||
Alarm alarm = entry.getValue();
|
||||
double t = (double)alarm.m_day * 24.0 + alarm.m_time;
|
||||
if( now >= t )
|
||||
{
|
||||
queueLuaEvent( "alarm", new Object[]{ entry.getKey() } );
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m_time = time;
|
||||
m_day = day;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown( )
|
||||
{
|
||||
synchronized( m_timers )
|
||||
{
|
||||
m_timers.clear();
|
||||
}
|
||||
|
||||
synchronized( m_alarms )
|
||||
{
|
||||
m_alarms.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"queueEvent",
|
||||
"startTimer",
|
||||
"setAlarm",
|
||||
"shutdown",
|
||||
"reboot",
|
||||
"computerID",
|
||||
"getComputerID",
|
||||
"setComputerLabel",
|
||||
"computerLabel",
|
||||
"getComputerLabel",
|
||||
"clock",
|
||||
"time",
|
||||
"day",
|
||||
"cancelTimer",
|
||||
"cancelAlarm",
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// queueEvent
|
||||
if( args.length == 0 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
queueLuaEvent( (String)args[0], trimArray( args, 1 ) );
|
||||
return null;
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// startTimer
|
||||
if( args.length < 1 || args[0] == null || !(args[0] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected number" );
|
||||
}
|
||||
double timer = ((Number)args[0]).doubleValue();
|
||||
synchronized( m_timers )
|
||||
{
|
||||
m_timers.put( m_nextTimerToken, new Timer( (int)Math.round( timer / 0.05 ) ) );
|
||||
return new Object[] { m_nextTimerToken++ };
|
||||
}
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// setAlarm
|
||||
if( args.length < 1 || args[0] == null || !(args[0] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected number" );
|
||||
}
|
||||
double time = ((Number)args[0]).doubleValue();
|
||||
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 new Object[] { m_nextAlarmToken++ };
|
||||
}
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
// shutdown
|
||||
m_apiEnvironment.shutdown();
|
||||
return null;
|
||||
}
|
||||
case 4:
|
||||
{
|
||||
// reboot
|
||||
m_apiEnvironment.reboot();
|
||||
return null;
|
||||
}
|
||||
case 5:
|
||||
case 6:
|
||||
{
|
||||
// computerID/getComputerID
|
||||
return new Object[] { getComputerID() };
|
||||
}
|
||||
case 7:
|
||||
{
|
||||
// setComputerLabel
|
||||
String label = null;
|
||||
if( args.length > 0 && args[0] != null )
|
||||
{
|
||||
if(!(args[0] instanceof String))
|
||||
{
|
||||
throw new LuaException( "Expected string or nil" );
|
||||
}
|
||||
label = (String)args[0];
|
||||
if( label.length() > 32 )
|
||||
{
|
||||
label = label.substring( 0, 32 );
|
||||
}
|
||||
}
|
||||
m_apiEnvironment.setLabel( label );
|
||||
return null;
|
||||
}
|
||||
case 8:
|
||||
case 9:
|
||||
{
|
||||
// computerLabel/getComputerLabel
|
||||
String label = m_apiEnvironment.getLabel();
|
||||
if( label != null )
|
||||
{
|
||||
return new Object[] { label };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 10:
|
||||
{
|
||||
// clock
|
||||
synchronized( m_timers )
|
||||
{
|
||||
return new Object[] { (double)m_clock * 0.05 };
|
||||
}
|
||||
}
|
||||
case 11:
|
||||
{
|
||||
// m_time
|
||||
synchronized( m_alarms )
|
||||
{
|
||||
return new Object[] { m_time };
|
||||
}
|
||||
}
|
||||
case 12:
|
||||
{
|
||||
// day
|
||||
synchronized( m_alarms )
|
||||
{
|
||||
return new Object[] { m_day };
|
||||
}
|
||||
}
|
||||
case 13:
|
||||
{
|
||||
// cancelTimer
|
||||
if( args.length < 1 || args[0] == null || !(args[0] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected number" );
|
||||
}
|
||||
int token = ((Number)args[0]).intValue();
|
||||
synchronized( m_timers )
|
||||
{
|
||||
if( m_timers.containsKey( token ) )
|
||||
{
|
||||
m_timers.remove( token );
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 14:
|
||||
{
|
||||
// cancelAlarm
|
||||
if( args.length < 1 || args[0] == null || !(args[0] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected number" );
|
||||
}
|
||||
int token = ((Number)args[0]).intValue();
|
||||
synchronized( m_alarms )
|
||||
{
|
||||
if( m_alarms.containsKey( token ) )
|
||||
{
|
||||
m_alarms.remove( token );
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Private methods
|
||||
|
||||
private void queueLuaEvent( String event, Object[] args )
|
||||
{
|
||||
m_apiEnvironment.queueEvent( event, args );
|
||||
}
|
||||
|
||||
private Object[] trimArray( Object[] array, int skip )
|
||||
{
|
||||
return Arrays.copyOfRange( array, skip, array.length );
|
||||
}
|
||||
|
||||
private int getComputerID()
|
||||
{
|
||||
return m_apiEnvironment.getComputerID();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,534 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. 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.ILuaContext;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.api.peripheral.IComputerAccess;
|
||||
import dan200.computercraft.api.peripheral.IPeripheral;
|
||||
import dan200.computercraft.core.computer.Computer;
|
||||
import dan200.computercraft.core.computer.ComputerThread;
|
||||
import dan200.computercraft.core.computer.ITask;
|
||||
import dan200.computercraft.core.filesystem.FileSystem;
|
||||
import dan200.computercraft.core.filesystem.FileSystemException;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChangeListener
|
||||
{
|
||||
private class PeripheralWrapper implements IComputerAccess
|
||||
{
|
||||
private final String m_side;
|
||||
private final IPeripheral m_peripheral;
|
||||
|
||||
private String m_type;
|
||||
private String[] m_methods;
|
||||
private Map<String, Integer> m_methodMap;
|
||||
private boolean m_attached;
|
||||
|
||||
private Set<String> m_mounts;
|
||||
|
||||
public PeripheralWrapper( IPeripheral peripheral, String side )
|
||||
{
|
||||
m_side = side;
|
||||
m_peripheral = peripheral;
|
||||
m_attached = false;
|
||||
|
||||
m_type = peripheral.getType();
|
||||
m_methods = peripheral.getMethodNames();
|
||||
assert( m_type != null );
|
||||
assert( m_methods != null );
|
||||
|
||||
m_methodMap = new HashMap<String, Integer>();
|
||||
for(int i=0; i<m_methods.length; ++i ) {
|
||||
if( m_methods[i] != null ) {
|
||||
m_methodMap.put( m_methods[i], i );
|
||||
}
|
||||
}
|
||||
|
||||
m_mounts = new HashSet<String>();
|
||||
}
|
||||
|
||||
public IPeripheral getPeripheral()
|
||||
{
|
||||
return m_peripheral;
|
||||
}
|
||||
|
||||
public String getType()
|
||||
{
|
||||
return m_type;
|
||||
}
|
||||
|
||||
public String[] getMethods()
|
||||
{
|
||||
return m_methods;
|
||||
}
|
||||
|
||||
public synchronized boolean isAttached()
|
||||
{
|
||||
return m_attached;
|
||||
}
|
||||
|
||||
public synchronized void attach()
|
||||
{
|
||||
m_attached = true;
|
||||
m_peripheral.attach( this );
|
||||
}
|
||||
|
||||
public synchronized void detach()
|
||||
{
|
||||
// Call detach
|
||||
m_peripheral.detach( this );
|
||||
m_attached = false;
|
||||
|
||||
// Unmount everything the detach function forgot to do
|
||||
Iterator<String> it = m_mounts.iterator();
|
||||
while( it.hasNext() ) {
|
||||
m_fileSystem.unmount( it.next() );
|
||||
}
|
||||
m_mounts.clear();
|
||||
}
|
||||
|
||||
public Object[] call( ILuaContext context, String methodName, Object[] arguments ) throws LuaException, InterruptedException
|
||||
{
|
||||
int method = -1;
|
||||
synchronized( this )
|
||||
{
|
||||
if( m_methodMap.containsKey( methodName ) )
|
||||
{
|
||||
method = m_methodMap.get( methodName );
|
||||
}
|
||||
}
|
||||
if( method >= 0 )
|
||||
{
|
||||
return m_peripheral.callMethod( this, context, method, arguments );
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new LuaException( "No such method " + methodName );
|
||||
}
|
||||
}
|
||||
|
||||
// IComputerAccess implementation
|
||||
|
||||
@Override
|
||||
public String mount( String desiredLoc, IMount mount )
|
||||
{
|
||||
return mount( desiredLoc, mount, m_side );
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized String mount( String desiredLoc, IMount mount, String driveName )
|
||||
{
|
||||
if( !m_attached )
|
||||
{
|
||||
throw new RuntimeException( "You are not attached to this Computer" );
|
||||
}
|
||||
|
||||
// Mount the location
|
||||
String location = null;
|
||||
synchronized( m_fileSystem )
|
||||
{
|
||||
location = findFreeLocation( desiredLoc );
|
||||
if( location != null )
|
||||
{
|
||||
try {
|
||||
m_fileSystem.mount( driveName, location, mount );
|
||||
} catch( FileSystemException e ) {
|
||||
// fail and return null
|
||||
}
|
||||
}
|
||||
}
|
||||
if( location != null )
|
||||
{
|
||||
m_mounts.add( location );
|
||||
}
|
||||
return location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String mountWritable( String desiredLoc, IWritableMount mount )
|
||||
{
|
||||
return mountWritable( desiredLoc, mount, m_side );
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized String mountWritable( String desiredLoc, IWritableMount mount, String driveName )
|
||||
{
|
||||
if( !m_attached )
|
||||
{
|
||||
throw new RuntimeException( "You are not attached to this Computer" );
|
||||
}
|
||||
|
||||
// Mount the location
|
||||
String location = null;
|
||||
synchronized( m_fileSystem )
|
||||
{
|
||||
location = findFreeLocation( desiredLoc );
|
||||
if( location != null )
|
||||
{
|
||||
try {
|
||||
m_fileSystem.mountWritable( driveName, location, mount );
|
||||
} catch( FileSystemException e ) {
|
||||
// fail and return null
|
||||
}
|
||||
}
|
||||
}
|
||||
if( location != null )
|
||||
{
|
||||
m_mounts.add( location );
|
||||
}
|
||||
return location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void unmount( String location )
|
||||
{
|
||||
if( !m_attached ) {
|
||||
throw new RuntimeException( "You are not attached to this Computer" );
|
||||
}
|
||||
|
||||
if( location != null )
|
||||
{
|
||||
if( !m_mounts.contains( location ) ) {
|
||||
throw new RuntimeException( "You didn't mount this location" );
|
||||
}
|
||||
|
||||
m_fileSystem.unmount( location );
|
||||
m_mounts.remove( location );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized int getID()
|
||||
{
|
||||
if( !m_attached ) {
|
||||
throw new RuntimeException( "You are not attached to this Computer" );
|
||||
}
|
||||
return m_environment.getComputerID();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void queueEvent( final String event, final Object[] arguments )
|
||||
{
|
||||
if( !m_attached ) {
|
||||
throw new RuntimeException( "You are not attached to this Computer" );
|
||||
}
|
||||
m_environment.queueEvent( event, arguments );
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized String getAttachmentName()
|
||||
{
|
||||
if( !m_attached ) {
|
||||
throw new RuntimeException( "You are not attached to this Computer" );
|
||||
}
|
||||
return m_side;
|
||||
}
|
||||
}
|
||||
|
||||
private IAPIEnvironment m_environment;
|
||||
private FileSystem m_fileSystem;
|
||||
private PeripheralWrapper[] m_peripherals;
|
||||
private boolean m_running;
|
||||
|
||||
public PeripheralAPI( IAPIEnvironment _environment )
|
||||
{
|
||||
m_environment = _environment;
|
||||
m_environment.setPeripheralChangeListener( this );
|
||||
|
||||
m_peripherals = new PeripheralWrapper[6];
|
||||
for(int i=0; i<6; ++i)
|
||||
{
|
||||
m_peripherals[i] = null;
|
||||
}
|
||||
|
||||
m_running = false;
|
||||
}
|
||||
|
||||
// IPeripheralChangeListener
|
||||
|
||||
@Override
|
||||
public void onPeripheralChanged( int side, IPeripheral newPeripheral )
|
||||
{
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
if( m_peripherals[side] != null )
|
||||
{
|
||||
// Queue a detachment
|
||||
final PeripheralWrapper wrapper = m_peripherals[side];
|
||||
ComputerThread.queueTask(new ITask() {
|
||||
@Override
|
||||
public Computer getOwner() {
|
||||
return m_environment.getComputer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
synchronized (m_peripherals) {
|
||||
if (wrapper.isAttached()) {
|
||||
wrapper.detach();
|
||||
}
|
||||
}
|
||||
}
|
||||
}, null);
|
||||
|
||||
// Queue a detachment event
|
||||
m_environment.queueEvent( "peripheral_detach", new Object[] { Computer.s_sideNames[side] } );
|
||||
}
|
||||
|
||||
// Assign the new peripheral
|
||||
if( newPeripheral != null )
|
||||
{
|
||||
m_peripherals[side] = new PeripheralWrapper( newPeripheral, Computer.s_sideNames[side] );
|
||||
}
|
||||
else
|
||||
{
|
||||
m_peripherals[side] = null;
|
||||
}
|
||||
|
||||
if( m_peripherals[side] != null )
|
||||
{
|
||||
// Queue an attachment
|
||||
final PeripheralWrapper wrapper = m_peripherals[side];
|
||||
ComputerThread.queueTask( new ITask() {
|
||||
@Override
|
||||
public Computer getOwner() {
|
||||
return m_environment.getComputer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
if( m_running && !wrapper.isAttached() )
|
||||
{
|
||||
wrapper.attach();
|
||||
}
|
||||
}
|
||||
}
|
||||
}, null );
|
||||
|
||||
// Queue an attachment event
|
||||
m_environment.queueEvent( "peripheral", new Object[] { Computer.s_sideNames[side] } );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ILuaAPI implementation
|
||||
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"peripheral"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startup( )
|
||||
{
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
m_fileSystem = m_environment.getFileSystem();
|
||||
m_running = true;
|
||||
for( int i=0; i<6; ++i )
|
||||
{
|
||||
PeripheralWrapper wrapper = m_peripherals[i];
|
||||
if( wrapper != null && !wrapper.isAttached() )
|
||||
{
|
||||
wrapper.attach();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void advance( double _dt )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown( )
|
||||
{
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
m_running = false;
|
||||
for( int i=0; i<6; ++i )
|
||||
{
|
||||
PeripheralWrapper wrapper = m_peripherals[i];
|
||||
if( wrapper != null && wrapper.isAttached() )
|
||||
{
|
||||
wrapper.detach();
|
||||
}
|
||||
}
|
||||
m_fileSystem = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"isPresent",
|
||||
"getType",
|
||||
"getMethods",
|
||||
"call"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException, InterruptedException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// isPresent
|
||||
boolean present = false;
|
||||
int side = parseSide( args );
|
||||
if( side >= 0 )
|
||||
{
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
PeripheralWrapper p = m_peripherals[ side ];
|
||||
if( p != null )
|
||||
{
|
||||
present = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Object[] { present };
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// getType
|
||||
String type = null;
|
||||
int side = parseSide( args );
|
||||
if( side >= 0 )
|
||||
{
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
PeripheralWrapper p = m_peripherals[ side ];
|
||||
if( p != null )
|
||||
{
|
||||
type = p.getType();
|
||||
}
|
||||
}
|
||||
if( type != null )
|
||||
{
|
||||
return new Object[] { type };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// getMethods
|
||||
String[] methods = null;
|
||||
int side = parseSide( args );
|
||||
if( side >= 0 )
|
||||
{
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
PeripheralWrapper p = m_peripherals[ side ];
|
||||
if( p != null )
|
||||
{
|
||||
methods = p.getMethods();
|
||||
}
|
||||
}
|
||||
}
|
||||
if( methods != null )
|
||||
{
|
||||
Map<Object,Object> table = new HashMap<Object,Object>();
|
||||
for(int i=0; i<methods.length; ++i ) {
|
||||
table.put( i+1, methods[i] );
|
||||
}
|
||||
return new Object[] { table };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
// call
|
||||
if( args.length < 2 || args[1] == null || !(args[1] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string, string" );
|
||||
}
|
||||
String methodName = (String)args[1];
|
||||
Object[] methodArgs = trimArray( args, 2 );
|
||||
|
||||
int side = parseSide( args );
|
||||
if( side >= 0 )
|
||||
{
|
||||
PeripheralWrapper p = null;
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
p = m_peripherals[ side ];
|
||||
}
|
||||
if( p != null )
|
||||
{
|
||||
Object[] results = p.call( context, methodName, methodArgs );
|
||||
return results;
|
||||
}
|
||||
}
|
||||
throw new LuaException( "No peripheral attached" );
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Privates
|
||||
|
||||
private Object[] trimArray( Object[] array, int skip )
|
||||
{
|
||||
return Arrays.copyOfRange( array, skip, array.length );
|
||||
}
|
||||
|
||||
private int parseSide( Object[] args ) throws LuaException
|
||||
{
|
||||
if( args.length < 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String side = (String)args[0];
|
||||
for( int n=0; n<Computer.s_sideNames.length; ++n )
|
||||
{
|
||||
if( side.equals( Computer.s_sideNames[n] ) )
|
||||
{
|
||||
return n;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private String findFreeLocation( String desiredLoc )
|
||||
{
|
||||
try
|
||||
{
|
||||
synchronized( m_fileSystem )
|
||||
{
|
||||
if( !m_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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.core.computer.Computer;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class RedstoneAPI implements ILuaAPI
|
||||
{
|
||||
private IAPIEnvironment m_environment;
|
||||
|
||||
public RedstoneAPI( IAPIEnvironment environment )
|
||||
{
|
||||
m_environment = environment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"rs", "redstone"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startup( )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void advance( double _dt )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown( )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"getSides",
|
||||
"setOutput",
|
||||
"getOutput",
|
||||
"getInput",
|
||||
"setBundledOutput",
|
||||
"getBundledOutput",
|
||||
"getBundledInput",
|
||||
"testBundledInput",
|
||||
"setAnalogOutput",
|
||||
"setAnalogueOutput",
|
||||
"getAnalogOutput",
|
||||
"getAnalogueOutput",
|
||||
"getAnalogInput",
|
||||
"getAnalogueInput",
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// getSides
|
||||
Map<Object,Object> table = new HashMap<Object,Object>();
|
||||
for(int i=0; i< Computer.s_sideNames.length; ++i )
|
||||
{
|
||||
table.put( i+1, Computer.s_sideNames[i] );
|
||||
}
|
||||
return new Object[] { table };
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// setOutput
|
||||
if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof Boolean) )
|
||||
{
|
||||
throw new LuaException( "Expected string, boolean" );
|
||||
}
|
||||
int side = parseSide( args );
|
||||
boolean output = ((Boolean)args[1]).booleanValue();
|
||||
m_environment.setOutput( side, output ? 15 : 0 );
|
||||
return null;
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// getOutput
|
||||
int side = parseSide( args );
|
||||
return new Object[] { m_environment.getOutput( side ) > 0 };
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
// getInput
|
||||
int side = parseSide( args );
|
||||
return new Object[] { m_environment.getInput( side ) > 0 };
|
||||
}
|
||||
case 4:
|
||||
{
|
||||
// setBundledOutput
|
||||
if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof Double) )
|
||||
{
|
||||
throw new LuaException( "Expected string, number" );
|
||||
}
|
||||
int side = parseSide( args );
|
||||
int output = ((Double)args[1]).intValue();
|
||||
m_environment.setBundledOutput( side, output );
|
||||
return null;
|
||||
}
|
||||
case 5:
|
||||
{
|
||||
// getBundledOutput
|
||||
int side = parseSide( args );
|
||||
return new Object[] { m_environment.getBundledOutput( side ) };
|
||||
}
|
||||
case 6:
|
||||
{
|
||||
// getBundledInput
|
||||
int side = parseSide( args );
|
||||
return new Object[] { m_environment.getBundledInput( side ) };
|
||||
}
|
||||
case 7:
|
||||
{
|
||||
// testBundledInput
|
||||
if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof Double) )
|
||||
{
|
||||
throw new LuaException( "Expected string, number" );
|
||||
}
|
||||
int side = parseSide( args );
|
||||
int mask = ((Double)args[1]).intValue();
|
||||
int input = m_environment.getBundledInput( side );
|
||||
return new Object[] { ((input & mask) == mask) };
|
||||
}
|
||||
case 8:
|
||||
case 9:
|
||||
{
|
||||
// setAnalogOutput/setAnalogueOutput
|
||||
if( args.length < 2 || args[0] == null || !(args[0] instanceof String) || args[1] == null || !(args[1] instanceof Double) )
|
||||
{
|
||||
throw new LuaException( "Expected string, number" );
|
||||
}
|
||||
int side = parseSide( args );
|
||||
int output = ((Double)args[1]).intValue();
|
||||
if( output < 0 || output > 15 )
|
||||
{
|
||||
throw new LuaException( "Expected number in range 0-15" );
|
||||
}
|
||||
m_environment.setOutput( side, output );
|
||||
return null;
|
||||
}
|
||||
case 10:
|
||||
case 11:
|
||||
{
|
||||
// getAnalogOutput/getAnalogueOutput
|
||||
int side = parseSide( args );
|
||||
return new Object[] { m_environment.getOutput( side ) };
|
||||
}
|
||||
case 12:
|
||||
case 13:
|
||||
{
|
||||
// getAnalogInput/getAnalogueInput
|
||||
int side = parseSide( args );
|
||||
return new Object[] { m_environment.getInput( side ) };
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int parseSide( Object[] args ) throws LuaException
|
||||
{
|
||||
if( args.length < 1 || args[0] == null || !(args[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
String side = (String)args[0];
|
||||
for( int n=0; n<Computer.s_sideNames.length; ++n )
|
||||
{
|
||||
if( side.equals( Computer.s_sideNames[n] ) )
|
||||
{
|
||||
return n;
|
||||
}
|
||||
}
|
||||
throw new LuaException( "Invalid side." );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.core.computer.IComputerEnvironment;
|
||||
import dan200.computercraft.core.terminal.Terminal;
|
||||
|
||||
public class TermAPI implements ILuaAPI
|
||||
{
|
||||
private Terminal m_terminal;
|
||||
private IComputerEnvironment m_environment;
|
||||
|
||||
public TermAPI( IAPIEnvironment _environment )
|
||||
{
|
||||
m_terminal = _environment.getTerminal();
|
||||
m_environment = _environment.getComputerEnvironment();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"term"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startup( )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void advance( double _dt )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown( )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"write",
|
||||
"scroll",
|
||||
"setCursorPos",
|
||||
"setCursorBlink",
|
||||
"getCursorPos",
|
||||
"getSize",
|
||||
"clear",
|
||||
"clearLine",
|
||||
"setTextColour",
|
||||
"setTextColor",
|
||||
"setBackgroundColour",
|
||||
"setBackgroundColor",
|
||||
"isColour",
|
||||
"isColor",
|
||||
"getTextColour",
|
||||
"getTextColor",
|
||||
"getBackgroundColour",
|
||||
"getBackgroundColor",
|
||||
"blit"
|
||||
};
|
||||
}
|
||||
|
||||
public static int parseColour( Object[] args, boolean _enableColours ) throws LuaException
|
||||
{
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof Double) )
|
||||
{
|
||||
throw new LuaException( "Expected number" );
|
||||
}
|
||||
int colour = (int)((Double)args[0]).doubleValue();
|
||||
if( colour <= 0 )
|
||||
{
|
||||
throw new LuaException( "Colour out of range" );
|
||||
}
|
||||
colour = getHighestBit( colour ) - 1;
|
||||
if( colour < 0 || colour > 15 )
|
||||
{
|
||||
throw new LuaException( "Colour out of range" );
|
||||
}
|
||||
if( !_enableColours && (colour != 0 && colour != 15 && colour != 7 && colour != 8) )
|
||||
{
|
||||
throw new LuaException( "Colour not supported" );
|
||||
}
|
||||
return colour;
|
||||
}
|
||||
|
||||
public static Object[] encodeColour( int colour ) throws LuaException
|
||||
{
|
||||
return new Object[] {
|
||||
1 << colour
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] args ) throws LuaException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// write
|
||||
String text;
|
||||
if( args.length > 0 && args[0] != null ) {
|
||||
text = args[0].toString();
|
||||
} else {
|
||||
text = "";
|
||||
}
|
||||
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
m_terminal.write( text );
|
||||
m_terminal.setCursorPos( m_terminal.getCursorX() + text.length(), m_terminal.getCursorY() );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// scroll
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof Double) )
|
||||
{
|
||||
throw new LuaException( "Expected number" );
|
||||
}
|
||||
|
||||
int y = (int)((Double)args[0]).doubleValue();
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
m_terminal.scroll(y);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// setCursorPos
|
||||
if( args.length != 2 || args[0] == null || !(args[0] instanceof Double) || args[1] == null || !(args[1] instanceof Double) )
|
||||
{
|
||||
throw new LuaException( "Expected number, number" );
|
||||
}
|
||||
int x = (int)((Double)args[0]).doubleValue() - 1;
|
||||
int y = (int)((Double)args[1]).doubleValue() - 1;
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
m_terminal.setCursorPos( x, y );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
// setCursorBlink
|
||||
if( args.length != 1 || args[0] == null || !(args[0] instanceof Boolean) )
|
||||
{
|
||||
throw new LuaException( "Expected boolean" );
|
||||
}
|
||||
boolean b = ((Boolean)args[0]).booleanValue();
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
m_terminal.setCursorBlink( b );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 4:
|
||||
{
|
||||
// getCursorPos
|
||||
int x, y;
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
x = m_terminal.getCursorX();
|
||||
y = m_terminal.getCursorY();
|
||||
}
|
||||
return new Object[] { x + 1, y + 1 };
|
||||
}
|
||||
case 5:
|
||||
{
|
||||
// getSize
|
||||
int width, height;
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
width = m_terminal.getWidth();
|
||||
height = m_terminal.getHeight();
|
||||
}
|
||||
return new Object[] { width, height };
|
||||
}
|
||||
case 6:
|
||||
{
|
||||
// clear
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
m_terminal.clear();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 7:
|
||||
{
|
||||
// clearLine
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
m_terminal.clearLine();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 8:
|
||||
case 9:
|
||||
{
|
||||
// setTextColour/setTextColor
|
||||
int colour = parseColour( args, m_environment.isColour() );
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
m_terminal.setTextColour( colour );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 10:
|
||||
case 11:
|
||||
{
|
||||
// setBackgroundColour/setBackgroundColor
|
||||
int colour = parseColour( args, m_environment.isColour() );
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
m_terminal.setBackgroundColour( colour );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 12:
|
||||
case 13:
|
||||
{
|
||||
// isColour/isColor
|
||||
return new Object[] { m_environment.isColour() };
|
||||
}
|
||||
case 14:
|
||||
case 15:
|
||||
{
|
||||
// getTextColour/getTextColor
|
||||
return encodeColour( m_terminal.getTextColour() );
|
||||
}
|
||||
case 16:
|
||||
case 17:
|
||||
{
|
||||
// getBackgroundColour/getBackgroundColor
|
||||
return encodeColour( m_terminal.getBackgroundColour() );
|
||||
}
|
||||
case 18:
|
||||
{
|
||||
// blit
|
||||
if( args.length < 3 || !(args[0] instanceof String) || !(args[1] instanceof String) || !(args[2] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string, string, string" );
|
||||
}
|
||||
|
||||
String text = (String)args[0];
|
||||
String textColour = (String)args[1];
|
||||
String backgroundColour = (String)args[2];
|
||||
if( textColour.length() != text.length() || backgroundColour.length() != text.length() )
|
||||
{
|
||||
throw new LuaException( "Arguments must be the same length" );
|
||||
}
|
||||
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
m_terminal.blit( text, textColour, backgroundColour );
|
||||
m_terminal.setCursorPos( m_terminal.getCursorX() + text.length(), m_terminal.getCursorY() );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int getHighestBit( int group )
|
||||
{
|
||||
int bit = 0;
|
||||
while( group > 0 )
|
||||
{
|
||||
group >>= 1;
|
||||
bit++;
|
||||
}
|
||||
return bit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,894 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.computer;
|
||||
|
||||
import com.google.common.base.Objects;
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
import dan200.computercraft.api.filesystem.IWritableMount;
|
||||
import dan200.computercraft.api.peripheral.IPeripheral;
|
||||
import dan200.computercraft.core.apis.*;
|
||||
import dan200.computercraft.core.filesystem.FileSystem;
|
||||
import dan200.computercraft.core.filesystem.FileSystemException;
|
||||
import dan200.computercraft.core.lua.ILuaMachine;
|
||||
import dan200.computercraft.core.lua.LuaJLuaMachine;
|
||||
import dan200.computercraft.core.terminal.Terminal;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class Computer
|
||||
{
|
||||
public static final String[] s_sideNames = new String[] {
|
||||
"bottom", "top", "back", "front", "right", "left",
|
||||
};
|
||||
|
||||
private static enum State
|
||||
{
|
||||
Off,
|
||||
Starting,
|
||||
Running,
|
||||
Stopping,
|
||||
}
|
||||
|
||||
private static class APIEnvironment implements IAPIEnvironment
|
||||
{
|
||||
private Computer m_computer;
|
||||
private IAPIEnvironment.IPeripheralChangeListener m_peripheralListener;
|
||||
|
||||
public APIEnvironment( Computer computer )
|
||||
{
|
||||
m_computer = computer;
|
||||
m_peripheralListener = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Computer getComputer()
|
||||
{
|
||||
return m_computer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getComputerID()
|
||||
{
|
||||
return m_computer.assignID();
|
||||
}
|
||||
|
||||
@Override
|
||||
public IComputerEnvironment getComputerEnvironment()
|
||||
{
|
||||
return m_computer.m_environment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Terminal getTerminal()
|
||||
{
|
||||
return m_computer.m_terminal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileSystem getFileSystem()
|
||||
{
|
||||
return m_computer.m_fileSystem;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown()
|
||||
{
|
||||
m_computer.shutdown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reboot()
|
||||
{
|
||||
m_computer.reboot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void queueEvent( String event, Object[] args )
|
||||
{
|
||||
m_computer.queueEvent( event, args );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOutput( int side, int output )
|
||||
{
|
||||
m_computer.setRedstoneOutput( side, output );
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOutput( int side )
|
||||
{
|
||||
return m_computer.getInternalRedstoneOutput( side );
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getInput( int side )
|
||||
{
|
||||
return m_computer.getRedstoneInput( side );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBundledOutput( int side, int output )
|
||||
{
|
||||
m_computer.setBundledRedstoneOutput( side, output );
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBundledOutput( int side )
|
||||
{
|
||||
return m_computer.getInternalBundledRedstoneOutput( side );
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBundledInput( int side )
|
||||
{
|
||||
return m_computer.getBundledRedstoneInput( side );
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPeripheral getPeripheral( int side )
|
||||
{
|
||||
synchronized( m_computer.m_peripherals )
|
||||
{
|
||||
return m_computer.m_peripherals[ side ];
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPeripheralChangeListener( IPeripheralChangeListener listener )
|
||||
{
|
||||
synchronized( m_computer.m_peripherals )
|
||||
{
|
||||
m_peripheralListener = listener;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLabel()
|
||||
{
|
||||
return m_computer.getLabel();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLabel( String label )
|
||||
{
|
||||
m_computer.setLabel( label );
|
||||
}
|
||||
|
||||
public void onPeripheralChanged( int side, IPeripheral peripheral )
|
||||
{
|
||||
synchronized( m_computer.m_peripherals )
|
||||
{
|
||||
if( m_peripheralListener != null )
|
||||
{
|
||||
m_peripheralListener.onPeripheralChanged( side, peripheral );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static IMount s_romMount = null;
|
||||
|
||||
private int m_id;
|
||||
private String m_label;
|
||||
private final IComputerEnvironment m_environment;
|
||||
|
||||
private int m_ticksSinceStart;
|
||||
private boolean m_startRequested;
|
||||
private State m_state;
|
||||
private boolean m_blinking;
|
||||
|
||||
private ILuaMachine m_machine;
|
||||
private List<ILuaAPI> m_apis;
|
||||
private APIEnvironment m_apiEnvironment;
|
||||
|
||||
private Terminal m_terminal;
|
||||
private FileSystem m_fileSystem;
|
||||
private IWritableMount m_rootMount;
|
||||
|
||||
private int[] m_internalOutput;
|
||||
private int[] m_internalBundledOutput;
|
||||
private boolean m_internalOutputChanged;
|
||||
|
||||
private int[] m_externalOutput;
|
||||
private int[] m_externalBundledOutput;
|
||||
private boolean m_externalOutputChanged;
|
||||
|
||||
private int[] m_input;
|
||||
private int[] m_bundledInput;
|
||||
private boolean m_inputChanged;
|
||||
|
||||
private IPeripheral[] m_peripherals;
|
||||
|
||||
public Computer( IComputerEnvironment environment, Terminal terminal, int id )
|
||||
{
|
||||
ComputerThread.start();
|
||||
|
||||
m_id = id;
|
||||
m_label = null;
|
||||
m_environment = environment;
|
||||
|
||||
m_ticksSinceStart = -1;
|
||||
m_startRequested = false;
|
||||
m_state = State.Off;
|
||||
m_blinking = false;
|
||||
|
||||
m_terminal = terminal;
|
||||
m_fileSystem = null;
|
||||
|
||||
m_machine = null;
|
||||
m_apis = new ArrayList<ILuaAPI>();
|
||||
m_apiEnvironment = new APIEnvironment( this );
|
||||
|
||||
m_internalOutput = new int[6];
|
||||
m_internalBundledOutput = new int[6];
|
||||
m_internalOutputChanged = true;
|
||||
|
||||
m_externalOutput = new int[6];
|
||||
m_externalBundledOutput = new int[6];
|
||||
m_externalOutputChanged = true;
|
||||
|
||||
m_input = new int[6];
|
||||
m_bundledInput = new int[6];
|
||||
m_inputChanged = false;
|
||||
|
||||
m_peripherals = new IPeripheral[6];
|
||||
for( int i=0; i<6; ++i )
|
||||
{
|
||||
m_peripherals[i] = null;
|
||||
}
|
||||
|
||||
m_rootMount = null;
|
||||
createAPIs();
|
||||
}
|
||||
|
||||
public IAPIEnvironment getAPIEnvironment()
|
||||
{
|
||||
return m_apiEnvironment;
|
||||
}
|
||||
|
||||
public void turnOn()
|
||||
{
|
||||
if( m_state == State.Off )
|
||||
{
|
||||
m_startRequested = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown()
|
||||
{
|
||||
stopComputer( false );
|
||||
}
|
||||
|
||||
public void reboot()
|
||||
{
|
||||
stopComputer( true );
|
||||
}
|
||||
|
||||
public boolean isOn()
|
||||
{
|
||||
synchronized( this )
|
||||
{
|
||||
return m_state == State.Running;
|
||||
}
|
||||
}
|
||||
|
||||
public void abort( boolean hard )
|
||||
{
|
||||
synchronized( this )
|
||||
{
|
||||
if( m_state == State.Running )
|
||||
{
|
||||
if( hard )
|
||||
{
|
||||
m_machine.hardAbort( "Too long without yielding" );
|
||||
}
|
||||
else
|
||||
{
|
||||
m_machine.softAbort( "Too long without yielding" );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void unload()
|
||||
{
|
||||
synchronized( this )
|
||||
{
|
||||
stopComputer( false );
|
||||
}
|
||||
}
|
||||
|
||||
public int getID()
|
||||
{
|
||||
return m_id;
|
||||
}
|
||||
|
||||
public int assignID()
|
||||
{
|
||||
if( m_id < 0 )
|
||||
{
|
||||
m_id = m_environment.assignNewID();
|
||||
}
|
||||
return m_id;
|
||||
}
|
||||
|
||||
public void setID( int id )
|
||||
{
|
||||
m_id = id;
|
||||
}
|
||||
|
||||
public String getLabel()
|
||||
{
|
||||
return m_label;
|
||||
}
|
||||
|
||||
public void setLabel( String label )
|
||||
{
|
||||
if( !Objects.equal( label, m_label ) )
|
||||
{
|
||||
m_label = label;
|
||||
m_externalOutputChanged = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void advance( double _dt )
|
||||
{
|
||||
synchronized( this )
|
||||
{
|
||||
// Start after a number of ticks
|
||||
if( m_ticksSinceStart >= 0 )
|
||||
{
|
||||
m_ticksSinceStart++;
|
||||
}
|
||||
if( m_startRequested && (m_ticksSinceStart < 0 || m_ticksSinceStart > 50) )
|
||||
{
|
||||
startComputer();
|
||||
m_startRequested = false;
|
||||
}
|
||||
|
||||
if( m_state == State.Running )
|
||||
{
|
||||
// Fire the redstone event if our redstone input has changed
|
||||
synchronized( m_input )
|
||||
{
|
||||
if( m_inputChanged )
|
||||
{
|
||||
queueEvent( "redstone", null );
|
||||
m_inputChanged = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Advance our APIs
|
||||
synchronized( m_apis )
|
||||
{
|
||||
Iterator<ILuaAPI> it = m_apis.iterator();
|
||||
while( it.hasNext() )
|
||||
{
|
||||
ILuaAPI api = it.next();
|
||||
api.advance( _dt );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Set outputchanged if the internal redstone has changed
|
||||
synchronized( m_internalOutput )
|
||||
{
|
||||
if( m_internalOutputChanged )
|
||||
{
|
||||
boolean changed = false;
|
||||
for( int i=0; i<6; ++i )
|
||||
{
|
||||
if( m_externalOutput[i] != m_internalOutput[i] )
|
||||
{
|
||||
m_externalOutput[ i ] = m_internalOutput[ i ];
|
||||
changed = true;
|
||||
}
|
||||
if( m_externalBundledOutput[i] != m_internalBundledOutput[i] )
|
||||
{
|
||||
m_externalBundledOutput[ i ] = m_internalBundledOutput[ i ];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
m_internalOutputChanged = false;
|
||||
if( changed )
|
||||
{
|
||||
m_externalOutputChanged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Set outputchanged if the terminal has changed from blinking to not
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
boolean blinking =
|
||||
m_terminal.getCursorBlink() &&
|
||||
m_terminal.getCursorX() >= 0 && m_terminal.getCursorX() < m_terminal.getWidth() &&
|
||||
m_terminal.getCursorY() >= 0 && m_terminal.getCursorY() < m_terminal.getHeight();
|
||||
|
||||
if( blinking != m_blinking )
|
||||
{
|
||||
m_blinking = blinking;
|
||||
m_externalOutputChanged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean pollChanged()
|
||||
{
|
||||
return m_externalOutputChanged;
|
||||
}
|
||||
|
||||
public void clearChanged()
|
||||
{
|
||||
m_externalOutputChanged = false;
|
||||
}
|
||||
|
||||
public boolean isBlinking()
|
||||
{
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
return isOn() && m_blinking;
|
||||
}
|
||||
}
|
||||
|
||||
public IWritableMount getRootMount()
|
||||
{
|
||||
if( m_rootMount == null )
|
||||
{
|
||||
m_rootMount = m_environment.createSaveDirMount( "computer/" + assignID(), m_environment.getComputerSpaceLimit() );
|
||||
}
|
||||
return m_rootMount;
|
||||
}
|
||||
|
||||
// FileSystem
|
||||
|
||||
private boolean initFileSystem()
|
||||
{
|
||||
// Create the file system
|
||||
int id = assignID();
|
||||
try
|
||||
{
|
||||
m_fileSystem = new FileSystem( "hdd", getRootMount() );
|
||||
if( s_romMount == null )
|
||||
{
|
||||
s_romMount = m_environment.createResourceMount( "computercraft", "lua/rom" );
|
||||
}
|
||||
if( s_romMount != null )
|
||||
{
|
||||
m_fileSystem.mount( "rom", "rom", s_romMount );
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
catch( FileSystemException e )
|
||||
{
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Redstone
|
||||
|
||||
public int getRedstoneOutput( int side )
|
||||
{
|
||||
synchronized( m_internalOutput )
|
||||
{
|
||||
return isOn() ? m_externalOutput[side] : 0;
|
||||
}
|
||||
}
|
||||
|
||||
private int getInternalRedstoneOutput( int side )
|
||||
{
|
||||
synchronized( m_internalOutput )
|
||||
{
|
||||
return isOn() ? m_internalOutput[side] : 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void setRedstoneOutput( int side, int level )
|
||||
{
|
||||
synchronized( m_internalOutput )
|
||||
{
|
||||
if( m_internalOutput[side] != level )
|
||||
{
|
||||
m_internalOutput[side] = level;
|
||||
m_internalOutputChanged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setRedstoneInput( int side, int level )
|
||||
{
|
||||
synchronized( m_input )
|
||||
{
|
||||
if( m_input[side] != level )
|
||||
{
|
||||
m_input[side] = level;
|
||||
m_inputChanged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int getRedstoneInput( int side )
|
||||
{
|
||||
synchronized( m_input )
|
||||
{
|
||||
return m_input[side];
|
||||
}
|
||||
}
|
||||
|
||||
public int getBundledRedstoneOutput( int side )
|
||||
{
|
||||
synchronized( m_internalOutput )
|
||||
{
|
||||
return isOn() ? m_externalBundledOutput[side] : 0;
|
||||
}
|
||||
}
|
||||
|
||||
private int getInternalBundledRedstoneOutput( int side )
|
||||
{
|
||||
synchronized( m_internalOutput )
|
||||
{
|
||||
return isOn() ? m_internalBundledOutput[side] : 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void setBundledRedstoneOutput( int side, int combination )
|
||||
{
|
||||
synchronized( m_internalOutput )
|
||||
{
|
||||
if( m_internalBundledOutput[side] != combination )
|
||||
{
|
||||
m_internalBundledOutput[side] = combination;
|
||||
m_internalOutputChanged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setBundledRedstoneInput( int side, int combination )
|
||||
{
|
||||
synchronized( m_input )
|
||||
{
|
||||
if( m_bundledInput[side] != combination )
|
||||
{
|
||||
m_bundledInput[side] = combination;
|
||||
m_inputChanged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int getBundledRedstoneInput( int side )
|
||||
{
|
||||
synchronized( m_input )
|
||||
{
|
||||
return m_bundledInput[side];
|
||||
}
|
||||
}
|
||||
|
||||
// Peripherals
|
||||
|
||||
public void addAPI( ILuaAPI api )
|
||||
{
|
||||
m_apis.add( api );
|
||||
}
|
||||
|
||||
public void setPeripheral( int side, IPeripheral peripheral )
|
||||
{
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
IPeripheral existing = m_peripherals[side];
|
||||
if( (existing == null && peripheral != null) ||
|
||||
(existing != null && peripheral == null) ||
|
||||
(existing != null && !existing.equals( peripheral )) )
|
||||
{
|
||||
m_peripherals[side] = peripheral;
|
||||
m_apiEnvironment.onPeripheralChanged( side, peripheral );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public IPeripheral getPeripheral( int side )
|
||||
{
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
return m_peripherals[side];
|
||||
}
|
||||
}
|
||||
|
||||
// Lua
|
||||
|
||||
private void createAPIs()
|
||||
{
|
||||
m_apis.add( new TermAPI( m_apiEnvironment ) );
|
||||
m_apis.add( new RedstoneAPI( m_apiEnvironment ) );
|
||||
m_apis.add( new FSAPI( m_apiEnvironment ) );
|
||||
m_apis.add( new PeripheralAPI( m_apiEnvironment ) );
|
||||
m_apis.add( new OSAPI( m_apiEnvironment ) );
|
||||
m_apis.add( new BitAPI( m_apiEnvironment ) );
|
||||
//m_apis.add( new BufferAPI( m_apiEnvironment ) );
|
||||
if( ComputerCraft.http_enable )
|
||||
{
|
||||
m_apis.add( new HTTPAPI( m_apiEnvironment ) );
|
||||
}
|
||||
}
|
||||
|
||||
private void initLua()
|
||||
{
|
||||
// Create the lua machine
|
||||
ILuaMachine machine = new LuaJLuaMachine( this );
|
||||
|
||||
// Add the APIs
|
||||
Iterator<ILuaAPI> it = m_apis.iterator();
|
||||
while( it.hasNext() )
|
||||
{
|
||||
ILuaAPI api = it.next();
|
||||
machine.addAPI( api );
|
||||
api.startup();
|
||||
}
|
||||
|
||||
// Load the bios resource
|
||||
InputStream biosStream;
|
||||
try
|
||||
{
|
||||
biosStream = Computer.class.getResourceAsStream( "/assets/computercraft/lua/bios.lua" );
|
||||
}
|
||||
catch( Exception e )
|
||||
{
|
||||
biosStream = null;
|
||||
}
|
||||
|
||||
// Start the machine running the bios resource
|
||||
if( biosStream != null )
|
||||
{
|
||||
machine.loadBios( biosStream );
|
||||
try {
|
||||
biosStream.close();
|
||||
} catch( IOException e ) {
|
||||
// meh
|
||||
}
|
||||
|
||||
if( machine.isFinished() )
|
||||
{
|
||||
m_terminal.reset();
|
||||
m_terminal.write("Error starting bios.lua" );
|
||||
m_terminal.setCursorPos( 0, 1 );
|
||||
m_terminal.write( "ComputerCraft may be installed incorrectly" );
|
||||
|
||||
machine.unload();
|
||||
m_machine = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_machine = machine;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_terminal.reset();
|
||||
m_terminal.write("Error loading bios.lua" );
|
||||
m_terminal.setCursorPos( 0, 1 );
|
||||
m_terminal.write( "ComputerCraft may be installed incorrectly" );
|
||||
|
||||
machine.unload();
|
||||
m_machine = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void startComputer()
|
||||
{
|
||||
synchronized( this )
|
||||
{
|
||||
if( m_state != State.Off )
|
||||
{
|
||||
return;
|
||||
}
|
||||
m_state = State.Starting;
|
||||
m_ticksSinceStart = 0;
|
||||
}
|
||||
|
||||
// Turn the computercraft on
|
||||
final Computer computer = this;
|
||||
ComputerThread.queueTask( new ITask() {
|
||||
@Override
|
||||
public Computer getOwner()
|
||||
{
|
||||
return computer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute()
|
||||
{
|
||||
synchronized( this )
|
||||
{
|
||||
if( m_state != State.Starting )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Init terminal
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
m_terminal.reset();
|
||||
}
|
||||
|
||||
// Init filesystem
|
||||
if( !initFileSystem() )
|
||||
{
|
||||
// Init failed, so shutdown
|
||||
m_terminal.reset();
|
||||
m_terminal.write( "Error mounting lua/rom" );
|
||||
m_terminal.setCursorPos( 0, 1 );
|
||||
m_terminal.write( "ComputerCraft may be installed incorrectly" );
|
||||
|
||||
m_state = State.Running;
|
||||
stopComputer( false );
|
||||
return;
|
||||
}
|
||||
|
||||
// Init lua
|
||||
initLua();
|
||||
if( m_machine == null )
|
||||
{
|
||||
m_terminal.reset();
|
||||
m_terminal.write( "Error loading bios.lua" );
|
||||
m_terminal.setCursorPos( 0, 1 );
|
||||
m_terminal.write( "ComputerCraft may be installed incorrectly" );
|
||||
|
||||
// Init failed, so shutdown
|
||||
m_state = State.Running;
|
||||
stopComputer( false );
|
||||
return;
|
||||
}
|
||||
|
||||
// Start a new state
|
||||
m_state = State.Running;
|
||||
synchronized( m_machine )
|
||||
{
|
||||
m_machine.handleEvent( null, null );
|
||||
}
|
||||
}
|
||||
}
|
||||
}, computer );
|
||||
}
|
||||
|
||||
private void stopComputer( final boolean reboot )
|
||||
{
|
||||
synchronized( this )
|
||||
{
|
||||
if( m_state != State.Running )
|
||||
{
|
||||
return;
|
||||
}
|
||||
m_state = State.Stopping;
|
||||
}
|
||||
|
||||
// Turn the computercraft off
|
||||
final Computer computer = this;
|
||||
ComputerThread.queueTask( new ITask() {
|
||||
@Override
|
||||
public Computer getOwner()
|
||||
{
|
||||
return computer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute()
|
||||
{
|
||||
synchronized( this )
|
||||
{
|
||||
if( m_state != State.Stopping )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Shutdown our APIs
|
||||
synchronized( m_apis )
|
||||
{
|
||||
Iterator<ILuaAPI> it = m_apis.iterator();
|
||||
while( it.hasNext() )
|
||||
{
|
||||
ILuaAPI api = it.next();
|
||||
api.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown terminal and filesystem
|
||||
if( m_fileSystem != null )
|
||||
{
|
||||
m_fileSystem.unload();
|
||||
m_fileSystem = null;
|
||||
}
|
||||
|
||||
if( m_machine != null )
|
||||
{
|
||||
synchronized( m_terminal )
|
||||
{
|
||||
m_terminal.reset();
|
||||
}
|
||||
|
||||
synchronized( m_machine )
|
||||
{
|
||||
m_machine.unload();
|
||||
m_machine = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Reset redstone output
|
||||
synchronized( m_internalOutput )
|
||||
{
|
||||
for( int i=0; i<6; ++i )
|
||||
{
|
||||
m_internalOutput[i] = 0;
|
||||
m_internalBundledOutput[i] = 0;
|
||||
}
|
||||
m_internalOutputChanged = true;
|
||||
}
|
||||
|
||||
m_state = State.Off;
|
||||
if( reboot )
|
||||
{
|
||||
m_startRequested = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}, computer );
|
||||
}
|
||||
|
||||
public void queueEvent( final String event, final Object[] arguments )
|
||||
{
|
||||
synchronized( this )
|
||||
{
|
||||
if( m_state != State.Running )
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
final Computer computer = this;
|
||||
ITask task = new ITask() {
|
||||
@Override
|
||||
public Computer getOwner()
|
||||
{
|
||||
return computer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute()
|
||||
{
|
||||
synchronized( this )
|
||||
{
|
||||
if( m_state != State.Running )
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
synchronized( m_machine )
|
||||
{
|
||||
m_machine.handleEvent( event, arguments );
|
||||
if( m_machine.isFinished() )
|
||||
{
|
||||
m_terminal.reset();
|
||||
m_terminal.write( "Error resuming bios.lua" );
|
||||
m_terminal.setCursorPos( 0, 1 );
|
||||
m_terminal.write( "ComputerCraft may be installed incorrectly" );
|
||||
|
||||
stopComputer( false );
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ComputerThread.queueTask( task, computer );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.computer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
|
||||
public class ComputerThread
|
||||
{
|
||||
private static Object m_lock;
|
||||
|
||||
private static Thread m_thread;
|
||||
private static WeakHashMap <Object, LinkedBlockingQueue<ITask>> m_computerTasks;
|
||||
private static ArrayList <LinkedBlockingQueue<ITask>> m_computerTasksActive;
|
||||
private static ArrayList <LinkedBlockingQueue<ITask>> m_computerTasksPending;
|
||||
private static Object m_defaultQueue;
|
||||
private static Object m_monitor;
|
||||
|
||||
private static boolean m_running;
|
||||
private static boolean m_stopped;
|
||||
|
||||
static
|
||||
{
|
||||
m_lock = new Object();
|
||||
m_thread = null;
|
||||
m_computerTasks = new WeakHashMap<Object, LinkedBlockingQueue<ITask>>();
|
||||
m_computerTasksPending = new ArrayList<LinkedBlockingQueue<ITask>>();
|
||||
m_computerTasksActive = new ArrayList<LinkedBlockingQueue<ITask>>();
|
||||
m_defaultQueue = new Object();
|
||||
m_monitor = new Object();
|
||||
m_running = false;
|
||||
m_stopped = false;
|
||||
}
|
||||
|
||||
public static void start()
|
||||
{
|
||||
synchronized( m_lock )
|
||||
{
|
||||
if( m_running )
|
||||
{
|
||||
m_stopped = false;
|
||||
return;
|
||||
}
|
||||
|
||||
m_thread = new Thread( new Runnable() {
|
||||
public void run()
|
||||
{
|
||||
while( true )
|
||||
{
|
||||
synchronized( m_computerTasksPending )
|
||||
{
|
||||
if (!m_computerTasksPending.isEmpty())
|
||||
{
|
||||
Iterator<LinkedBlockingQueue<ITask>> it = m_computerTasksPending.iterator();
|
||||
while(it.hasNext())
|
||||
{
|
||||
LinkedBlockingQueue<ITask> queue = it.next();
|
||||
|
||||
if (!m_computerTasksActive.contains(queue))
|
||||
{
|
||||
m_computerTasksActive.add(queue);
|
||||
}
|
||||
it.remove();
|
||||
}
|
||||
/*
|
||||
m_computerTasksActive.addAll(m_computerTasksPending); // put any that have been added since
|
||||
m_computerTasksPending.clear();
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
Iterator<LinkedBlockingQueue<ITask>> it = m_computerTasksActive.iterator();
|
||||
|
||||
while (it.hasNext())
|
||||
{
|
||||
LinkedBlockingQueue<ITask> queue = it.next();
|
||||
|
||||
if (queue == null || queue.isEmpty()) // we don't need the blocking part of the queue. Null check to ensure it exists due to a weird NPE I got
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
synchronized( m_lock )
|
||||
{
|
||||
if( m_stopped )
|
||||
{
|
||||
m_running = false;
|
||||
m_thread = null;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
final ITask task = queue.take();
|
||||
|
||||
// Create the task
|
||||
Thread worker = new Thread( new Runnable() {
|
||||
public void run() {
|
||||
try {
|
||||
task.execute();
|
||||
} catch( Throwable e ) {
|
||||
System.out.println( "ComputerCraft: Error running task." );
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
} );
|
||||
|
||||
// Run the task
|
||||
worker.start();
|
||||
worker.join( 7000 );
|
||||
|
||||
if( worker.isAlive() )
|
||||
{
|
||||
// Task ran for too long
|
||||
// Initiate escape plan
|
||||
Computer computer = task.getOwner();
|
||||
if( computer != null )
|
||||
{
|
||||
// Step 1: Soft abort
|
||||
computer.abort( false );
|
||||
worker.join( 1500 );
|
||||
|
||||
if( worker.isAlive() )
|
||||
{
|
||||
// Step 2: Hard abort
|
||||
computer.abort( true );
|
||||
worker.join( 1500 );
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3: abandon
|
||||
if( worker.isAlive() )
|
||||
{
|
||||
//System.out.println( "computercraft: Warning! Failed to abort Computer " + computercraft.getDescription() + ". Dangling lua thread could cause errors." );
|
||||
worker.interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch( InterruptedException e )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
synchronized (queue)
|
||||
{
|
||||
if (queue.isEmpty())
|
||||
{
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while (m_computerTasksActive.isEmpty() && m_computerTasksPending.isEmpty())
|
||||
{
|
||||
synchronized (m_monitor)
|
||||
{
|
||||
try
|
||||
{
|
||||
m_monitor.wait();
|
||||
}
|
||||
catch( InterruptedException e )
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, "Computer Dispatch Thread" );
|
||||
|
||||
m_thread.start();
|
||||
m_running = true;
|
||||
}
|
||||
}
|
||||
|
||||
public static void stop()
|
||||
{
|
||||
synchronized( m_lock )
|
||||
{
|
||||
if( m_running )
|
||||
{
|
||||
m_stopped = true;
|
||||
m_thread.interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void queueTask( ITask _task, Computer computer )
|
||||
{
|
||||
Object queueObject = computer;
|
||||
|
||||
if (queueObject == null)
|
||||
{
|
||||
queueObject = m_defaultQueue;
|
||||
}
|
||||
|
||||
LinkedBlockingQueue<ITask> queue = m_computerTasks.get(queueObject);
|
||||
|
||||
if (queue == null)
|
||||
{
|
||||
m_computerTasks.put(queueObject, queue = new LinkedBlockingQueue<ITask>(256));
|
||||
}
|
||||
|
||||
synchronized ( m_computerTasksPending )
|
||||
{
|
||||
if( queue.offer( _task ) )
|
||||
{
|
||||
if( !m_computerTasksPending.contains( queue ) )
|
||||
{
|
||||
m_computerTasksPending.add( queue );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//System.out.println( "Event queue overflow" );
|
||||
}
|
||||
}
|
||||
|
||||
synchronized (m_monitor)
|
||||
{
|
||||
m_monitor.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.computer;
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
import dan200.computercraft.api.filesystem.IWritableMount;
|
||||
|
||||
public interface IComputerEnvironment
|
||||
{
|
||||
public int getDay();
|
||||
public double getTimeOfDay();
|
||||
public boolean isColour();
|
||||
public long getComputerSpaceLimit();
|
||||
public String getHostString();
|
||||
|
||||
public int assignNewID();
|
||||
public IWritableMount createSaveDirMount( String subPath, long capacity );
|
||||
public IMount createResourceMount( String domain, String subPath );
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.computer;
|
||||
|
||||
public interface ITask
|
||||
{
|
||||
public Computer getOwner();
|
||||
public void execute();
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.computer;
|
||||
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class MainThread
|
||||
{
|
||||
private static final int MAX_TASKS_PER_TICK = 1000;
|
||||
private static final int MAX_TASKS_TOTAL = 50000;
|
||||
|
||||
private static final LinkedList<ITask> m_outstandingTasks = new LinkedList<ITask>();
|
||||
private static final Object m_nextUnusedTaskIDLock = new Object();
|
||||
private static long m_nextUnusedTaskID = 0;
|
||||
|
||||
public static long getUniqueTaskID()
|
||||
{
|
||||
synchronized( m_nextUnusedTaskIDLock )
|
||||
{
|
||||
return ++m_nextUnusedTaskID;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean queueTask( ITask task )
|
||||
{
|
||||
synchronized( m_outstandingTasks )
|
||||
{
|
||||
if( m_outstandingTasks.size() < MAX_TASKS_TOTAL )
|
||||
{
|
||||
m_outstandingTasks.addLast( task );
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void executePendingTasks()
|
||||
{
|
||||
int tasksThisTick = 0;
|
||||
while( tasksThisTick < MAX_TASKS_PER_TICK )
|
||||
{
|
||||
ITask task = null;
|
||||
synchronized( m_outstandingTasks )
|
||||
{
|
||||
if( m_outstandingTasks.size() > 0 )
|
||||
{
|
||||
task = m_outstandingTasks.removeFirst();
|
||||
}
|
||||
}
|
||||
if( task != null )
|
||||
{
|
||||
task.execute();
|
||||
++tasksThisTick;
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class ComboMount implements IMount
|
||||
{
|
||||
private IMount[] m_parts;
|
||||
|
||||
public ComboMount( IMount[] parts )
|
||||
{
|
||||
m_parts = parts;
|
||||
}
|
||||
|
||||
// IMount implementation
|
||||
|
||||
@Override
|
||||
public boolean exists( String path ) throws IOException
|
||||
{
|
||||
for( int i=m_parts.length-1; i>=0; --i )
|
||||
{
|
||||
IMount part = m_parts[i];
|
||||
if( part.exists( path ) )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDirectory( String path ) throws IOException
|
||||
{
|
||||
for( int i=m_parts.length-1; i>=0; --i )
|
||||
{
|
||||
IMount part = m_parts[i];
|
||||
if( part.isDirectory( path ) )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void list( String path, List<String> contents ) throws IOException
|
||||
{
|
||||
// Combine the lists from all the mounts
|
||||
List<String> foundFiles = null;
|
||||
int foundDirs = 0;
|
||||
for( int i=m_parts.length-1; i>=0; --i )
|
||||
{
|
||||
IMount part = m_parts[i];
|
||||
if( part.exists( path ) && part.isDirectory( path ) )
|
||||
{
|
||||
if( foundFiles == null )
|
||||
{
|
||||
foundFiles = new ArrayList<String>();
|
||||
}
|
||||
part.list( path, foundFiles );
|
||||
foundDirs++;
|
||||
}
|
||||
}
|
||||
|
||||
if( foundDirs == 1 )
|
||||
{
|
||||
// We found one directory, so we know it already doesn't contain duplicates
|
||||
contents.addAll( foundFiles );
|
||||
}
|
||||
else if( foundDirs > 1 )
|
||||
{
|
||||
// We found multiple directories, so filter for duplicates
|
||||
Set<String> seen = new HashSet<String>();
|
||||
for( int i=0; i<foundFiles.size(); ++i )
|
||||
{
|
||||
String file = foundFiles.get(i);
|
||||
if( seen.add( file ) )
|
||||
{
|
||||
contents.add( file );
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new IOException( "Not a directory" );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize( String path ) throws IOException
|
||||
{
|
||||
for( int i=m_parts.length-1; i>=0; --i )
|
||||
{
|
||||
IMount part = m_parts[i];
|
||||
if( part.exists( path ) )
|
||||
{
|
||||
return part.getSize( path );
|
||||
}
|
||||
}
|
||||
throw new IOException( "No such file" );
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream openForRead( String path ) throws IOException
|
||||
{
|
||||
for( int i=m_parts.length-1; i>=0; --i )
|
||||
{
|
||||
IMount part = m_parts[i];
|
||||
if( part.exists( path ) && !part.isDirectory( path ) )
|
||||
{
|
||||
return part.openForRead( path );
|
||||
}
|
||||
}
|
||||
throw new IOException( "No such file" );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
public class EmptyMount implements IMount
|
||||
{
|
||||
public EmptyMount()
|
||||
{
|
||||
}
|
||||
|
||||
// IMount implementation
|
||||
|
||||
@Override
|
||||
public boolean exists( String path ) throws IOException
|
||||
{
|
||||
return path.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDirectory( String path ) throws IOException
|
||||
{
|
||||
return path.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void list( String path, List<String> contents ) throws IOException
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize( String path ) throws IOException
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream openForRead( String path ) throws IOException
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
import dan200.computercraft.api.filesystem.IWritableMount;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.List;
|
||||
|
||||
public class FileMount implements IWritableMount
|
||||
{
|
||||
private static int MINIMUM_FILE_SIZE = 500;
|
||||
|
||||
private class CountingOutputStream extends OutputStream
|
||||
{
|
||||
private OutputStream m_innerStream;
|
||||
private long m_ignoredBytesLeft;
|
||||
|
||||
public CountingOutputStream( OutputStream innerStream, long bytesToIgnore )
|
||||
{
|
||||
m_innerStream = innerStream;
|
||||
m_ignoredBytesLeft = bytesToIgnore;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
m_innerStream.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() throws IOException
|
||||
{
|
||||
m_innerStream.flush();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write( byte[] b ) throws IOException
|
||||
{
|
||||
count( b.length );
|
||||
m_innerStream.write( b );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write( byte[] b, int off, int len ) throws IOException
|
||||
{
|
||||
count( len );
|
||||
m_innerStream.write( b, off, len );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write( int b ) throws IOException
|
||||
{
|
||||
count( 1 );
|
||||
m_innerStream.write( b );
|
||||
}
|
||||
|
||||
private void count( long n ) throws IOException
|
||||
{
|
||||
m_ignoredBytesLeft -= n;
|
||||
if( m_ignoredBytesLeft < 0 )
|
||||
{
|
||||
long newBytes = -m_ignoredBytesLeft;
|
||||
m_ignoredBytesLeft = 0;
|
||||
|
||||
long bytesLeft = m_capacity - m_usedSpace;
|
||||
if( newBytes > bytesLeft )
|
||||
{
|
||||
throw new IOException( "Out of space" );
|
||||
}
|
||||
else
|
||||
{
|
||||
m_usedSpace += newBytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private File m_rootPath;
|
||||
private long m_capacity;
|
||||
private long m_usedSpace;
|
||||
|
||||
public FileMount( File rootPath, long capacity )
|
||||
{
|
||||
m_rootPath = rootPath;
|
||||
m_capacity = capacity + MINIMUM_FILE_SIZE;
|
||||
m_usedSpace = created() ? measureUsedSpace( m_rootPath ) : MINIMUM_FILE_SIZE;
|
||||
}
|
||||
|
||||
// IMount implementation
|
||||
|
||||
@Override
|
||||
public boolean exists( String path ) throws IOException
|
||||
{
|
||||
if( !created() )
|
||||
{
|
||||
return path.length() == 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
File file = getRealPath( path );
|
||||
return file.exists();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDirectory( String path ) throws IOException
|
||||
{
|
||||
if( !created() )
|
||||
{
|
||||
return path.length() == 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
File file = getRealPath( path );
|
||||
return file.exists() && file.isDirectory();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void list( String path, List<String> contents ) throws IOException
|
||||
{
|
||||
if( !created() )
|
||||
{
|
||||
if( path.length() != 0 )
|
||||
{
|
||||
throw new IOException( "Not a directory" );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
File file = getRealPath( path );
|
||||
if( file.exists() && file.isDirectory() )
|
||||
{
|
||||
String[] paths = file.list();
|
||||
for( String subPath : paths )
|
||||
{
|
||||
if( new File( file, subPath ).exists() )
|
||||
{
|
||||
contents.add( subPath );
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new IOException( "Not a directory" );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize( String path ) throws IOException
|
||||
{
|
||||
if( !created() )
|
||||
{
|
||||
if( path.length() == 0 )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
File file = getRealPath( path );
|
||||
if( file.exists() )
|
||||
{
|
||||
if( file.isDirectory() )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
return file.length();
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new IOException( "No such file" );
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream openForRead( String path ) throws IOException
|
||||
{
|
||||
if( created() )
|
||||
{
|
||||
File file = getRealPath( path );
|
||||
if( file.exists() && !file.isDirectory() )
|
||||
{
|
||||
return new FileInputStream( file );
|
||||
}
|
||||
}
|
||||
throw new IOException( "No such file" );
|
||||
}
|
||||
|
||||
// IWritableMount implementation
|
||||
|
||||
@Override
|
||||
public void makeDirectory( String path ) throws IOException
|
||||
{
|
||||
create();
|
||||
File file = getRealPath( path );
|
||||
if( file.exists() )
|
||||
{
|
||||
if( !file.isDirectory() )
|
||||
{
|
||||
throw new IOException( "File exists" );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int dirsToCreate = 1;
|
||||
File parent = file.getParentFile();
|
||||
while( !parent.exists() )
|
||||
{
|
||||
++dirsToCreate;
|
||||
parent = parent.getParentFile();
|
||||
}
|
||||
|
||||
if( getRemainingSpace() < dirsToCreate * MINIMUM_FILE_SIZE )
|
||||
{
|
||||
throw new IOException( "Out of space" );
|
||||
}
|
||||
|
||||
boolean success = file.mkdirs();
|
||||
if( success )
|
||||
{
|
||||
m_usedSpace += dirsToCreate * MINIMUM_FILE_SIZE;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new IOException( "Access denied" );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete( String path ) throws IOException
|
||||
{
|
||||
if( path.length() == 0 )
|
||||
{
|
||||
throw new IOException( "Access denied" );
|
||||
}
|
||||
|
||||
if( created() )
|
||||
{
|
||||
File file = getRealPath( path );
|
||||
if( file.exists() )
|
||||
{
|
||||
deleteRecursively( file );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteRecursively( File file ) throws IOException
|
||||
{
|
||||
// Empty directories first
|
||||
if( file.isDirectory() )
|
||||
{
|
||||
String[] children = file.list();
|
||||
for( int i=0; i<children.length; i++ )
|
||||
{
|
||||
deleteRecursively( new File( file, children[i] ) );
|
||||
}
|
||||
}
|
||||
|
||||
// Then delete
|
||||
long fileSize = file.isDirectory() ? 0 : file.length();
|
||||
boolean success = file.delete();
|
||||
if( success )
|
||||
{
|
||||
m_usedSpace -= Math.max( MINIMUM_FILE_SIZE, fileSize );
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new IOException( "Access denied" );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OutputStream openForWrite( String path ) throws IOException
|
||||
{
|
||||
create();
|
||||
File file = getRealPath( path );
|
||||
if( file.exists() && file.isDirectory() )
|
||||
{
|
||||
throw new IOException( "Cannot write to directory" );
|
||||
}
|
||||
else
|
||||
{
|
||||
if( !file.exists() )
|
||||
{
|
||||
if( getRemainingSpace() < MINIMUM_FILE_SIZE )
|
||||
{
|
||||
throw new IOException( "Out of space" );
|
||||
}
|
||||
else
|
||||
{
|
||||
m_usedSpace += MINIMUM_FILE_SIZE;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_usedSpace -= Math.max( file.length(), MINIMUM_FILE_SIZE );
|
||||
m_usedSpace += MINIMUM_FILE_SIZE;
|
||||
}
|
||||
return new CountingOutputStream( new FileOutputStream( file, false ), MINIMUM_FILE_SIZE );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OutputStream openForAppend( String path ) throws IOException
|
||||
{
|
||||
if( created() )
|
||||
{
|
||||
File file = getRealPath( path );
|
||||
if( !file.exists() )
|
||||
{
|
||||
throw new IOException( "No such file" );
|
||||
}
|
||||
else if( file.isDirectory() )
|
||||
{
|
||||
throw new IOException( "Cannot write to directory" );
|
||||
}
|
||||
else
|
||||
{
|
||||
return new CountingOutputStream( new FileOutputStream( file, true ), Math.max( MINIMUM_FILE_SIZE - file.length(), 0 ) );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new IOException( "No such file" );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getRemainingSpace() throws IOException
|
||||
{
|
||||
return Math.max( m_capacity - m_usedSpace, 0 );
|
||||
}
|
||||
|
||||
public File getRealPath( String path )
|
||||
{
|
||||
return new File( m_rootPath, path );
|
||||
}
|
||||
|
||||
private boolean created()
|
||||
{
|
||||
return m_rootPath.exists();
|
||||
}
|
||||
|
||||
private void create() throws IOException
|
||||
{
|
||||
if( !m_rootPath.exists() )
|
||||
{
|
||||
boolean success = m_rootPath.mkdirs();
|
||||
if( !success )
|
||||
{
|
||||
throw new IOException( "Access denied" );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private long measureUsedSpace( File file )
|
||||
{
|
||||
if( !file.exists() )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
if( file.isDirectory() )
|
||||
{
|
||||
long size = MINIMUM_FILE_SIZE;
|
||||
String[] contents = file.list();
|
||||
for( int i=0; i<contents.length; ++i )
|
||||
{
|
||||
size += measureUsedSpace( new File( file, contents[i] ) );
|
||||
}
|
||||
return size;
|
||||
}
|
||||
else
|
||||
{
|
||||
return Math.max( file.length(), MINIMUM_FILE_SIZE );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,985 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
import dan200.computercraft.api.filesystem.IWritableMount;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class FileSystem
|
||||
{
|
||||
private class MountWrapper
|
||||
{
|
||||
private String m_label;
|
||||
private String m_location;
|
||||
|
||||
private IMount m_mount;
|
||||
private IWritableMount m_writableMount;
|
||||
|
||||
public MountWrapper( String label, String location, IMount mount )
|
||||
{
|
||||
m_label = label;
|
||||
m_location = location;
|
||||
m_mount = mount;
|
||||
m_writableMount = null;
|
||||
}
|
||||
|
||||
public MountWrapper( String label, String location, IWritableMount mount )
|
||||
{
|
||||
this( label, location, (IMount)mount );
|
||||
m_writableMount = mount;
|
||||
}
|
||||
|
||||
public String getLabel()
|
||||
{
|
||||
return m_label;
|
||||
}
|
||||
|
||||
public String getLocation()
|
||||
{
|
||||
return m_location;
|
||||
}
|
||||
|
||||
public long getFreeSpace()
|
||||
{
|
||||
if( m_writableMount == null )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return m_writableMount.getRemainingSpace();
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isReadOnly( String path ) throws FileSystemException
|
||||
{
|
||||
return (m_writableMount == null);
|
||||
}
|
||||
|
||||
// IMount forwarders:
|
||||
|
||||
public boolean exists( String path ) throws FileSystemException
|
||||
{
|
||||
path = toLocal( path );
|
||||
try
|
||||
{
|
||||
return m_mount.exists( path );
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isDirectory( String path ) throws FileSystemException
|
||||
{
|
||||
path = toLocal( path );
|
||||
try
|
||||
{
|
||||
return m_mount.exists( path ) && m_mount.isDirectory( path );
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public void list( String path, List<String> contents ) throws FileSystemException
|
||||
{
|
||||
path = toLocal( path );
|
||||
try
|
||||
{
|
||||
if( m_mount.exists( path ) && m_mount.isDirectory( path ) )
|
||||
{
|
||||
m_mount.list( path, contents );
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new FileSystemException( "Not a directory" );
|
||||
}
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public long getSize( String path ) throws FileSystemException
|
||||
{
|
||||
path = toLocal( path );
|
||||
try
|
||||
{
|
||||
if( m_mount.exists( path ) )
|
||||
{
|
||||
if( m_mount.isDirectory( path ) )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
return m_mount.getSize( path );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new FileSystemException( "No such file" );
|
||||
}
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public InputStream openForRead( String path ) throws FileSystemException
|
||||
{
|
||||
path = toLocal( path );
|
||||
try
|
||||
{
|
||||
if( m_mount.exists( path ) && !m_mount.isDirectory( path ) )
|
||||
{
|
||||
return m_mount.openForRead( path );
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new FileSystemException( "No such file" );
|
||||
}
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
// IWritableMount forwarders:
|
||||
|
||||
public void makeDirectory( String path ) throws FileSystemException
|
||||
{
|
||||
if( m_writableMount == null )
|
||||
{
|
||||
throw new FileSystemException( "Access Denied" );
|
||||
}
|
||||
try
|
||||
{
|
||||
path = toLocal( path );
|
||||
if( m_mount.exists( path ) )
|
||||
{
|
||||
if( !m_mount.isDirectory( path ) )
|
||||
{
|
||||
throw new FileSystemException( "File exists" );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_writableMount.makeDirectory( path );
|
||||
}
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public void delete( String path ) throws FileSystemException
|
||||
{
|
||||
if( m_writableMount == null )
|
||||
{
|
||||
throw new FileSystemException( "Access Denied" );
|
||||
}
|
||||
try
|
||||
{
|
||||
path = toLocal( path );
|
||||
if( m_mount.exists( path ) )
|
||||
{
|
||||
m_writableMount.delete( path );
|
||||
}
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public OutputStream openForWrite( String path ) throws FileSystemException
|
||||
{
|
||||
if( m_writableMount == null )
|
||||
{
|
||||
throw new FileSystemException( "Access Denied" );
|
||||
}
|
||||
try
|
||||
{
|
||||
path = toLocal( path );
|
||||
if( m_mount.exists( path ) && m_mount.isDirectory( path ) )
|
||||
{
|
||||
throw new FileSystemException( "Cannot write to directory" );
|
||||
}
|
||||
else
|
||||
{
|
||||
if( !path.isEmpty() )
|
||||
{
|
||||
String dir = getDirectory( path );
|
||||
if( !dir.isEmpty() && !m_mount.exists( path ) )
|
||||
{
|
||||
m_writableMount.makeDirectory( dir );
|
||||
}
|
||||
}
|
||||
return m_writableMount.openForWrite( path );
|
||||
}
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public OutputStream openForAppend( String path ) throws FileSystemException
|
||||
{
|
||||
if( m_writableMount == null )
|
||||
{
|
||||
throw new FileSystemException( "Access Denied" );
|
||||
}
|
||||
try
|
||||
{
|
||||
path = toLocal( path );
|
||||
if( !m_mount.exists( path ) )
|
||||
{
|
||||
if( !path.isEmpty() )
|
||||
{
|
||||
String dir = getDirectory( path );
|
||||
if( !dir.isEmpty() && !m_mount.exists( path ) )
|
||||
{
|
||||
m_writableMount.makeDirectory( dir );
|
||||
}
|
||||
}
|
||||
return m_writableMount.openForWrite( path );
|
||||
}
|
||||
else if( m_mount.isDirectory( path ) )
|
||||
{
|
||||
throw new FileSystemException( "Cannot write to directory" );
|
||||
}
|
||||
else
|
||||
{
|
||||
return m_writableMount.openForAppend( path );
|
||||
}
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
// private members
|
||||
|
||||
private String toLocal( String path )
|
||||
{
|
||||
return FileSystem.toLocal( path, m_location );
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, MountWrapper> m_mounts = new HashMap<String, MountWrapper>();
|
||||
private Set<IMountedFile> m_openFiles = new HashSet<IMountedFile>();
|
||||
|
||||
public FileSystem( String rootLabel, IMount rootMount ) throws FileSystemException
|
||||
{
|
||||
mount( rootLabel, "", rootMount );
|
||||
}
|
||||
|
||||
public FileSystem( String rootLabel, IWritableMount rootMount ) throws FileSystemException
|
||||
{
|
||||
mountWritable( rootLabel, "", rootMount );
|
||||
}
|
||||
|
||||
public void unload()
|
||||
{
|
||||
// Close all dangling open files
|
||||
synchronized( m_openFiles )
|
||||
{
|
||||
while( m_openFiles.size() > 0 )
|
||||
{
|
||||
IMountedFile file = m_openFiles.iterator().next();
|
||||
try
|
||||
{
|
||||
file.close();
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
m_openFiles.remove( file );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void mount( String label, String location, IMount mount ) throws FileSystemException
|
||||
{
|
||||
if( mount == null )
|
||||
{
|
||||
throw new NullPointerException();
|
||||
}
|
||||
location = sanitizePath( location );
|
||||
if( location.indexOf( ".." ) != -1 ) {
|
||||
throw new FileSystemException( "Cannot mount below the root" );
|
||||
}
|
||||
mount( new MountWrapper( label, location, mount ) );
|
||||
}
|
||||
|
||||
public synchronized void mountWritable( String label, String location, IWritableMount mount ) throws FileSystemException
|
||||
{
|
||||
if( mount == null )
|
||||
{
|
||||
throw new NullPointerException();
|
||||
}
|
||||
location = sanitizePath( location );
|
||||
if( location.contains( ".." ) )
|
||||
{
|
||||
throw new FileSystemException( "Cannot mount below the root" );
|
||||
}
|
||||
mount( new MountWrapper( label, location, mount ) );
|
||||
}
|
||||
|
||||
private synchronized void mount( MountWrapper wrapper ) throws FileSystemException
|
||||
{
|
||||
String location = wrapper.getLocation();
|
||||
if( m_mounts.containsKey( location ) )
|
||||
{
|
||||
m_mounts.remove( location );
|
||||
}
|
||||
m_mounts.put( location, wrapper );
|
||||
}
|
||||
|
||||
public synchronized void unmount( String path )
|
||||
{
|
||||
path = sanitizePath( path );
|
||||
if( m_mounts.containsKey( path ) )
|
||||
{
|
||||
m_mounts.remove( path );
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized String combine( String path, String childPath )
|
||||
{
|
||||
path = sanitizePath( path, true );
|
||||
childPath = sanitizePath( childPath, true );
|
||||
|
||||
if( path.isEmpty() ) {
|
||||
return childPath;
|
||||
} else if( childPath.isEmpty() ) {
|
||||
return path;
|
||||
} else {
|
||||
return sanitizePath( path + '/' + childPath, true );
|
||||
}
|
||||
}
|
||||
|
||||
public static String getDirectory( String path )
|
||||
{
|
||||
path = sanitizePath( path, true );
|
||||
if( path.isEmpty() ) {
|
||||
return "..";
|
||||
}
|
||||
|
||||
int lastSlash = path.lastIndexOf('/');
|
||||
if( lastSlash >= 0 ) {
|
||||
return path.substring( 0, lastSlash );
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static String getName( String path )
|
||||
{
|
||||
path = sanitizePath( path, true );
|
||||
if( path.isEmpty() ) {
|
||||
return "root";
|
||||
}
|
||||
|
||||
int lastSlash = path.lastIndexOf('/');
|
||||
if( lastSlash >= 0 ) {
|
||||
return path.substring( lastSlash + 1 );
|
||||
} else {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized long getSize( String path ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
return mount.getSize( path );
|
||||
}
|
||||
|
||||
public synchronized String[] list( String path ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
|
||||
// Gets a list of the files in the mount
|
||||
List<String> list = new ArrayList<String>();
|
||||
mount.list( path, list );
|
||||
|
||||
// Add any mounts that are mounted at this location
|
||||
Iterator<MountWrapper> it = m_mounts.values().iterator();
|
||||
while( it.hasNext() ) {
|
||||
MountWrapper otherMount = it.next();
|
||||
if( getDirectory( otherMount.getLocation() ).equals( path ) ) {
|
||||
list.add( getName( otherMount.getLocation() ) );
|
||||
}
|
||||
}
|
||||
|
||||
// Return list
|
||||
String[] array = new String[ list.size() ];
|
||||
list.toArray(array);
|
||||
return array;
|
||||
}
|
||||
|
||||
private void findIn( String dir, List<String> matches, Pattern wildPattern ) throws FileSystemException
|
||||
{
|
||||
String[] list = list( dir );
|
||||
for( int i=0; i<list.length; ++i )
|
||||
{
|
||||
String entry = list[i];
|
||||
String entryPath = dir.isEmpty() ? entry : (dir + "/" + entry);
|
||||
if( wildPattern.matcher( entryPath ).matches() )
|
||||
{
|
||||
matches.add( entryPath );
|
||||
}
|
||||
if( isDir( entryPath ) )
|
||||
{
|
||||
findIn( entryPath, matches, wildPattern );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized String[] find( String wildPath ) throws FileSystemException
|
||||
{
|
||||
// Match all the files on the system
|
||||
wildPath = sanitizePath( wildPath, true );
|
||||
Pattern wildPattern = Pattern.compile( "^\\Q" + wildPath.replaceAll( "\\*", "\\\\E[^\\\\/]*\\\\Q" ) + "\\E$" );
|
||||
List<String> matches = new ArrayList<String>();
|
||||
findIn( "", matches, wildPattern );
|
||||
|
||||
// Return matches
|
||||
String[] array = new String[ matches.size() ];
|
||||
matches.toArray(array);
|
||||
return array;
|
||||
}
|
||||
|
||||
public synchronized boolean exists( String path ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
return mount.exists( path );
|
||||
}
|
||||
|
||||
public synchronized boolean isDir( String path ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
return mount.isDirectory( path );
|
||||
}
|
||||
|
||||
public synchronized boolean isReadOnly( String path ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
return mount.isReadOnly( path );
|
||||
}
|
||||
|
||||
public synchronized String getMountLabel( String path ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
return mount.getLabel();
|
||||
}
|
||||
|
||||
public synchronized void makeDir( String path ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
mount.makeDirectory( path );
|
||||
}
|
||||
|
||||
public synchronized void delete( String path ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
mount.delete( path );
|
||||
}
|
||||
|
||||
public synchronized void move( String sourcePath, String destPath ) throws FileSystemException
|
||||
{
|
||||
sourcePath = sanitizePath( sourcePath );
|
||||
destPath = sanitizePath( destPath );
|
||||
if( isReadOnly( sourcePath ) || isReadOnly( destPath ) ) {
|
||||
throw new FileSystemException( "Access denied" );
|
||||
}
|
||||
if( !exists( sourcePath ) ) {
|
||||
throw new FileSystemException( "No such file" );
|
||||
}
|
||||
if( exists( destPath ) ) {
|
||||
throw new FileSystemException( "File exists" );
|
||||
}
|
||||
if( contains( sourcePath, destPath ) ) {
|
||||
throw new FileSystemException( "Can't move a directory inside itself" );
|
||||
}
|
||||
copy( sourcePath, destPath );
|
||||
delete( sourcePath );
|
||||
}
|
||||
|
||||
public synchronized void copy( String sourcePath, String destPath ) throws FileSystemException
|
||||
{
|
||||
sourcePath = sanitizePath( sourcePath );
|
||||
destPath = sanitizePath( destPath );
|
||||
if( isReadOnly( destPath ) ) {
|
||||
throw new FileSystemException( "Access denied" );
|
||||
}
|
||||
if( !exists( sourcePath ) ) {
|
||||
throw new FileSystemException( "No such file" );
|
||||
}
|
||||
if( exists( destPath ) ) {
|
||||
throw new FileSystemException( "File exists" );
|
||||
}
|
||||
if( contains( sourcePath, destPath ) ) {
|
||||
throw new FileSystemException( "Can't copy a directory inside itself" );
|
||||
}
|
||||
copyRecursive( sourcePath, getMount( sourcePath ), destPath, getMount( destPath ) );
|
||||
}
|
||||
|
||||
private synchronized void copyRecursive( String sourcePath, MountWrapper sourceMount, String destinationPath, MountWrapper destinationMount ) throws FileSystemException
|
||||
{
|
||||
if( !sourceMount.exists( sourcePath ) )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if( sourceMount.isDirectory( sourcePath ) )
|
||||
{
|
||||
// Copy a directory:
|
||||
// Make the new directory
|
||||
destinationMount.makeDirectory( destinationPath );
|
||||
|
||||
// Copy the source contents into it
|
||||
List<String> sourceChildren = new ArrayList<String>();
|
||||
sourceMount.list( sourcePath, sourceChildren );
|
||||
for( String child : sourceChildren )
|
||||
{
|
||||
copyRecursive(
|
||||
combine( sourcePath, child ), sourceMount,
|
||||
combine( destinationPath, child ), destinationMount
|
||||
);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Copy a file:
|
||||
InputStream source = null;
|
||||
OutputStream destination = null;
|
||||
try
|
||||
{
|
||||
// Open both files
|
||||
source = sourceMount.openForRead( sourcePath );
|
||||
destination = destinationMount.openForWrite( destinationPath );
|
||||
|
||||
// Copy bytes as fast as we can
|
||||
byte[] buffer = new byte[1024];
|
||||
while( true )
|
||||
{
|
||||
int bytesRead = source.read( buffer );
|
||||
if( bytesRead >= 0 )
|
||||
{
|
||||
destination.write( buffer, 0, bytesRead );
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Close both files
|
||||
if( source != null )
|
||||
{
|
||||
try {
|
||||
source.close();
|
||||
} catch( IOException e ) {
|
||||
// nobody cares
|
||||
}
|
||||
}
|
||||
if( destination != null )
|
||||
{
|
||||
try {
|
||||
destination.close();
|
||||
} catch( IOException e ) {
|
||||
// nobody cares
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized IMountedFileNormal openForRead( String path ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath ( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
InputStream stream = mount.openForRead( path );
|
||||
if( stream != null )
|
||||
{
|
||||
InputStreamReader isr;
|
||||
try
|
||||
{
|
||||
isr = new InputStreamReader( stream, "UTF-8" );
|
||||
}
|
||||
catch( UnsupportedEncodingException e )
|
||||
{
|
||||
isr = new InputStreamReader( stream );
|
||||
}
|
||||
final BufferedReader reader = new BufferedReader( isr );
|
||||
IMountedFileNormal file = new IMountedFileNormal()
|
||||
{
|
||||
@Override
|
||||
public String readLine() throws IOException
|
||||
{
|
||||
return reader.readLine();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(String s, int off, int len, boolean newLine) throws IOException
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
synchronized( m_openFiles )
|
||||
{
|
||||
m_openFiles.remove( this );
|
||||
reader.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() throws IOException
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
};
|
||||
synchronized( m_openFiles )
|
||||
{
|
||||
m_openFiles.add( file );
|
||||
}
|
||||
return file;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public synchronized IMountedFileNormal openForWrite( String path, boolean append ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath ( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
OutputStream stream = append ? mount.openForAppend( path ) : mount.openForWrite( path );
|
||||
if( stream != null )
|
||||
{
|
||||
OutputStreamWriter osw;
|
||||
try
|
||||
{
|
||||
osw = new OutputStreamWriter( stream, "UTF-8" );
|
||||
}
|
||||
catch( UnsupportedEncodingException e )
|
||||
{
|
||||
osw = new OutputStreamWriter( stream );
|
||||
}
|
||||
final BufferedWriter writer = new BufferedWriter( osw );
|
||||
IMountedFileNormal file = new IMountedFileNormal()
|
||||
{
|
||||
@Override
|
||||
public String readLine() throws IOException
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write( String s, int off, int len, boolean newLine ) throws IOException
|
||||
{
|
||||
writer.write( s, off, len );
|
||||
if( newLine )
|
||||
{
|
||||
writer.newLine();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
synchronized( m_openFiles )
|
||||
{
|
||||
m_openFiles.remove( this );
|
||||
writer.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() throws IOException
|
||||
{
|
||||
writer.flush();
|
||||
}
|
||||
};
|
||||
synchronized( m_openFiles )
|
||||
{
|
||||
m_openFiles.add( file );
|
||||
}
|
||||
return file;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public synchronized IMountedFileBinary openForBinaryRead( String path ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath ( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
final InputStream stream = mount.openForRead( path );
|
||||
if( stream != null )
|
||||
{
|
||||
IMountedFileBinary file = new IMountedFileBinary()
|
||||
{
|
||||
@Override
|
||||
public int read() throws IOException
|
||||
{
|
||||
return stream.read();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(int i) throws IOException
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
synchronized( m_openFiles )
|
||||
{
|
||||
m_openFiles.remove( this );
|
||||
stream.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() throws IOException
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
};
|
||||
synchronized( m_openFiles )
|
||||
{
|
||||
m_openFiles.add( file );
|
||||
}
|
||||
return file;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public synchronized IMountedFileBinary openForBinaryWrite( String path, boolean append ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath ( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
final OutputStream stream = append ? mount.openForAppend( path ) : mount.openForWrite( path );
|
||||
if( stream != null )
|
||||
{
|
||||
IMountedFileBinary file = new IMountedFileBinary()
|
||||
{
|
||||
@Override
|
||||
public int read() throws IOException
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(int i) throws IOException
|
||||
{
|
||||
stream.write(i);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
synchronized( m_openFiles )
|
||||
{
|
||||
m_openFiles.remove( this );
|
||||
stream.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() throws IOException
|
||||
{
|
||||
stream.flush();
|
||||
}
|
||||
};
|
||||
synchronized( m_openFiles )
|
||||
{
|
||||
m_openFiles.add( file );
|
||||
}
|
||||
return file;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public long getFreeSpace( String path ) throws FileSystemException
|
||||
{
|
||||
path = sanitizePath( path );
|
||||
MountWrapper mount = getMount( path );
|
||||
return mount.getFreeSpace();
|
||||
}
|
||||
|
||||
private MountWrapper getMount( String path ) throws FileSystemException
|
||||
{
|
||||
// Return the deepest mount that contains a given path
|
||||
Iterator<MountWrapper> it = m_mounts.values().iterator();
|
||||
MountWrapper match = null;
|
||||
int matchLength = 999;
|
||||
while( it.hasNext() )
|
||||
{
|
||||
MountWrapper mount = it.next();
|
||||
if( contains( mount.getLocation(), path ) ) {
|
||||
int len = toLocal( path, mount.getLocation() ).length();
|
||||
if( match == null || len < matchLength ) {
|
||||
match = mount;
|
||||
matchLength = len;
|
||||
}
|
||||
}
|
||||
}
|
||||
if( match == null )
|
||||
{
|
||||
throw new FileSystemException( "Invalid Path" );
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
private static String sanitizePath( String path )
|
||||
{
|
||||
return sanitizePath( path, false );
|
||||
}
|
||||
|
||||
private static String sanitizePath( String path, boolean allowWildcards )
|
||||
{
|
||||
// Allow windowsy slashes
|
||||
path = path.replace( '\\', '/' );
|
||||
|
||||
// Clean the path or illegal characters.
|
||||
final char[] specialChars = {
|
||||
'"', ':', '<', '>', '?', '|' // Sorted by ascii value (important)
|
||||
};
|
||||
|
||||
StringBuilder cleanName = new StringBuilder();
|
||||
for( int i = 0; i < path.length(); i++ ) {
|
||||
char c = path.charAt(i);
|
||||
if( c >= 32 && Arrays.binarySearch( specialChars, c ) < 0 && (allowWildcards || c != '*') )
|
||||
{
|
||||
cleanName.append((char)c);
|
||||
}
|
||||
}
|
||||
path = cleanName.toString();
|
||||
|
||||
// Collapse the string into its component parts, removing ..'s
|
||||
String[] parts = path.split("/");
|
||||
Stack<String> outputParts = new Stack<String>();
|
||||
for( int n=0; n<parts.length; ++n ) {
|
||||
String part = parts[n];
|
||||
if( part.length() == 0 || part.equals(".") )
|
||||
{
|
||||
// . is redundant
|
||||
continue;
|
||||
} else if( part.equals("..") || part.equals( "..." ) ) {
|
||||
// .. or ... can cancel out the last folder entered
|
||||
if( !outputParts.empty() ) {
|
||||
String top = outputParts.peek();
|
||||
if( !top.equals("..") ) {
|
||||
outputParts.pop();
|
||||
} else {
|
||||
outputParts.push("..");
|
||||
}
|
||||
} else {
|
||||
outputParts.push("..");
|
||||
}
|
||||
} else if (part.length() >= 255) {
|
||||
// If part length > 255 and it is the last part
|
||||
outputParts.push( part.substring(0, 255) );
|
||||
} else {
|
||||
// Anything else we add to the stack
|
||||
outputParts.push(part);
|
||||
}
|
||||
}
|
||||
|
||||
// Recombine the output parts into a new string
|
||||
StringBuilder result = new StringBuilder( "" );
|
||||
Iterator<String> it = outputParts.iterator();
|
||||
while( it.hasNext() ) {
|
||||
String part = it.next();
|
||||
result.append( part );
|
||||
if( it.hasNext() ) {
|
||||
result.append( '/' );
|
||||
}
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static boolean contains( String pathA, String pathB )
|
||||
{
|
||||
pathA = sanitizePath( pathA );
|
||||
pathB = sanitizePath( pathB );
|
||||
|
||||
if( pathB.equals("..") )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else if ( pathB.startsWith("../") )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else if( pathB.equals( pathA ) )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else if( pathA.isEmpty() )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return pathB.startsWith( pathA + "/" );
|
||||
}
|
||||
}
|
||||
|
||||
public static String toLocal( String path, String location )
|
||||
{
|
||||
path = sanitizePath( path );
|
||||
location = sanitizePath( location );
|
||||
|
||||
assert( contains( location, path ) );
|
||||
String local = path.substring( location.length() );
|
||||
if( local.startsWith("/") ) {
|
||||
return local.substring( 1 );
|
||||
} else {
|
||||
return local;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
public class FileSystemException extends Exception {
|
||||
FileSystemException( String s ) {
|
||||
super( s );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public interface IMountedFile {
|
||||
public void close() throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public interface IMountedFileBinary extends IMountedFile {
|
||||
public int read() throws IOException;
|
||||
public void write(int i) throws IOException;
|
||||
public void close() throws IOException;
|
||||
public void flush() throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public interface IMountedFileNormal extends IMountedFile {
|
||||
public String readLine() throws IOException;
|
||||
public void write(String s, int off, int len, boolean newLine) throws IOException;
|
||||
public void close() throws IOException;
|
||||
public void flush() throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Enumeration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
public class JarMount implements IMount
|
||||
{
|
||||
private class FileInZip
|
||||
{
|
||||
private String m_path;
|
||||
private boolean m_directory;
|
||||
private long m_size;
|
||||
private Map<String, FileInZip> m_children;
|
||||
|
||||
public FileInZip( String path, boolean directory, long size )
|
||||
{
|
||||
m_path = path;
|
||||
m_directory = directory;
|
||||
m_size = m_directory ? 0 : size;
|
||||
m_children = new LinkedHashMap<String, FileInZip>();
|
||||
}
|
||||
|
||||
public String getPath()
|
||||
{
|
||||
return m_path;
|
||||
}
|
||||
|
||||
public boolean isDirectory()
|
||||
{
|
||||
return m_directory;
|
||||
}
|
||||
|
||||
public long getSize()
|
||||
{
|
||||
return m_size;
|
||||
}
|
||||
|
||||
public void list( List<String> contents )
|
||||
{
|
||||
for( String child : m_children.keySet() )
|
||||
{
|
||||
contents.add( child );
|
||||
}
|
||||
}
|
||||
|
||||
public void insertChild( FileInZip child )
|
||||
{
|
||||
String localPath = FileSystem.toLocal( child.getPath(), m_path );
|
||||
m_children.put( localPath, child );
|
||||
}
|
||||
|
||||
public FileInZip getFile( String path )
|
||||
{
|
||||
// If we've reached the target, return this
|
||||
if( path.equals( m_path ) )
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
// Otherwise, get the next component of the path
|
||||
String localPath = FileSystem.toLocal( path, m_path );
|
||||
int slash = localPath.indexOf("/");
|
||||
if( slash >= 0 )
|
||||
{
|
||||
localPath = localPath.substring( 0, slash );
|
||||
}
|
||||
|
||||
// And recurse down using it
|
||||
FileInZip subFile = m_children.get( localPath );
|
||||
if( subFile != null )
|
||||
{
|
||||
return subFile.getFile( path );
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public FileInZip getParent( String path )
|
||||
{
|
||||
if( path.length() == 0 )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
FileInZip file = getFile( FileSystem.getDirectory( path ) );
|
||||
if( file.isDirectory() )
|
||||
{
|
||||
return file;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private ZipFile m_zipFile;
|
||||
private FileInZip m_root;
|
||||
private String m_rootPath;
|
||||
|
||||
public JarMount( File jarFile, String subPath ) throws IOException
|
||||
{
|
||||
if( !jarFile.exists() || jarFile.isDirectory() )
|
||||
{
|
||||
throw new FileNotFoundException();
|
||||
}
|
||||
|
||||
// Open the zip file
|
||||
try
|
||||
{
|
||||
m_zipFile = new ZipFile( jarFile );
|
||||
}
|
||||
catch( Exception e )
|
||||
{
|
||||
throw new IOException( "Error loading zip file" );
|
||||
}
|
||||
|
||||
if( m_zipFile.getEntry( subPath ) == null )
|
||||
{
|
||||
m_zipFile.close();
|
||||
throw new IOException( "Zip does not contain path" );
|
||||
}
|
||||
|
||||
// Read in all the entries
|
||||
Enumeration<? extends ZipEntry> zipEntries = m_zipFile.entries();
|
||||
while( zipEntries.hasMoreElements() )
|
||||
{
|
||||
ZipEntry entry = zipEntries.nextElement();
|
||||
String entryName = entry.getName();
|
||||
if( entryName.startsWith( subPath ) )
|
||||
{
|
||||
entryName = FileSystem.toLocal( entryName, subPath );
|
||||
if( m_root == null )
|
||||
{
|
||||
if( entryName.equals( "" ) )
|
||||
{
|
||||
m_root = new FileInZip( entryName, entry.isDirectory(), entry.getSize() );
|
||||
m_rootPath = subPath;
|
||||
if( !m_root.isDirectory() )
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO: handle this case. The code currently assumes we find the root before anything else
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
FileInZip parent = m_root.getParent( entryName );
|
||||
if( parent != null )
|
||||
{
|
||||
parent.insertChild( new FileInZip( entryName, entry.isDirectory(), entry.getSize() ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO: handle this case. The code currently assumes we find folders before their contents
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// IMount implementation
|
||||
|
||||
@Override
|
||||
public boolean exists( String path ) throws IOException
|
||||
{
|
||||
FileInZip file = m_root.getFile( path );
|
||||
return file != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDirectory( String path ) throws IOException
|
||||
{
|
||||
FileInZip file = m_root.getFile( path );
|
||||
if( file != null )
|
||||
{
|
||||
return file.isDirectory();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void list( String path, List<String> contents ) throws IOException
|
||||
{
|
||||
FileInZip file = m_root.getFile( path );
|
||||
if( file != null && file.isDirectory() )
|
||||
{
|
||||
file.list( contents );
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new IOException( "Not a directory" );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize( String path ) throws IOException
|
||||
{
|
||||
FileInZip file = m_root.getFile( path );
|
||||
if( file != null )
|
||||
{
|
||||
return file.getSize();
|
||||
}
|
||||
throw new IOException( "No such file" );
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream openForRead( String path ) throws IOException
|
||||
{
|
||||
FileInZip file = m_root.getFile( path );
|
||||
if( file != null && !file.isDirectory() )
|
||||
{
|
||||
try
|
||||
{
|
||||
String fullPath = m_rootPath;
|
||||
if( path.length() > 0 )
|
||||
{
|
||||
fullPath = fullPath + "/" + path;
|
||||
}
|
||||
ZipEntry entry = m_zipFile.getEntry( fullPath );
|
||||
if( entry != null )
|
||||
{
|
||||
return m_zipFile.getInputStream( entry );
|
||||
}
|
||||
}
|
||||
catch( Exception e )
|
||||
{
|
||||
// treat errors as non-existance of file
|
||||
}
|
||||
}
|
||||
throw new IOException( "No such file" );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
public class SubMount implements IMount
|
||||
{
|
||||
private IMount m_parent;
|
||||
private String m_subPath;
|
||||
|
||||
public SubMount( IMount parent, String subPath )
|
||||
{
|
||||
m_parent = parent;
|
||||
m_subPath = subPath;
|
||||
}
|
||||
|
||||
// IMount implementation
|
||||
|
||||
@Override
|
||||
public boolean exists( String path ) throws IOException
|
||||
{
|
||||
return m_parent.exists( getFullPath( path ) );
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDirectory( String path ) throws IOException
|
||||
{
|
||||
return m_parent.isDirectory( getFullPath( path ) );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void list( String path, List<String> contents ) throws IOException
|
||||
{
|
||||
m_parent.list( getFullPath( path ), contents );
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize( String path ) throws IOException
|
||||
{
|
||||
return m_parent.getSize( getFullPath( path ) );
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream openForRead( String path ) throws IOException
|
||||
{
|
||||
return m_parent.openForRead( getFullPath( path ) );
|
||||
}
|
||||
|
||||
private String getFullPath( String path )
|
||||
{
|
||||
if( path.length() == 0 )
|
||||
{
|
||||
return m_subPath;
|
||||
}
|
||||
else
|
||||
{
|
||||
return m_subPath + "/" + path;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.lua;
|
||||
import dan200.computercraft.core.apis.ILuaAPI;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
public interface ILuaMachine
|
||||
{
|
||||
public void addAPI( ILuaAPI api );
|
||||
|
||||
public void loadBios( InputStream bios );
|
||||
public void handleEvent( String eventName, Object[] arguments );
|
||||
public void softAbort( String abortMessage );
|
||||
public void hardAbort( String abortMessage );
|
||||
|
||||
public boolean saveState( OutputStream output );
|
||||
public boolean restoreState( InputStream input );
|
||||
|
||||
public boolean isFinished();
|
||||
|
||||
public void unload();
|
||||
}
|
||||
@@ -0,0 +1,682 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.lua;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.ILuaObject;
|
||||
import dan200.computercraft.api.lua.ILuaTask;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.core.apis.ILuaAPI;
|
||||
import dan200.computercraft.core.computer.Computer;
|
||||
import dan200.computercraft.core.computer.ITask;
|
||||
import dan200.computercraft.core.computer.MainThread;
|
||||
import org.luaj.vm2.*;
|
||||
import org.luaj.vm2.lib.OneArgFunction;
|
||||
import org.luaj.vm2.lib.VarArgFunction;
|
||||
import org.luaj.vm2.lib.ZeroArgFunction;
|
||||
import org.luaj.vm2.lib.jse.JsePlatform;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
public class LuaJLuaMachine implements ILuaMachine
|
||||
{
|
||||
private Computer m_computer;
|
||||
|
||||
private LuaValue m_globals;
|
||||
private LuaValue m_loadString;
|
||||
private LuaValue m_assert;
|
||||
private LuaValue m_coroutine_create;
|
||||
private LuaValue m_coroutine_resume;
|
||||
private LuaValue m_coroutine_yield;
|
||||
|
||||
private LuaValue m_mainRoutine;
|
||||
private String m_eventFilter;
|
||||
private String m_softAbortMessage;
|
||||
private String m_hardAbortMessage;
|
||||
|
||||
private Map<Object, LuaValue> m_valuesInProgress;
|
||||
private Map<LuaValue, Object> m_objectsInProgress;
|
||||
|
||||
public LuaJLuaMachine( Computer computer )
|
||||
{
|
||||
m_computer = computer;
|
||||
|
||||
// Create an environment to run in
|
||||
m_globals = JsePlatform.debugGlobals();
|
||||
m_loadString = m_globals.get("loadstring");
|
||||
m_assert = m_globals.get("assert");
|
||||
|
||||
LuaValue coroutine = m_globals.get("coroutine");
|
||||
final LuaValue native_coroutine_create = coroutine.get("create");
|
||||
|
||||
LuaValue debug = m_globals.get("debug");
|
||||
final LuaValue debug_sethook = debug.get("sethook");
|
||||
|
||||
coroutine.set("create", new OneArgFunction() {
|
||||
@Override
|
||||
public LuaValue call( LuaValue value )
|
||||
{
|
||||
final LuaThread thread = native_coroutine_create.call( value ).checkthread();
|
||||
debug_sethook.invoke( new LuaValue[] {
|
||||
thread,
|
||||
new ZeroArgFunction() {
|
||||
@Override
|
||||
public LuaValue call() {
|
||||
String hardAbortMessage = m_hardAbortMessage;
|
||||
if( hardAbortMessage != null )
|
||||
{
|
||||
LuaThread.yield(LuaValue.NIL);
|
||||
}
|
||||
return LuaValue.NIL;
|
||||
}
|
||||
},
|
||||
LuaValue.NIL,
|
||||
LuaValue.valueOf(100000)
|
||||
} );
|
||||
return thread;
|
||||
}
|
||||
});
|
||||
|
||||
m_coroutine_create = coroutine.get("create");
|
||||
m_coroutine_resume = coroutine.get("resume");
|
||||
m_coroutine_yield = coroutine.get("yield");
|
||||
|
||||
// Remove globals we don't want to expose
|
||||
m_globals.set( "collectgarbage", LuaValue.NIL );
|
||||
m_globals.set( "dofile", LuaValue.NIL );
|
||||
m_globals.set( "loadfile", LuaValue.NIL );
|
||||
m_globals.set( "module", LuaValue.NIL );
|
||||
m_globals.set( "require", LuaValue.NIL );
|
||||
m_globals.set( "package", LuaValue.NIL );
|
||||
m_globals.set( "io", LuaValue.NIL );
|
||||
m_globals.set( "os", LuaValue.NIL );
|
||||
m_globals.set( "print", LuaValue.NIL );
|
||||
m_globals.set( "luajava", LuaValue.NIL );
|
||||
m_globals.set( "debug", LuaValue.NIL );
|
||||
m_globals.set( "newproxy", LuaValue.NIL );
|
||||
m_globals.set( "__inext", LuaValue.NIL );
|
||||
|
||||
// Add version globals
|
||||
m_globals.set( "_VERSION", "Lua 5.1" );
|
||||
m_globals.set( "_HOST", computer.getAPIEnvironment().getComputerEnvironment().getHostString() );
|
||||
m_globals.set( "_CC_DEFAULT_SETTINGS", toValue( ComputerCraft.default_computer_settings ) );
|
||||
if( ComputerCraft.disable_lua51_features )
|
||||
{
|
||||
m_globals.set( "_CC_DISABLE_LUA51_FEATURES", toValue( true ) );
|
||||
}
|
||||
|
||||
// Our main function will go here
|
||||
m_mainRoutine = null;
|
||||
m_eventFilter = null;
|
||||
|
||||
m_softAbortMessage = null;
|
||||
m_hardAbortMessage = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addAPI( ILuaAPI api )
|
||||
{
|
||||
// Add the methods of an API to the global table
|
||||
LuaTable table = wrapLuaObject( api );
|
||||
String[] names = api.getNames();
|
||||
for( int i=0; i<names.length; ++i )
|
||||
{
|
||||
m_globals.set( names[i], table );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadBios( InputStream bios )
|
||||
{
|
||||
// Begin executing a file (ie, the bios)
|
||||
if( m_mainRoutine != null )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Read the whole bios into a string
|
||||
String biosText = null;
|
||||
try
|
||||
{
|
||||
InputStreamReader isr;
|
||||
try
|
||||
{
|
||||
isr = new InputStreamReader( bios, "UTF-8" );
|
||||
}
|
||||
catch( UnsupportedEncodingException e )
|
||||
{
|
||||
isr = new InputStreamReader( bios );
|
||||
}
|
||||
BufferedReader reader = new BufferedReader( isr );
|
||||
StringBuilder fileText = new StringBuilder( "" );
|
||||
String line = reader.readLine();
|
||||
while( line != null ) {
|
||||
fileText.append( line );
|
||||
line = reader.readLine();
|
||||
if( line != null ) {
|
||||
fileText.append( "\n" );
|
||||
}
|
||||
}
|
||||
biosText = fileText.toString();
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new LuaError( "Could not read file" );
|
||||
}
|
||||
|
||||
// Load it
|
||||
LuaValue program = m_assert.call( m_loadString.call(
|
||||
toValue( biosText ), toValue( "bios.lua" )
|
||||
));
|
||||
m_mainRoutine = m_coroutine_create.call( program );
|
||||
}
|
||||
catch( LuaError e )
|
||||
{
|
||||
if( m_mainRoutine != null )
|
||||
{
|
||||
((LuaThread)m_mainRoutine).abandon();
|
||||
m_mainRoutine = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleEvent( String eventName, Object[] arguments )
|
||||
{
|
||||
if( m_mainRoutine == null )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if( m_eventFilter != null && eventName != null && !eventName.equals( m_eventFilter ) && !eventName.equals( "terminate" ) )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
LuaValue[] resumeArgs;
|
||||
if( eventName != null )
|
||||
{
|
||||
resumeArgs = toValues( arguments, 2 );
|
||||
resumeArgs[0] = m_mainRoutine;
|
||||
resumeArgs[1] = toValue( eventName );
|
||||
}
|
||||
else
|
||||
{
|
||||
resumeArgs = new LuaValue[1];
|
||||
resumeArgs[0] = m_mainRoutine;
|
||||
}
|
||||
|
||||
Varargs results = m_coroutine_resume.invoke( LuaValue.varargsOf( resumeArgs ) );
|
||||
if( m_hardAbortMessage != null )
|
||||
{
|
||||
throw new LuaError( m_hardAbortMessage );
|
||||
}
|
||||
else if( results.arg1().checkboolean() == false )
|
||||
{
|
||||
throw new LuaError( results.arg(2).checkstring().toString() );
|
||||
}
|
||||
else
|
||||
{
|
||||
LuaValue filter = results.arg(2);
|
||||
if( filter.isstring() )
|
||||
{
|
||||
m_eventFilter = filter.toString();
|
||||
}
|
||||
else
|
||||
{
|
||||
m_eventFilter = null;
|
||||
}
|
||||
}
|
||||
|
||||
LuaThread mainThread = (LuaThread)m_mainRoutine;
|
||||
if( mainThread.getStatus().equals("dead") )
|
||||
{
|
||||
m_mainRoutine = null;
|
||||
}
|
||||
}
|
||||
catch( LuaError e )
|
||||
{
|
||||
((LuaThread)m_mainRoutine).abandon();
|
||||
m_mainRoutine = null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
m_softAbortMessage = null;
|
||||
m_hardAbortMessage = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void softAbort( String abortMessage )
|
||||
{
|
||||
m_softAbortMessage = abortMessage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void hardAbort( String abortMessage )
|
||||
{
|
||||
m_softAbortMessage = abortMessage;
|
||||
m_hardAbortMessage = abortMessage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean saveState( OutputStream output )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean restoreState( InputStream input )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isFinished()
|
||||
{
|
||||
return (m_mainRoutine == null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unload()
|
||||
{
|
||||
if( m_mainRoutine != null )
|
||||
{
|
||||
LuaThread mainThread = (LuaThread)m_mainRoutine;
|
||||
mainThread.abandon();
|
||||
m_mainRoutine = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void tryAbort() throws LuaError
|
||||
{
|
||||
// while( m_stopped )
|
||||
// {
|
||||
// m_coroutine_yield.call();
|
||||
// }
|
||||
|
||||
String abortMessage = m_softAbortMessage;
|
||||
if( abortMessage != null )
|
||||
{
|
||||
m_softAbortMessage = null;
|
||||
m_hardAbortMessage = null;
|
||||
throw new LuaError( abortMessage );
|
||||
}
|
||||
}
|
||||
|
||||
private static long s_nextUnusedTaskID = 0;
|
||||
|
||||
private LuaTable wrapLuaObject( ILuaObject object )
|
||||
{
|
||||
LuaTable table = new LuaTable();
|
||||
String[] methods = object.getMethodNames();
|
||||
for(int i=0; i<methods.length; ++i )
|
||||
{
|
||||
if( methods[i] != null )
|
||||
{
|
||||
final int method = i;
|
||||
final ILuaObject apiObject = object;
|
||||
table.set( methods[i], new VarArgFunction() {
|
||||
@Override
|
||||
public Varargs invoke( Varargs _args )
|
||||
{
|
||||
tryAbort();
|
||||
Object[] arguments = toObjects( _args, 1 );
|
||||
Object[] results = null;
|
||||
try
|
||||
{
|
||||
results = apiObject.callMethod( new ILuaContext() {
|
||||
@Override
|
||||
public Object[] pullEvent( String filter ) throws LuaException, InterruptedException
|
||||
{
|
||||
Object[] results = pullEventRaw( filter );
|
||||
if( results.length >= 1 && results[0].equals( "terminate" ) )
|
||||
{
|
||||
throw new LuaException( "Terminated", 0 );
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] pullEventRaw( String filter ) throws InterruptedException
|
||||
{
|
||||
return yield( new Object[] { filter } );
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] yield( Object[] yieldArgs ) throws InterruptedException
|
||||
{
|
||||
try
|
||||
{
|
||||
LuaValue[] yieldValues = toValues( yieldArgs, 0 );
|
||||
Varargs results = m_coroutine_yield.invoke( LuaValue.varargsOf( yieldValues ) );
|
||||
return toObjects( results, 1 );
|
||||
}
|
||||
catch( OrphanedThread e )
|
||||
{
|
||||
throw new InterruptedException();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long issueMainThreadTask( final ILuaTask task ) throws LuaException
|
||||
{
|
||||
// Issue command
|
||||
final long taskID = MainThread.getUniqueTaskID();
|
||||
final ITask iTask = new ITask()
|
||||
{
|
||||
@Override
|
||||
public Computer getOwner()
|
||||
{
|
||||
return m_computer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute()
|
||||
{
|
||||
try
|
||||
{
|
||||
Object[] results = task.execute();
|
||||
if( results != null )
|
||||
{
|
||||
Object[] eventArguments = new Object[ results.length + 2 ];
|
||||
eventArguments[ 0 ] = taskID;
|
||||
eventArguments[ 1 ] = true;
|
||||
for( int i = 0; i < results.length; ++i )
|
||||
{
|
||||
eventArguments[ i + 2 ] = results[ i ];
|
||||
}
|
||||
m_computer.queueEvent( "task_complete", eventArguments );
|
||||
}
|
||||
else
|
||||
{
|
||||
m_computer.queueEvent( "task_complete", new Object[] { taskID, true } );
|
||||
}
|
||||
}
|
||||
catch( LuaException e )
|
||||
{
|
||||
m_computer.queueEvent( "task_complete", new Object[] {
|
||||
taskID, false, e.getMessage()
|
||||
} );
|
||||
}
|
||||
catch( Throwable t )
|
||||
{
|
||||
m_computer.queueEvent( "task_complete", new Object[] {
|
||||
taskID, false, "Java Exception Thrown: " + t.toString()
|
||||
} );
|
||||
}
|
||||
}
|
||||
};
|
||||
if( MainThread.queueTask( iTask ) )
|
||||
{
|
||||
return taskID;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new LuaException( "Task limit exceeded" );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] executeMainThreadTask( final ILuaTask task ) throws LuaException, InterruptedException
|
||||
{
|
||||
// Issue task
|
||||
final long taskID = issueMainThreadTask( task );
|
||||
|
||||
// Wait for response
|
||||
while( true )
|
||||
{
|
||||
Object[] response = pullEvent( "task_complete" );
|
||||
if( response.length >= 3 && response[ 1 ] instanceof Number && response[ 2 ] instanceof Boolean )
|
||||
{
|
||||
if( ( (Number)response[ 1 ] ).intValue() == taskID )
|
||||
{
|
||||
Object[] returnValues = new Object[ response.length - 3 ];
|
||||
if( (Boolean)response[ 2 ] )
|
||||
{
|
||||
// Extract the return values from the event and return them
|
||||
for( int i = 0; i < returnValues.length; ++i )
|
||||
{
|
||||
returnValues[ i ] = response[ i + 3 ];
|
||||
}
|
||||
return returnValues;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Extract the error message from the event and raise it
|
||||
if( response.length >= 4 && response[3] instanceof String )
|
||||
{
|
||||
throw new LuaException( (String)response[ 3 ] );
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new LuaException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}, method, arguments );
|
||||
}
|
||||
catch( InterruptedException e )
|
||||
{
|
||||
throw new OrphanedThread();
|
||||
}
|
||||
catch( LuaException e )
|
||||
{
|
||||
throw new LuaError( e.getMessage(), e.getLevel() );
|
||||
}
|
||||
catch( Throwable t )
|
||||
{
|
||||
throw new LuaError( "Java Exception Thrown: " + t.toString(), 0 );
|
||||
}
|
||||
return LuaValue.varargsOf( toValues( results, 0 ) );
|
||||
}
|
||||
} );
|
||||
}
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
private LuaValue toValue( Object object )
|
||||
{
|
||||
if( object == null )
|
||||
{
|
||||
return LuaValue.NIL;
|
||||
}
|
||||
else if( object instanceof Number )
|
||||
{
|
||||
double d = ((Number)object).doubleValue();
|
||||
return LuaValue.valueOf( d );
|
||||
}
|
||||
else if( object instanceof Boolean )
|
||||
{
|
||||
boolean b = ((Boolean)object).booleanValue();
|
||||
return LuaValue.valueOf( b );
|
||||
}
|
||||
else if( object instanceof String )
|
||||
{
|
||||
String s = object.toString();
|
||||
return LuaValue.valueOf( s );
|
||||
}
|
||||
else if( object instanceof Map )
|
||||
{
|
||||
// Table:
|
||||
// Start remembering stuff
|
||||
boolean clearWhenDone = false;
|
||||
try
|
||||
{
|
||||
if( m_valuesInProgress == null )
|
||||
{
|
||||
m_valuesInProgress = new IdentityHashMap<Object, LuaValue>();
|
||||
clearWhenDone = true;
|
||||
}
|
||||
else if( m_valuesInProgress.containsKey( object ) )
|
||||
{
|
||||
return m_valuesInProgress.get( object );
|
||||
}
|
||||
LuaValue table = new LuaTable();
|
||||
m_valuesInProgress.put( object, table );
|
||||
|
||||
// Convert all keys
|
||||
Iterator it = ((Map)object).entrySet().iterator();
|
||||
while( it.hasNext() )
|
||||
{
|
||||
Map.Entry pair = (Map.Entry)it.next();
|
||||
LuaValue key = toValue( pair.getKey() );
|
||||
LuaValue value = toValue( pair.getValue() );
|
||||
if( !key.isnil() && !value.isnil() )
|
||||
{
|
||||
table.set( key, value );
|
||||
}
|
||||
}
|
||||
return table;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Clear (if exiting top level)
|
||||
if( clearWhenDone )
|
||||
{
|
||||
m_valuesInProgress = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if( object instanceof ILuaObject )
|
||||
{
|
||||
LuaValue table = wrapLuaObject( (ILuaObject)object );
|
||||
return table;
|
||||
}
|
||||
else
|
||||
{
|
||||
return LuaValue.NIL;
|
||||
}
|
||||
}
|
||||
|
||||
private LuaValue[] toValues( Object[] objects, int leaveEmpty )
|
||||
{
|
||||
if( objects == null || objects.length == 0 )
|
||||
{
|
||||
return new LuaValue[ leaveEmpty ];
|
||||
}
|
||||
|
||||
LuaValue[] values = new LuaValue[objects.length + leaveEmpty];
|
||||
for( int i=0; i<values.length; ++i )
|
||||
{
|
||||
if( i < leaveEmpty )
|
||||
{
|
||||
values[i] = null;
|
||||
continue;
|
||||
}
|
||||
Object object = objects[i - leaveEmpty];
|
||||
values[i] = toValue( object );
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private Object toObject( LuaValue value )
|
||||
{
|
||||
switch( value.type() )
|
||||
{
|
||||
case LuaValue.TNIL:
|
||||
case LuaValue.TNONE:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
case LuaValue.TINT:
|
||||
case LuaValue.TNUMBER:
|
||||
{
|
||||
return value.todouble();
|
||||
}
|
||||
case LuaValue.TBOOLEAN:
|
||||
{
|
||||
return value.toboolean();
|
||||
}
|
||||
case LuaValue.TSTRING:
|
||||
{
|
||||
LuaString str = value.checkstring();
|
||||
return str.tojstring();
|
||||
}
|
||||
case LuaValue.TTABLE:
|
||||
{
|
||||
// Table:
|
||||
boolean clearWhenDone = false;
|
||||
try
|
||||
{
|
||||
// Start remembering stuff
|
||||
if( m_objectsInProgress == null )
|
||||
{
|
||||
m_objectsInProgress = new IdentityHashMap<LuaValue, Object>();
|
||||
clearWhenDone = true;
|
||||
}
|
||||
else if( m_objectsInProgress.containsKey( value ) )
|
||||
{
|
||||
return m_objectsInProgress.get( value );
|
||||
}
|
||||
Map table = new HashMap();
|
||||
m_objectsInProgress.put( value, table );
|
||||
|
||||
// Convert all keys
|
||||
LuaValue k = LuaValue.NIL;
|
||||
while( true )
|
||||
{
|
||||
Varargs keyValue = value.next( k );
|
||||
k = keyValue.arg1();
|
||||
if( k.isnil() )
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
LuaValue v = keyValue.arg(2);
|
||||
Object keyObject = toObject(k);
|
||||
Object valueObject = toObject(v);
|
||||
if( keyObject != null && valueObject != null )
|
||||
{
|
||||
table.put( keyObject, valueObject );
|
||||
}
|
||||
}
|
||||
return table;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Clear (if exiting top level)
|
||||
if( clearWhenDone )
|
||||
{
|
||||
m_objectsInProgress = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Object[] toObjects( Varargs values, int startIdx )
|
||||
{
|
||||
int count = values.narg();
|
||||
Object[] objects = new Object[ count - startIdx + 1 ];
|
||||
for( int n=startIdx; n<=count; ++n )
|
||||
{
|
||||
int i = n - startIdx;
|
||||
LuaValue value = values.arg(n);
|
||||
objects[i] = toObject( value );
|
||||
}
|
||||
return objects;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.terminal;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
|
||||
public class Terminal
|
||||
{
|
||||
private static final String base16 = "0123456789abcdef";
|
||||
|
||||
private int m_cursorX;
|
||||
private int m_cursorY;
|
||||
private boolean m_cursorBlink;
|
||||
private int m_cursorColour;
|
||||
private int m_cursorBackgroundColour;
|
||||
|
||||
private int m_width;
|
||||
private int m_height;
|
||||
|
||||
private TextBuffer m_text[];
|
||||
private TextBuffer m_textColour[];
|
||||
private TextBuffer m_backgroundColour[];
|
||||
|
||||
private boolean m_changed;
|
||||
|
||||
public Terminal( int width, int height )
|
||||
{
|
||||
m_width = width;
|
||||
m_height = height;
|
||||
|
||||
m_cursorColour = 0;
|
||||
m_cursorBackgroundColour = 15;
|
||||
|
||||
m_text = new TextBuffer[ m_height ];
|
||||
m_textColour = new TextBuffer[ m_height ];
|
||||
m_backgroundColour = new TextBuffer[ m_height ];
|
||||
for( int i=0; i<m_height; ++i )
|
||||
{
|
||||
m_text[i] = new TextBuffer( ' ', m_width );
|
||||
m_textColour[i] = new TextBuffer( base16.charAt( m_cursorColour ), m_width );
|
||||
m_backgroundColour[i] = new TextBuffer( base16.charAt( m_cursorBackgroundColour ), m_width );
|
||||
}
|
||||
|
||||
m_cursorX = 0;
|
||||
m_cursorY = 0;
|
||||
m_cursorBlink = false;
|
||||
|
||||
m_changed = false;
|
||||
}
|
||||
|
||||
public void reset()
|
||||
{
|
||||
m_cursorColour = 0;
|
||||
m_cursorBackgroundColour = 15;
|
||||
m_cursorX = 0;
|
||||
m_cursorY = 0;
|
||||
m_cursorBlink = false;
|
||||
clear();
|
||||
m_changed = true;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return m_width;
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return m_height;
|
||||
}
|
||||
|
||||
public void resize( int width, int height )
|
||||
{
|
||||
if( width == m_width && height == m_height )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int oldHeight = m_height;
|
||||
int oldWidth = m_width;
|
||||
TextBuffer[] oldText = m_text;
|
||||
TextBuffer[] oldTextColour = m_textColour;
|
||||
TextBuffer[] oldBackgroundColour = m_backgroundColour;
|
||||
|
||||
m_width = width;
|
||||
m_height = height;
|
||||
|
||||
m_text = new TextBuffer[ m_height ];
|
||||
m_textColour = new TextBuffer[ m_height ];
|
||||
m_backgroundColour = new TextBuffer[ m_height ];
|
||||
for( int i=0; i<m_height; ++i )
|
||||
{
|
||||
if( i >= oldHeight )
|
||||
{
|
||||
m_text[ i ] = new TextBuffer( ' ', m_width );
|
||||
m_textColour[ i ] = new TextBuffer( base16.charAt( m_cursorColour ), m_width );
|
||||
m_backgroundColour[ i ] = new TextBuffer( base16.charAt( m_cursorBackgroundColour ), m_width );
|
||||
}
|
||||
else if( m_width == oldWidth )
|
||||
{
|
||||
m_text[ i ] = oldText[ i ];
|
||||
m_textColour[ i ] = oldTextColour[ i ];
|
||||
m_backgroundColour[ i ] = oldBackgroundColour[ i ];
|
||||
}
|
||||
else
|
||||
{
|
||||
m_text[ i ] = new TextBuffer( ' ', m_width );
|
||||
m_textColour[ i ] = new TextBuffer( base16.charAt( m_cursorColour ), m_width );
|
||||
m_backgroundColour[ i ] = new TextBuffer( base16.charAt( m_cursorBackgroundColour ), m_width );
|
||||
m_text[ i ].write( oldText[ i ] );
|
||||
m_textColour[ i ].write( oldTextColour[ i ] );
|
||||
m_backgroundColour[ i ].write( oldBackgroundColour[ i ] );
|
||||
}
|
||||
}
|
||||
m_changed = true;
|
||||
}
|
||||
|
||||
public void setCursorPos( int x, int y )
|
||||
{
|
||||
if( m_cursorX != x || m_cursorY != y )
|
||||
{
|
||||
m_cursorX = x;
|
||||
m_cursorY = y;
|
||||
m_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void setCursorBlink( boolean blink )
|
||||
{
|
||||
if( m_cursorBlink != blink )
|
||||
{
|
||||
m_cursorBlink = blink;
|
||||
m_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void setTextColour( int colour )
|
||||
{
|
||||
if( m_cursorColour != colour )
|
||||
{
|
||||
m_cursorColour = colour;
|
||||
m_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void setBackgroundColour( int colour )
|
||||
{
|
||||
if( m_cursorBackgroundColour != colour )
|
||||
{
|
||||
m_cursorBackgroundColour = colour;
|
||||
m_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public int getCursorX()
|
||||
{
|
||||
return m_cursorX;
|
||||
}
|
||||
|
||||
public int getCursorY()
|
||||
{
|
||||
return m_cursorY;
|
||||
}
|
||||
|
||||
public boolean getCursorBlink()
|
||||
{
|
||||
return m_cursorBlink;
|
||||
}
|
||||
|
||||
public int getTextColour()
|
||||
{
|
||||
return m_cursorColour;
|
||||
}
|
||||
|
||||
public int getBackgroundColour()
|
||||
{
|
||||
return m_cursorBackgroundColour;
|
||||
}
|
||||
|
||||
public void blit( String text, String textColour, String backgroundColour )
|
||||
{
|
||||
int x = m_cursorX;
|
||||
int y = m_cursorY;
|
||||
if( y >= 0 && y < m_height )
|
||||
{
|
||||
m_text[ y ].write( text, x );
|
||||
m_textColour[ y ].write( textColour, x );
|
||||
m_backgroundColour[ y ].write( backgroundColour, x );
|
||||
m_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void write( String text )
|
||||
{
|
||||
int x = m_cursorX;
|
||||
int y = m_cursorY;
|
||||
if( y >= 0 && y < m_height )
|
||||
{
|
||||
m_text[ y ].write( text, x );
|
||||
m_textColour[ y ].fill( base16.charAt( m_cursorColour ), x, x + text.length() );
|
||||
m_backgroundColour[ y ].fill( base16.charAt( m_cursorBackgroundColour ), x, x + text.length() );
|
||||
m_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void scroll( int yDiff )
|
||||
{
|
||||
if( yDiff != 0 )
|
||||
{
|
||||
TextBuffer[] newText = new TextBuffer[ m_height ];
|
||||
TextBuffer[] newTextColour = new TextBuffer[ m_height ];
|
||||
TextBuffer[] newBackgroundColour = new TextBuffer[ m_height ];
|
||||
for( int y = 0; y < m_height; ++y )
|
||||
{
|
||||
int oldY = y + yDiff;
|
||||
if( oldY >= 0 && oldY < m_height )
|
||||
{
|
||||
newText[ y ] = m_text[ oldY ];
|
||||
newTextColour[ y ] = m_textColour[ oldY ];
|
||||
newBackgroundColour[ y ] = m_backgroundColour[ oldY ];
|
||||
}
|
||||
else
|
||||
{
|
||||
newText[ y ] = new TextBuffer( ' ', m_width );
|
||||
newTextColour[ y ] = new TextBuffer( base16.charAt( m_cursorColour ), m_width );
|
||||
newBackgroundColour[ y ] = new TextBuffer( base16.charAt( m_cursorBackgroundColour ), m_width );
|
||||
}
|
||||
}
|
||||
m_text = newText;
|
||||
m_textColour = newTextColour;
|
||||
m_backgroundColour = newBackgroundColour;
|
||||
m_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void clear()
|
||||
{
|
||||
for( int y = 0; y < m_height; ++y )
|
||||
{
|
||||
m_text[ y ].fill( ' ' );
|
||||
m_textColour[ y ].fill( base16.charAt( m_cursorColour ) );
|
||||
m_backgroundColour[ y ].fill( base16.charAt( m_cursorBackgroundColour ) );
|
||||
}
|
||||
m_changed = true;
|
||||
}
|
||||
|
||||
public void clearLine()
|
||||
{
|
||||
int y = m_cursorY;
|
||||
if( y >= 0 && y < m_height )
|
||||
{
|
||||
m_text[ y ].fill( ' ' );
|
||||
m_textColour[ y ].fill( base16.charAt( m_cursorColour ) );
|
||||
m_backgroundColour[ y ].fill( base16.charAt( m_cursorBackgroundColour ) );
|
||||
m_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public TextBuffer getLine( int y )
|
||||
{
|
||||
if( y >= 0 && y < m_height )
|
||||
{
|
||||
return m_text[ y ];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setLine( int y, String text, String textColour, String backgroundColour )
|
||||
{
|
||||
m_text[y].write( text );
|
||||
m_textColour[y].write( textColour );
|
||||
m_backgroundColour[y].write( backgroundColour );
|
||||
m_changed = true;
|
||||
}
|
||||
|
||||
public TextBuffer getTextColourLine( int y )
|
||||
{
|
||||
if( y>=0 && y<m_height )
|
||||
{
|
||||
return m_textColour[ y ];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public TextBuffer getBackgroundColourLine( int y )
|
||||
{
|
||||
if( y>=0 && y<m_height )
|
||||
{
|
||||
return m_backgroundColour[ y ];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean getChanged()
|
||||
{
|
||||
return m_changed;
|
||||
}
|
||||
|
||||
public void clearChanged()
|
||||
{
|
||||
m_changed = false;
|
||||
}
|
||||
|
||||
public void writeToNBT( NBTTagCompound nbttagcompound )
|
||||
{
|
||||
nbttagcompound.setInteger( "term_cursorX", m_cursorX );
|
||||
nbttagcompound.setInteger( "term_cursorY", m_cursorY );
|
||||
nbttagcompound.setBoolean( "term_cursorBlink", m_cursorBlink );
|
||||
nbttagcompound.setInteger( "term_textColour", m_cursorColour );
|
||||
nbttagcompound.setInteger( "term_bgColour", m_cursorBackgroundColour );
|
||||
for( int n=0; n<m_height; ++n )
|
||||
{
|
||||
nbttagcompound.setString( "term_text_" + n, m_text[n].toString() );
|
||||
nbttagcompound.setString( "term_textColour_" + n, m_textColour[n].toString() );
|
||||
nbttagcompound.setString( "term_textBgColour_" + n, m_backgroundColour[ n ].toString() );
|
||||
}
|
||||
}
|
||||
|
||||
public void readFromNBT( NBTTagCompound nbttagcompound )
|
||||
{
|
||||
m_cursorX = nbttagcompound.getInteger( "term_cursorX" );
|
||||
m_cursorY = nbttagcompound.getInteger( "term_cursorY" );
|
||||
m_cursorBlink = nbttagcompound.getBoolean( "term_cursorBlink" );
|
||||
m_cursorColour = nbttagcompound.getInteger( "term_textColour" );
|
||||
m_cursorBackgroundColour = nbttagcompound.getInteger( "term_bgColour" );
|
||||
|
||||
for( int n=0; n<m_height; ++n )
|
||||
{
|
||||
m_text[n].fill( ' ' );
|
||||
if( nbttagcompound.hasKey( "term_text_" + n ) )
|
||||
{
|
||||
m_text[n].write( nbttagcompound.getString( "term_text_" + n ) );
|
||||
}
|
||||
m_textColour[n].fill( base16.charAt( m_cursorColour ) );
|
||||
if( nbttagcompound.hasKey( "term_textColour_" + n ) )
|
||||
{
|
||||
m_textColour[n].write( nbttagcompound.getString( "term_textColour_" + n ) );
|
||||
}
|
||||
m_backgroundColour[n].fill( base16.charAt( m_cursorBackgroundColour ) );
|
||||
if( nbttagcompound.hasKey( "term_textBgColour_" + n ) )
|
||||
{
|
||||
m_backgroundColour[n].write( nbttagcompound.getString( "term_textBgColour_" + n ) );
|
||||
}
|
||||
}
|
||||
m_changed = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.terminal;
|
||||
|
||||
public class TextBuffer
|
||||
{
|
||||
public char[] m_text;
|
||||
|
||||
public TextBuffer( char c, int length )
|
||||
{
|
||||
m_text = new char[length];
|
||||
for( int i = 0; i < length; ++i )
|
||||
{
|
||||
m_text[i] = c;
|
||||
}
|
||||
}
|
||||
|
||||
public TextBuffer( String text )
|
||||
{
|
||||
this( text, 1 );
|
||||
}
|
||||
|
||||
public TextBuffer( String text, int repetitions )
|
||||
{
|
||||
int textLength = text.length();
|
||||
m_text = new char[ textLength * repetitions ];
|
||||
for( int i = 0; i < repetitions; ++i )
|
||||
{
|
||||
for( int j = 0; j < textLength; ++j )
|
||||
{
|
||||
m_text[ j + i * textLength ] = text.charAt(j );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public TextBuffer( TextBuffer text )
|
||||
{
|
||||
this( text, 1 );
|
||||
}
|
||||
|
||||
public TextBuffer( TextBuffer text, int repetitions )
|
||||
{
|
||||
int textLength = text.length();
|
||||
m_text = new char[ textLength * repetitions ];
|
||||
for( int i = 0; i < repetitions; ++i )
|
||||
{
|
||||
for( int j = 0; j < textLength; ++j )
|
||||
{
|
||||
m_text[ j + i * textLength ] = text.charAt(j );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int length()
|
||||
{
|
||||
return m_text.length;
|
||||
}
|
||||
|
||||
public String read()
|
||||
{
|
||||
return read( 0, m_text.length );
|
||||
}
|
||||
|
||||
public String read( int start )
|
||||
{
|
||||
return read( start, m_text.length );
|
||||
}
|
||||
|
||||
public String read( int start, int end )
|
||||
{
|
||||
start = Math.max( start, 0 );
|
||||
end = Math.min( end, m_text.length );
|
||||
int textLength = Math.max( end - start, 0 );
|
||||
return new String( m_text, start, textLength );
|
||||
}
|
||||
|
||||
public void write( String text )
|
||||
{
|
||||
write( text, 0, text.length() );
|
||||
}
|
||||
|
||||
public void write( String text, int start )
|
||||
{
|
||||
write( text, start, start + text.length() );
|
||||
}
|
||||
|
||||
public void write( String text, int start, int end )
|
||||
{
|
||||
int pos = start;
|
||||
start = Math.max( start, 0 );
|
||||
end = Math.min( end, pos + text.length() );
|
||||
end = Math.min( end, m_text.length );
|
||||
for( int i=start; i<end; ++i )
|
||||
{
|
||||
m_text[i] = text.charAt( i - pos );
|
||||
}
|
||||
}
|
||||
|
||||
public void write( TextBuffer text )
|
||||
{
|
||||
write( text, 0, text.length() );
|
||||
}
|
||||
|
||||
public void write( TextBuffer text, int start )
|
||||
{
|
||||
write( text, start, start + text.length() );
|
||||
}
|
||||
|
||||
public void write( TextBuffer text, int start, int end )
|
||||
{
|
||||
int pos = start;
|
||||
start = Math.max( start, 0 );
|
||||
end = Math.min( end, pos + text.length() );
|
||||
end = Math.min( end, m_text.length );
|
||||
for( int i=start; i<end; ++i )
|
||||
{
|
||||
m_text[i] = text.charAt( i - pos );
|
||||
}
|
||||
}
|
||||
|
||||
public void fill( char c )
|
||||
{
|
||||
fill( c, 0, m_text.length );
|
||||
}
|
||||
|
||||
public void fill( char c, int start )
|
||||
{
|
||||
fill( c, start, m_text.length );
|
||||
}
|
||||
|
||||
public void fill( char c, int start, int end )
|
||||
{
|
||||
start = Math.max( start, 0 );
|
||||
end = Math.min( end, m_text.length );
|
||||
for( int i=start; i<end; ++i )
|
||||
{
|
||||
m_text[i] = c;
|
||||
}
|
||||
}
|
||||
|
||||
public void fill( String text )
|
||||
{
|
||||
fill( text, 0, m_text.length );
|
||||
}
|
||||
|
||||
public void fill( String text, int start )
|
||||
{
|
||||
fill( text, start, m_text.length );
|
||||
}
|
||||
|
||||
public void fill( String text, int start, int end )
|
||||
{
|
||||
int pos = start;
|
||||
start = Math.max( start, 0 );
|
||||
end = Math.min( end, m_text.length );
|
||||
|
||||
int textLength = text.length();
|
||||
for( int i=start; i<end; ++i )
|
||||
{
|
||||
m_text[i] = text.charAt( (i - pos) % textLength );
|
||||
}
|
||||
}
|
||||
|
||||
public void fill( TextBuffer text )
|
||||
{
|
||||
fill( text, 0, m_text.length );
|
||||
}
|
||||
|
||||
public void fill( TextBuffer text, int start )
|
||||
{
|
||||
fill( text, start, m_text.length );
|
||||
}
|
||||
|
||||
public void fill( TextBuffer text, int start, int end )
|
||||
{
|
||||
int pos = start;
|
||||
start = Math.max( start, 0 );
|
||||
end = Math.min( end, m_text.length );
|
||||
|
||||
int textLength = text.length();
|
||||
for( int i=start; i<end; ++i )
|
||||
{
|
||||
m_text[i] = text.charAt( (i - pos) % textLength );
|
||||
}
|
||||
}
|
||||
|
||||
public char charAt( int i )
|
||||
{
|
||||
return m_text[ i ];
|
||||
}
|
||||
|
||||
public void setChar( int i, char c )
|
||||
{
|
||||
if( i >= 0 && i <m_text.length )
|
||||
{
|
||||
m_text[ i ] = c;
|
||||
}
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return new String( m_text );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.server.proxy;
|
||||
|
||||
import dan200.computercraft.shared.proxy.CCTurtleProxyCommon;
|
||||
|
||||
public class CCTurtleProxyServer extends CCTurtleProxyCommon
|
||||
{
|
||||
public CCTurtleProxyServer()
|
||||
{
|
||||
}
|
||||
|
||||
// ICCTurtleProxy implementation
|
||||
|
||||
@Override
|
||||
public void init()
|
||||
{
|
||||
super.init();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.server.proxy;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.shared.computer.blocks.TileComputer;
|
||||
import dan200.computercraft.shared.peripheral.diskdrive.TileDiskDrive;
|
||||
import dan200.computercraft.shared.peripheral.printer.TilePrinter;
|
||||
import dan200.computercraft.shared.proxy.ComputerCraftProxyCommon;
|
||||
import dan200.computercraft.shared.turtle.blocks.TileTurtle;
|
||||
import net.minecraft.entity.player.InventoryPlayer;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraftforge.common.DimensionManager;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class ComputerCraftProxyServer extends ComputerCraftProxyCommon
|
||||
{
|
||||
public ComputerCraftProxyServer()
|
||||
{
|
||||
}
|
||||
|
||||
// IComputerCraftProxy implementation
|
||||
|
||||
@Override
|
||||
public void init()
|
||||
{
|
||||
super.init();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getTurtleGUI( InventoryPlayer inventory, TileTurtle turtle )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClient()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getGlobalCursorBlink()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getRenderFrame()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getFixedWidthFontRenderer()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void playRecord( String record, String recordInfo, World world, BlockPos pos )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getDiskDriveGUI( InventoryPlayer inventory, TileDiskDrive drive )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getComputerGUI( TileComputer computer )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrinterGUI( InventoryPlayer inventory, TilePrinter printer )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrintoutGUI( InventoryPlayer inventory )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPocketComputerGUI( InventoryPlayer inventory )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getWorldDir( World world )
|
||||
{
|
||||
return new File( ComputerCraft.getBaseDir(), DimensionManager.getWorld(0).getSaveHandler().getWorldDirectoryName() );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.common;
|
||||
|
||||
import net.minecraft.block.material.Material;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.world.IBlockAccess;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
public abstract class BlockDirectional extends BlockGeneric
|
||||
{
|
||||
protected BlockDirectional( Material material )
|
||||
{
|
||||
super( material );
|
||||
}
|
||||
|
||||
public EnumFacing getDirection( IBlockAccess world, BlockPos pos )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof IDirectionalTile )
|
||||
{
|
||||
IDirectionalTile directional = (IDirectionalTile)tile;
|
||||
return directional.getDirection();
|
||||
}
|
||||
return EnumFacing.NORTH;
|
||||
}
|
||||
|
||||
public void setDirection( World world, BlockPos pos, EnumFacing dir )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof IDirectionalTile )
|
||||
{
|
||||
IDirectionalTile directional = (IDirectionalTile)tile;
|
||||
directional.setDirection( dir );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.common;
|
||||
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.block.ITileEntityProvider;
|
||||
import net.minecraft.block.material.Material;
|
||||
import net.minecraft.block.state.IBlockState;
|
||||
import net.minecraft.enchantment.EnchantmentHelper;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.EntityLivingBase;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.AxisAlignedBB;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.util.MovingObjectPosition;
|
||||
import net.minecraft.world.Explosion;
|
||||
import net.minecraft.world.IBlockAccess;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class BlockGeneric extends Block implements
|
||||
ITileEntityProvider
|
||||
{
|
||||
protected BlockGeneric( Material material )
|
||||
{
|
||||
super( material );
|
||||
this.isBlockContainer = true;
|
||||
}
|
||||
|
||||
protected abstract IBlockState getDefaultBlockState( int damage, EnumFacing placedSide );
|
||||
protected abstract TileGeneric createTile( IBlockState state );
|
||||
protected abstract TileGeneric createTile( int damage );
|
||||
|
||||
@Override
|
||||
public final void dropBlockAsItemWithChance( World world, BlockPos pos, IBlockState state, float chance, int fortune )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public final List<ItemStack> getDrops( IBlockAccess world, BlockPos pos, IBlockState state, int fortune )
|
||||
{
|
||||
ArrayList<ItemStack> drops = new ArrayList<ItemStack>( 1 );
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
generic.getDroppedItems( drops, fortune, false, false );
|
||||
}
|
||||
return drops;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final IBlockState onBlockPlaced( World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, int damage, EntityLivingBase placer )
|
||||
{
|
||||
return getDefaultBlockState( damage, side );
|
||||
}
|
||||
|
||||
@Override
|
||||
public final boolean removedByPlayer( World world, BlockPos pos, EntityPlayer player, boolean willHarvest )
|
||||
{
|
||||
if( !world.isRemote )
|
||||
{
|
||||
// Drop items
|
||||
int fortune = EnchantmentHelper.getFortuneModifier( player );
|
||||
boolean creative = player.capabilities.isCreativeMode;
|
||||
boolean silkTouch = EnchantmentHelper.getSilkTouchModifier( player );
|
||||
dropAllItems( world, pos, fortune, creative, silkTouch );
|
||||
}
|
||||
|
||||
// Remove block
|
||||
return super.removedByPlayer( world, pos, player, willHarvest );
|
||||
}
|
||||
|
||||
public final void dropAllItems( World world, BlockPos pos, int fortune, boolean creative, boolean silkTouch )
|
||||
{
|
||||
// Get items to drop
|
||||
List<ItemStack> drops = new ArrayList<ItemStack>( 1 );
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
generic.getDroppedItems( drops, fortune, creative, silkTouch );
|
||||
}
|
||||
|
||||
// Drop items
|
||||
if( drops.size() > 0 )
|
||||
{
|
||||
Iterator<ItemStack> it = drops.iterator();
|
||||
while( it.hasNext() )
|
||||
{
|
||||
ItemStack item = it.next();
|
||||
dropItem( world, pos, item );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public final void dropItem( World world, BlockPos pos, ItemStack stack )
|
||||
{
|
||||
Block.spawnAsEntity( world, pos, stack );
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void breakBlock( World world, BlockPos pos, IBlockState newState )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
generic.destroy();
|
||||
}
|
||||
super.breakBlock( world, pos, newState );
|
||||
world.removeTileEntity( pos );
|
||||
}
|
||||
|
||||
@Override
|
||||
public final ItemStack getPickBlock( MovingObjectPosition target, World world, BlockPos pos, EntityPlayer player )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
return generic.getPickedItem();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final ItemStack createStackedBlock( IBlockState state )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final boolean onBlockActivated( World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumFacing side, float hitX, float hitY, float hitZ )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
return generic.onActivate( player, side, hitX, hitY, hitZ );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void onNeighborBlockChange( World world, BlockPos pos, IBlockState state, Block neighbour )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
generic.onNeighbourChange();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final boolean isSideSolid( IBlockAccess world, BlockPos pos, EnumFacing side )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
return generic.isSolidOnSide( side.ordinal() );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final boolean canBeReplacedByLeaves( IBlockAccess world, BlockPos pos )
|
||||
{
|
||||
return false; // Generify me if anyone ever feels the need to change this
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getExplosionResistance( World world, BlockPos pos, Entity exploder, Explosion explosion )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric && tile.hasWorldObj() )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
if( generic.isImmuneToExplosion( exploder ) )
|
||||
{
|
||||
return 2000.0f;
|
||||
}
|
||||
}
|
||||
return super.getExplosionResistance( exploder );
|
||||
}
|
||||
|
||||
private void setBlockBounds( AxisAlignedBB bounds )
|
||||
{
|
||||
setBlockBounds(
|
||||
(float)bounds.minX, (float)bounds.minY, (float)bounds.minZ,
|
||||
(float)bounds.maxX, (float)bounds.maxY, (float)bounds.maxZ
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void setBlockBoundsBasedOnState( IBlockAccess world, BlockPos pos )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric && tile.hasWorldObj() )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
setBlockBounds( generic.getBounds() );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final AxisAlignedBB getCollisionBoundingBox( World world, BlockPos pos, IBlockState state )
|
||||
{
|
||||
setBlockBoundsBasedOnState( world, pos );
|
||||
return super.getCollisionBoundingBox( world, pos, state );
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void addCollisionBoxesToList( World world, BlockPos pos, IBlockState state, AxisAlignedBB bigBox, List list, Entity entity )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
|
||||
// Get collision bounds
|
||||
List<AxisAlignedBB> collision = new ArrayList<AxisAlignedBB>( 1 );
|
||||
generic.getCollisionBounds( collision );
|
||||
|
||||
// Add collision bounds to list
|
||||
if( collision.size() > 0 )
|
||||
{
|
||||
Iterator<AxisAlignedBB> it = collision.iterator();
|
||||
while( it.hasNext() )
|
||||
{
|
||||
AxisAlignedBB localBounds = it.next();
|
||||
setBlockBounds( localBounds );
|
||||
|
||||
AxisAlignedBB bounds = super.getCollisionBoundingBox( world, pos, state );
|
||||
if( bounds != null && bigBox.intersectsWith(bounds) )
|
||||
{
|
||||
list.add( bounds );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final boolean canProvidePower()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final boolean canConnectRedstone( IBlockAccess world, BlockPos pos, EnumFacing side )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
return generic.getRedstoneConnectivity( side );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final int getStrongPower( IBlockAccess world, BlockPos pos, IBlockState state, EnumFacing oppositeSide )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric && tile.hasWorldObj() )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
return generic.getRedstoneOutput( oppositeSide.getOpposite() );
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final int getWeakPower( IBlockAccess world, BlockPos pos, IBlockState state, EnumFacing oppositeSide )
|
||||
{
|
||||
return getStrongPower( world, pos, state, oppositeSide );
|
||||
}
|
||||
|
||||
public boolean getBundledRedstoneConnectivity( World world, BlockPos pos, EnumFacing side )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
return generic.getBundledRedstoneConnectivity( side );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric && tile.hasWorldObj() )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
return generic.getBundledRedstoneOutput( side );
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onBlockEventReceived( World world, BlockPos pos, IBlockState state, int eventID, int eventParameter )
|
||||
{
|
||||
if( world.isRemote )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileGeneric )
|
||||
{
|
||||
TileGeneric generic = (TileGeneric)tile;
|
||||
generic.onBlockEvent( eventID, eventParameter );
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final TileEntity createTileEntity( World world, IBlockState state )
|
||||
{
|
||||
return createTile( state );
|
||||
}
|
||||
|
||||
@Override
|
||||
public final TileEntity createNewTileEntity( World world, int damage )
|
||||
{
|
||||
return createTile( damage );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.common;
|
||||
|
||||
import dan200.computercraft.core.terminal.Terminal;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
|
||||
public class ClientTerminal implements ITerminal
|
||||
{
|
||||
private boolean m_colour;
|
||||
private Terminal m_terminal;
|
||||
private boolean m_terminalChanged;
|
||||
private boolean m_terminalChangedLastFrame;
|
||||
|
||||
public ClientTerminal( boolean colour )
|
||||
{
|
||||
m_colour = colour;
|
||||
m_terminal = null;
|
||||
m_terminalChanged = false;
|
||||
m_terminalChangedLastFrame = false;
|
||||
}
|
||||
|
||||
public void update()
|
||||
{
|
||||
m_terminalChangedLastFrame = m_terminalChanged || (m_terminal != null && m_terminal.getChanged());
|
||||
if( m_terminal != null )
|
||||
{
|
||||
m_terminal.clearChanged();
|
||||
}
|
||||
m_terminalChanged = false;
|
||||
}
|
||||
|
||||
public boolean hasTerminalChanged()
|
||||
{
|
||||
return m_terminalChangedLastFrame;
|
||||
}
|
||||
|
||||
// ITerminal implementation
|
||||
|
||||
@Override
|
||||
public Terminal getTerminal()
|
||||
{
|
||||
return m_terminal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isColour()
|
||||
{
|
||||
return m_colour;
|
||||
}
|
||||
|
||||
public void readDescription( NBTTagCompound nbttagcompound )
|
||||
{
|
||||
m_colour = nbttagcompound.getBoolean( "colour" );
|
||||
if( nbttagcompound.hasKey( "terminal" ) )
|
||||
{
|
||||
NBTTagCompound terminal = nbttagcompound.getCompoundTag( "terminal" );
|
||||
resizeTerminal( terminal.getInteger( "term_width" ), terminal.getInteger( "term_height" ) );
|
||||
m_terminal.readFromNBT( terminal );
|
||||
}
|
||||
else
|
||||
{
|
||||
deleteTerminal();
|
||||
}
|
||||
}
|
||||
|
||||
private void resizeTerminal( int width, int height )
|
||||
{
|
||||
if( m_terminal == null )
|
||||
{
|
||||
m_terminal = new Terminal( width, height );
|
||||
m_terminalChanged = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_terminal.resize( width, height );
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteTerminal()
|
||||
{
|
||||
if( m_terminal != null )
|
||||
{
|
||||
m_terminal = null;
|
||||
m_terminalChanged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.common;
|
||||
|
||||
import dan200.computercraft.api.redstone.IBundledRedstoneProvider;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
public class DefaultBundledRedstoneProvider implements IBundledRedstoneProvider
|
||||
{
|
||||
public DefaultBundledRedstoneProvider()
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side )
|
||||
{
|
||||
return getDefaultBundledRedstoneOutput( world, pos, side );
|
||||
}
|
||||
|
||||
public static int getDefaultBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side )
|
||||
{
|
||||
Block block = world.getBlockState( pos ).getBlock();
|
||||
if( block != null && block instanceof BlockGeneric )
|
||||
{
|
||||
BlockGeneric generic = (BlockGeneric)block;
|
||||
if( generic.getBundledRedstoneConnectivity( world, pos, side ) )
|
||||
{
|
||||
return generic.getBundledRedstoneOutput( world, pos, side );
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.common;
|
||||
|
||||
import net.minecraft.util.EnumFacing;
|
||||
|
||||
public interface IDirectionalTile
|
||||
{
|
||||
public EnumFacing getDirection();
|
||||
public void setDirection( EnumFacing dir );
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.common;
|
||||
|
||||
import dan200.computercraft.core.terminal.Terminal;
|
||||
|
||||
public interface ITerminal
|
||||
{
|
||||
public Terminal getTerminal();
|
||||
public boolean isColour();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.common;
|
||||
|
||||
public interface ITerminalTile
|
||||
{
|
||||
public ITerminal getTerminal();
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.common;
|
||||
|
||||
import dan200.computercraft.core.terminal.Terminal;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
|
||||
public class ServerTerminal implements ITerminal
|
||||
{
|
||||
private final boolean m_colour;
|
||||
private Terminal m_terminal;
|
||||
private boolean m_terminalChanged;
|
||||
private boolean m_terminalChangedLastFrame;
|
||||
|
||||
public ServerTerminal( boolean colour )
|
||||
{
|
||||
m_colour = colour;
|
||||
m_terminal = null;
|
||||
m_terminalChanged = false;
|
||||
m_terminalChangedLastFrame = false;
|
||||
}
|
||||
|
||||
public ServerTerminal( boolean colour, int terminalWidth, int terminalHeight )
|
||||
{
|
||||
m_colour = colour;
|
||||
m_terminal = new Terminal( terminalWidth, terminalHeight );
|
||||
m_terminalChanged = false;
|
||||
m_terminalChangedLastFrame = false;
|
||||
}
|
||||
|
||||
public void resize( int width, int height )
|
||||
{
|
||||
if( m_terminal == null )
|
||||
{
|
||||
m_terminal = new Terminal( width, height );
|
||||
m_terminalChanged = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_terminal.resize( width, height );
|
||||
}
|
||||
}
|
||||
|
||||
public void delete()
|
||||
{
|
||||
if( m_terminal != null )
|
||||
{
|
||||
m_terminal = null;
|
||||
m_terminalChanged = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void update()
|
||||
{
|
||||
m_terminalChangedLastFrame = m_terminalChanged || (m_terminal != null && m_terminal.getChanged());
|
||||
if( m_terminal != null )
|
||||
{
|
||||
m_terminal.clearChanged();
|
||||
}
|
||||
m_terminalChanged = false;
|
||||
}
|
||||
|
||||
public boolean hasTerminalChanged()
|
||||
{
|
||||
return m_terminalChangedLastFrame;
|
||||
}
|
||||
|
||||
// ITerminal implementation
|
||||
|
||||
@Override
|
||||
public Terminal getTerminal()
|
||||
{
|
||||
return m_terminal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isColour()
|
||||
{
|
||||
return m_colour;
|
||||
}
|
||||
|
||||
// Networking stuff
|
||||
|
||||
public void writeDescription( NBTTagCompound nbttagcompound )
|
||||
{
|
||||
nbttagcompound.setBoolean( "colour", m_colour );
|
||||
if( m_terminal != null )
|
||||
{
|
||||
NBTTagCompound terminal = new NBTTagCompound();
|
||||
terminal.setInteger( "term_width", m_terminal.getWidth() );
|
||||
terminal.setInteger( "term_height", m_terminal.getHeight() );
|
||||
m_terminal.writeToNBT( terminal );
|
||||
nbttagcompound.setTag( "terminal", terminal );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.common;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.shared.network.ComputerCraftPacket;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.block.state.IBlockState;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.network.NetworkManager;
|
||||
import net.minecraft.network.Packet;
|
||||
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.AxisAlignedBB;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public abstract class TileGeneric extends TileEntity
|
||||
{
|
||||
public TileGeneric()
|
||||
{
|
||||
}
|
||||
|
||||
public void requestTileEntityUpdate()
|
||||
{
|
||||
if( worldObj.isRemote )
|
||||
{
|
||||
ComputerCraftPacket packet = new ComputerCraftPacket();
|
||||
packet.m_packetType = ComputerCraftPacket.RequestTileEntityUpdate;
|
||||
|
||||
BlockPos pos = getPos();
|
||||
packet.m_dataInt = new int[]{ pos.getX(), pos.getY(), pos.getZ() };
|
||||
ComputerCraft.sendToServer( packet );
|
||||
}
|
||||
}
|
||||
|
||||
public void destroy()
|
||||
{
|
||||
}
|
||||
|
||||
public BlockGeneric getBlock()
|
||||
{
|
||||
Block block = worldObj.getBlockState( getPos() ).getBlock();
|
||||
if( block != null && block instanceof BlockGeneric )
|
||||
{
|
||||
return (BlockGeneric)block;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected final IBlockState getBlockState()
|
||||
{
|
||||
return worldObj.getBlockState( getPos() );
|
||||
}
|
||||
|
||||
public final void updateBlock()
|
||||
{
|
||||
worldObj.markBlockForUpdate( getPos() );
|
||||
worldObj.markChunkDirty( getPos(), this );
|
||||
}
|
||||
|
||||
protected final void setBlockState( IBlockState newState )
|
||||
{
|
||||
worldObj.setBlockState( getPos(), newState, 3 );
|
||||
}
|
||||
|
||||
public void getDroppedItems( List<ItemStack> drops, int fortune, boolean creative, boolean silkTouch )
|
||||
{
|
||||
}
|
||||
|
||||
public ItemStack getPickedItem()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean onActivate( EntityPlayer player, EnumFacing side, float hitX, float hitY, float hitZ )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public void onNeighbourChange()
|
||||
{
|
||||
}
|
||||
|
||||
public boolean isSolidOnSide( int side )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isImmuneToExplosion( Entity exploder )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public AxisAlignedBB getBounds()
|
||||
{
|
||||
return new AxisAlignedBB( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 );
|
||||
}
|
||||
|
||||
public void getCollisionBounds( List<AxisAlignedBB> bounds )
|
||||
{
|
||||
bounds.add( getBounds() );
|
||||
}
|
||||
|
||||
public boolean getRedstoneConnectivity( EnumFacing side )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getRedstoneOutput( EnumFacing side )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
public boolean getBundledRedstoneConnectivity( EnumFacing side )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getBundledRedstoneOutput( EnumFacing side )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected double getInteractRange( EntityPlayer player )
|
||||
{
|
||||
return 8.0;
|
||||
}
|
||||
|
||||
public boolean isUsable( EntityPlayer player, boolean ignoreRange )
|
||||
{
|
||||
if( player != null && player.isEntityAlive() )
|
||||
{
|
||||
if( worldObj.getTileEntity( getPos() ) == this )
|
||||
{
|
||||
if( !ignoreRange )
|
||||
{
|
||||
double range = getInteractRange( player );
|
||||
BlockPos pos = getPos();
|
||||
return player.getEntityWorld() == worldObj &&
|
||||
player.getDistanceSq( (double)pos.getX() + 0.5, (double)pos.getY() + 0.5, (double)pos.getZ() + 0.5 ) <= ( range * range );
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
protected void writeDescription( NBTTagCompound nbttagcompound )
|
||||
{
|
||||
}
|
||||
|
||||
protected void readDescription( NBTTagCompound nbttagcompound )
|
||||
{
|
||||
}
|
||||
|
||||
public final void sendBlockEvent( int eventID )
|
||||
{
|
||||
sendBlockEvent( eventID, 0 );
|
||||
}
|
||||
|
||||
public final void sendBlockEvent( int eventID, int eventParameter )
|
||||
{
|
||||
worldObj.addBlockEvent( getPos(), worldObj.getBlockState( getPos() ).getBlock(), eventID, eventParameter );
|
||||
}
|
||||
|
||||
public void onBlockEvent( int eventID, int eventParameter )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldRefresh( World world, BlockPos pos, IBlockState oldState, IBlockState newState )
|
||||
{
|
||||
return newState.getBlock() != oldState.getBlock();
|
||||
}
|
||||
|
||||
@Override
|
||||
public final Packet getDescriptionPacket()
|
||||
{
|
||||
// Communicate properties
|
||||
NBTTagCompound nbttagcompound = new NBTTagCompound();
|
||||
writeDescription( nbttagcompound );
|
||||
return new S35PacketUpdateTileEntity( getPos(), 0, nbttagcompound );
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void onDataPacket( NetworkManager net, S35PacketUpdateTileEntity packet )
|
||||
{
|
||||
switch( packet.getTileEntityType() )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// Receive properties
|
||||
NBTTagCompound nbttagcompound = packet.getNbtCompound();
|
||||
readDescription( nbttagcompound );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.computer.apis;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.ILuaTask;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.core.apis.ILuaAPI;
|
||||
import dan200.computercraft.shared.computer.blocks.TileCommandComputer;
|
||||
import dan200.computercraft.shared.util.WorldUtil;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.block.properties.IProperty;
|
||||
import net.minecraft.block.state.IBlockState;
|
||||
import net.minecraft.command.ICommand;
|
||||
import net.minecraft.command.ICommandManager;
|
||||
import net.minecraft.command.ICommandSender;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class CommandAPI implements ILuaAPI
|
||||
{
|
||||
private TileCommandComputer m_computer;
|
||||
|
||||
public CommandAPI( TileCommandComputer computer )
|
||||
{
|
||||
m_computer = computer;
|
||||
}
|
||||
|
||||
// ILuaAPI implementation
|
||||
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"commands"
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startup()
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void advance( double dt )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown()
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"exec",
|
||||
"execAsync",
|
||||
"list",
|
||||
"getBlockPosition",
|
||||
"getBlockInfos",
|
||||
"getBlockInfo"
|
||||
};
|
||||
}
|
||||
|
||||
private Map<Object, Object> createOutput( String output )
|
||||
{
|
||||
Map<Object, Object> result = new HashMap<Object, Object>( 1 );
|
||||
result.put( 1, output );
|
||||
return result;
|
||||
}
|
||||
|
||||
private Object[] doCommand( String command )
|
||||
{
|
||||
MinecraftServer server = MinecraftServer.getServer();
|
||||
if( server != null && server.isCommandBlockEnabled() )
|
||||
{
|
||||
ICommandManager commandManager = server.getCommandManager();
|
||||
try
|
||||
{
|
||||
TileCommandComputer.CommandSender sender = m_computer.getCommandSender();
|
||||
sender.clearOutput();
|
||||
|
||||
int result = commandManager.executeCommand( sender, command );
|
||||
return new Object[]{ (result > 0), sender.copyOutput() };
|
||||
}
|
||||
catch( Throwable t )
|
||||
{
|
||||
return new Object[]{ false, createOutput( "Java Exception Thrown: " + t.toString() ) };
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return new Object[] { false, createOutput( "Command blocks disabled by server" ) };
|
||||
}
|
||||
}
|
||||
|
||||
private Object getBlockInfo( World world, BlockPos pos )
|
||||
{
|
||||
// Get the details of the block
|
||||
IBlockState state = world.getBlockState( pos );
|
||||
Block block = state.getBlock();
|
||||
String name = ((ResourceLocation)Block.blockRegistry.getNameForObject( block )).toString();
|
||||
int metadata = block.getMetaFromState( state );
|
||||
|
||||
Map<Object, Object> table = new HashMap<Object, Object>();
|
||||
table.put( "name", name );
|
||||
table.put( "metadata", metadata );
|
||||
|
||||
Map<Object, Object> stateTable = new HashMap<Object, Object>();
|
||||
for( Object o : block.getActualState( state, world, pos ).getProperties().entrySet() )
|
||||
{
|
||||
ImmutableMap.Entry<IProperty, Object> entry = (ImmutableMap.Entry<IProperty, Object>)o;
|
||||
String propertyName = entry.getKey().getName();
|
||||
Object value = entry.getValue();
|
||||
if( value instanceof String || value instanceof Number || value instanceof Boolean )
|
||||
{
|
||||
stateTable.put( propertyName, value );
|
||||
}
|
||||
else
|
||||
{
|
||||
stateTable.put( propertyName, value.toString() );
|
||||
}
|
||||
}
|
||||
table.put( "state", stateTable );
|
||||
// TODO: NBT data?
|
||||
return table;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( ILuaContext context, int method, Object[] arguments ) throws LuaException, InterruptedException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// exec
|
||||
if( arguments.length < 1 || !(arguments[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
final String command = (String)arguments[0];
|
||||
return context.executeMainThreadTask( new ILuaTask()
|
||||
{
|
||||
@Override
|
||||
public Object[] execute() throws LuaException
|
||||
{
|
||||
return doCommand( command );
|
||||
}
|
||||
} );
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// execAsync
|
||||
if( arguments.length < 1 || !(arguments[0] instanceof String) )
|
||||
{
|
||||
throw new LuaException( "Expected string" );
|
||||
}
|
||||
final String command = (String)arguments[0];
|
||||
long taskID = context.issueMainThreadTask( new ILuaTask()
|
||||
{
|
||||
@Override
|
||||
public Object[] execute() throws LuaException
|
||||
{
|
||||
return doCommand( command );
|
||||
}
|
||||
} );
|
||||
return new Object[] { taskID };
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// list
|
||||
return context.executeMainThreadTask( new ILuaTask()
|
||||
{
|
||||
@Override
|
||||
public Object[] execute() throws LuaException
|
||||
{
|
||||
int i = 1;
|
||||
Map<Object, Object> result = new HashMap<Object, Object>();
|
||||
MinecraftServer server = MinecraftServer.getServer();
|
||||
if( server != null )
|
||||
{
|
||||
ICommandManager commandManager = server.getCommandManager();
|
||||
ICommandSender commmandSender = m_computer.getCommandSender();
|
||||
Map commands = commandManager.getCommands();
|
||||
for( Object entryObject : commands.entrySet() )
|
||||
{
|
||||
Map.Entry entry = (Map.Entry)entryObject;
|
||||
String name = (String)entry.getKey();
|
||||
ICommand command = (ICommand)entry.getValue();
|
||||
try
|
||||
{
|
||||
if( command.canCommandSenderUseCommand( commmandSender ) )
|
||||
{
|
||||
result.put( i++, name );
|
||||
}
|
||||
}
|
||||
catch( Throwable t )
|
||||
{
|
||||
// Ignore buggy command
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Object[]{ result };
|
||||
}
|
||||
} );
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
// getBlockPosition
|
||||
// This is probably safe to do on the Lua thread. Probably.
|
||||
BlockPos pos = m_computer.getPos();
|
||||
return new Object[] { pos.getX(), pos.getY(), pos.getZ() };
|
||||
}
|
||||
case 4:
|
||||
{
|
||||
// getBlockInfos
|
||||
if( arguments.length < 6 ||
|
||||
!(arguments[0] instanceof Number) ||
|
||||
!(arguments[1] instanceof Number) ||
|
||||
!(arguments[2] instanceof Number) ||
|
||||
!(arguments[3] instanceof Number) ||
|
||||
!(arguments[4] instanceof Number) ||
|
||||
!(arguments[5] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected number, number, number, number, number, number" );
|
||||
}
|
||||
final int minx = ((Number)arguments[0]).intValue();
|
||||
final int miny = ((Number)arguments[1]).intValue();
|
||||
final int minz = ((Number)arguments[2]).intValue();
|
||||
final int maxx = ((Number)arguments[3]).intValue();
|
||||
final int maxy = ((Number)arguments[4]).intValue();
|
||||
final int maxz = ((Number)arguments[5]).intValue();
|
||||
return context.executeMainThreadTask( new ILuaTask()
|
||||
{
|
||||
@Override
|
||||
public Object[] execute() throws LuaException
|
||||
{
|
||||
// Get the details of the block
|
||||
World world = m_computer.getWorld();
|
||||
BlockPos min = new BlockPos(
|
||||
Math.min( minx, maxx ),
|
||||
Math.min( miny, maxy ),
|
||||
Math.min( minz, maxz )
|
||||
);
|
||||
BlockPos max = new BlockPos(
|
||||
Math.max( minx, maxx ),
|
||||
Math.max( miny, maxy ),
|
||||
Math.max( minz, maxz )
|
||||
);
|
||||
if( !WorldUtil.isBlockInWorld( world, min ) || !WorldUtil.isBlockInWorld( world, max ) )
|
||||
{
|
||||
throw new LuaException( "Co-ordinates out or range" );
|
||||
}
|
||||
if( ( max.getX() - min.getX() + 1 ) * ( max.getY() - min.getY() + 1 ) * ( max.getZ() - min.getZ() + 1 ) > 4096 )
|
||||
{
|
||||
throw new LuaException( "Too many blocks" );
|
||||
}
|
||||
int i=1;
|
||||
Map<Object, Object> results = new HashMap<Object, Object>();
|
||||
for( int y=min.getY(); y<= max.getY(); ++y )
|
||||
{
|
||||
for( int z = min.getZ(); z <= max.getZ(); ++z )
|
||||
{
|
||||
for( int x = min.getX(); x <= max.getX(); ++x )
|
||||
{
|
||||
BlockPos pos = new BlockPos( x, y, z );
|
||||
results.put( i++, getBlockInfo( world, pos ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Object[]{ results };
|
||||
}
|
||||
} );
|
||||
}
|
||||
case 5:
|
||||
{
|
||||
// getBlockInfo
|
||||
if( arguments.length < 3 ||
|
||||
!(arguments[0] instanceof Number) ||
|
||||
!(arguments[1] instanceof Number) ||
|
||||
!(arguments[2] instanceof Number) )
|
||||
{
|
||||
throw new LuaException( "Expected number, number, number" );
|
||||
}
|
||||
final int x = ((Number)arguments[0]).intValue();
|
||||
final int y = ((Number)arguments[1]).intValue();
|
||||
final int z = ((Number)arguments[2]).intValue();
|
||||
return context.executeMainThreadTask( new ILuaTask()
|
||||
{
|
||||
@Override
|
||||
public Object[] execute() throws LuaException
|
||||
{
|
||||
// Get the details of the block
|
||||
World world = m_computer.getWorld();
|
||||
BlockPos position = new BlockPos( x, y, z );
|
||||
if( WorldUtil.isBlockInWorld( world, position ) )
|
||||
{
|
||||
return new Object[]{ getBlockInfo( world, position ) };
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new LuaException( "co-ordinates out or range" );
|
||||
}
|
||||
}
|
||||
} );
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.computer.blocks;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.shared.computer.core.ComputerFamily;
|
||||
import dan200.computercraft.shared.computer.core.IComputer;
|
||||
import dan200.computercraft.shared.peripheral.common.TilePeripheralBase;
|
||||
import dan200.computercraft.shared.util.DirectionUtil;
|
||||
import net.minecraft.block.material.Material;
|
||||
import net.minecraft.block.properties.IProperty;
|
||||
import net.minecraft.block.properties.PropertyDirection;
|
||||
import net.minecraft.block.properties.PropertyEnum;
|
||||
import net.minecraft.block.state.BlockState;
|
||||
import net.minecraft.block.state.IBlockState;
|
||||
import net.minecraft.entity.EntityLivingBase;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.world.IBlockAccess;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
public class BlockCommandComputer extends BlockComputerBase
|
||||
{
|
||||
// Statics
|
||||
|
||||
public static class Properties
|
||||
{
|
||||
public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL);
|
||||
public static final PropertyEnum STATE = PropertyEnum.create("state", ComputerState.class);
|
||||
}
|
||||
|
||||
// Members
|
||||
|
||||
public BlockCommandComputer()
|
||||
{
|
||||
super( Material.iron );
|
||||
setBlockUnbreakable();
|
||||
setResistance( 6000000.0F );
|
||||
setUnlocalizedName( "computercraft:command_computer" );
|
||||
setCreativeTab( ComputerCraft.mainCreativeTab );
|
||||
setDefaultState( this.blockState.getBaseState()
|
||||
.withProperty( Properties.FACING, EnumFacing.NORTH )
|
||||
.withProperty( Properties.STATE, ComputerState.Off )
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BlockState createBlockState()
|
||||
{
|
||||
return new BlockState(this, new IProperty[] {
|
||||
Properties.FACING,
|
||||
Properties.STATE
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBlockState getStateFromMeta( int meta )
|
||||
{
|
||||
EnumFacing dir = EnumFacing.getFront( meta & 0x7 );
|
||||
if( dir.getAxis() == EnumFacing.Axis.Y )
|
||||
{
|
||||
dir = EnumFacing.NORTH;
|
||||
}
|
||||
return getDefaultState().withProperty( Properties.FACING, dir );
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMetaFromState( IBlockState state )
|
||||
{
|
||||
return ((EnumFacing)state.getValue( Properties.FACING )).getIndex();
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBlockState getActualState( IBlockState state, IBlockAccess world, BlockPos pos )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof IComputerTile )
|
||||
{
|
||||
IComputer computer = ((IComputerTile)tile).getComputer();
|
||||
if( computer != null && computer.isOn() )
|
||||
{
|
||||
if( computer.isCursorDisplayed() )
|
||||
{
|
||||
return state.withProperty( Properties.STATE, ComputerState.Blinking );
|
||||
}
|
||||
else
|
||||
{
|
||||
return state.withProperty( Properties.STATE, ComputerState.On );
|
||||
}
|
||||
}
|
||||
}
|
||||
return state.withProperty( Properties.STATE, ComputerState.Off );
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IBlockState getDefaultBlockState( ComputerFamily family, EnumFacing placedSide )
|
||||
{
|
||||
if( placedSide.getAxis() != EnumFacing.Axis.Y )
|
||||
{
|
||||
return getDefaultState().withProperty( Properties.FACING, placedSide );
|
||||
}
|
||||
else
|
||||
{
|
||||
return getDefaultState();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ComputerFamily getFamily( int damage )
|
||||
{
|
||||
return ComputerFamily.Command;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ComputerFamily getFamily( IBlockState state )
|
||||
{
|
||||
return ComputerFamily.Command;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected TileComputer createTile( ComputerFamily family )
|
||||
{
|
||||
return new TileCommandComputer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBlockPlacedBy( World world, BlockPos pos, IBlockState state, EntityLivingBase player, ItemStack itemstack )
|
||||
{
|
||||
// Not sure why this is necessary
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileCommandComputer )
|
||||
{
|
||||
tile.setWorldObj( world ); // Not sure why this is necessary
|
||||
tile.setPos( pos ); // Not sure why this is necessary
|
||||
}
|
||||
|
||||
// Set direction
|
||||
EnumFacing dir = DirectionUtil.fromEntityRot( player );
|
||||
setDirection( world, pos, dir );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.computer.blocks;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.shared.computer.core.ComputerFamily;
|
||||
import dan200.computercraft.shared.computer.core.IComputer;
|
||||
import dan200.computercraft.shared.computer.items.ItemComputer;
|
||||
import dan200.computercraft.shared.util.DirectionUtil;
|
||||
import net.minecraft.block.material.Material;
|
||||
import net.minecraft.block.properties.IProperty;
|
||||
import net.minecraft.block.properties.PropertyBool;
|
||||
import net.minecraft.block.properties.PropertyDirection;
|
||||
import net.minecraft.block.properties.PropertyEnum;
|
||||
import net.minecraft.block.state.BlockState;
|
||||
import net.minecraft.block.state.IBlockState;
|
||||
import net.minecraft.entity.EntityLivingBase;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.world.IBlockAccess;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
public class BlockComputer extends BlockComputerBase
|
||||
{
|
||||
// Statics
|
||||
public static class Properties
|
||||
{
|
||||
public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL);
|
||||
public static final PropertyBool ADVANCED = PropertyBool.create("advanced");
|
||||
public static final PropertyEnum STATE = PropertyEnum.create("state", ComputerState.class);
|
||||
}
|
||||
|
||||
// Members
|
||||
|
||||
public BlockComputer()
|
||||
{
|
||||
super( Material.rock );
|
||||
setHardness( 2.0f );
|
||||
setUnlocalizedName( "computercraft:computer" );
|
||||
setCreativeTab( ComputerCraft.mainCreativeTab );
|
||||
setDefaultState( this.blockState.getBaseState()
|
||||
.withProperty( Properties.FACING, EnumFacing.NORTH )
|
||||
.withProperty( Properties.ADVANCED, false )
|
||||
.withProperty( Properties.STATE, ComputerState.Off )
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BlockState createBlockState()
|
||||
{
|
||||
return new BlockState(this, new IProperty[] {
|
||||
Properties.FACING,
|
||||
Properties.ADVANCED,
|
||||
Properties.STATE
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBlockState getStateFromMeta( int meta )
|
||||
{
|
||||
EnumFacing dir = EnumFacing.getFront( meta & 0x7 );
|
||||
if( dir.getAxis() == EnumFacing.Axis.Y )
|
||||
{
|
||||
dir = EnumFacing.NORTH;
|
||||
}
|
||||
|
||||
IBlockState state = getDefaultState().withProperty( Properties.FACING, dir );
|
||||
if( meta > 8 )
|
||||
{
|
||||
state = state.withProperty( Properties.ADVANCED, true );
|
||||
}
|
||||
else
|
||||
{
|
||||
state = state.withProperty( Properties.ADVANCED, false );
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMetaFromState( IBlockState state )
|
||||
{
|
||||
int meta = ((EnumFacing)state.getValue( Properties.FACING )).getIndex();
|
||||
if( (Boolean)state.getValue( Properties.ADVANCED ) )
|
||||
{
|
||||
meta += 8;
|
||||
}
|
||||
return meta;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IBlockState getDefaultBlockState( ComputerFamily family, EnumFacing placedSide )
|
||||
{
|
||||
IBlockState state = getDefaultState();
|
||||
if( placedSide.getAxis() != EnumFacing.Axis.Y )
|
||||
{
|
||||
state = state.withProperty( Properties.FACING, placedSide );
|
||||
}
|
||||
|
||||
switch( family )
|
||||
{
|
||||
case Normal:
|
||||
default:
|
||||
{
|
||||
return state.withProperty( Properties.ADVANCED, false );
|
||||
}
|
||||
case Advanced:
|
||||
{
|
||||
return state.withProperty( Properties.ADVANCED, true );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBlockState getActualState( IBlockState state, IBlockAccess world, BlockPos pos )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof IComputerTile )
|
||||
{
|
||||
IComputer computer = ((IComputerTile)tile).getComputer();
|
||||
if( computer != null && computer.isOn() )
|
||||
{
|
||||
if( computer.isCursorDisplayed() )
|
||||
{
|
||||
return state.withProperty( Properties.STATE, ComputerState.Blinking );
|
||||
}
|
||||
else
|
||||
{
|
||||
return state.withProperty( Properties.STATE, ComputerState.On );
|
||||
}
|
||||
}
|
||||
}
|
||||
return state.withProperty( Properties.STATE, ComputerState.Off );
|
||||
}
|
||||
|
||||
@Override
|
||||
public ComputerFamily getFamily( int damage )
|
||||
{
|
||||
return ((ItemComputer) Item.getItemFromBlock(this)).getFamily( damage );
|
||||
}
|
||||
|
||||
@Override
|
||||
public ComputerFamily getFamily( IBlockState state )
|
||||
{
|
||||
if( (Boolean)state.getValue( Properties.ADVANCED ) ) {
|
||||
return ComputerFamily.Advanced;
|
||||
} else {
|
||||
return ComputerFamily.Normal;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected TileComputer createTile( ComputerFamily family )
|
||||
{
|
||||
return new TileComputer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBlockPlacedBy( World world, BlockPos pos, IBlockState state, EntityLivingBase player, ItemStack stack )
|
||||
{
|
||||
// Not sure why this is necessary
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileComputer )
|
||||
{
|
||||
tile.setWorldObj( world ); // Not sure why this is necessary
|
||||
tile.setPos( pos ); // Not sure why this is necessary
|
||||
}
|
||||
|
||||
// Set direction
|
||||
EnumFacing dir = DirectionUtil.fromEntityRot( player );
|
||||
setDirection( world, pos, dir );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.computer.blocks;
|
||||
|
||||
import dan200.computercraft.shared.common.BlockDirectional;
|
||||
import dan200.computercraft.shared.computer.core.ComputerFamily;
|
||||
import dan200.computercraft.shared.computer.items.ItemComputerBase;
|
||||
import net.minecraft.block.material.Material;
|
||||
import net.minecraft.block.state.IBlockState;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.world.IBlockAccess;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
public abstract class BlockComputerBase extends BlockDirectional
|
||||
{
|
||||
public BlockComputerBase( Material material )
|
||||
{
|
||||
super( material );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBlockAdded( World world, BlockPos pos, IBlockState state )
|
||||
{
|
||||
super.onBlockAdded( world, pos, state );
|
||||
updateInput( world, pos );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDirection( World world, BlockPos pos, EnumFacing dir )
|
||||
{
|
||||
super.setDirection( world, pos, dir );
|
||||
updateInput( world, pos );
|
||||
}
|
||||
|
||||
protected abstract IBlockState getDefaultBlockState( ComputerFamily family, EnumFacing placedSide );
|
||||
protected abstract ComputerFamily getFamily( int damage );
|
||||
protected abstract ComputerFamily getFamily( IBlockState state );
|
||||
protected abstract TileComputerBase createTile( ComputerFamily family );
|
||||
|
||||
@Override
|
||||
protected final IBlockState getDefaultBlockState( int damage, EnumFacing placedSide )
|
||||
{
|
||||
ItemComputerBase item = (ItemComputerBase)Item.getItemFromBlock( this );
|
||||
return getDefaultBlockState( item.getFamily( damage ), placedSide );
|
||||
}
|
||||
|
||||
@Override
|
||||
public final TileComputerBase createTile( IBlockState state )
|
||||
{
|
||||
return createTile( getFamily( state ) );
|
||||
}
|
||||
|
||||
@Override
|
||||
public final TileComputerBase createTile( int damage )
|
||||
{
|
||||
return createTile( getFamily( damage ) );
|
||||
}
|
||||
|
||||
public final ComputerFamily getFamily( IBlockAccess world, BlockPos pos )
|
||||
{
|
||||
return getFamily( world.getBlockState( pos ) );
|
||||
}
|
||||
|
||||
protected void updateInput( IBlockAccess world, BlockPos pos )
|
||||
{
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( tile != null && tile instanceof TileComputerBase )
|
||||
{
|
||||
TileComputerBase computer = (TileComputerBase)tile;
|
||||
computer.updateInput();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.computer.blocks;
|
||||
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.api.peripheral.IComputerAccess;
|
||||
import dan200.computercraft.api.peripheral.IPeripheral;
|
||||
import dan200.computercraft.shared.computer.core.ServerComputer;
|
||||
|
||||
public class ComputerPeripheral
|
||||
implements IPeripheral
|
||||
{
|
||||
private final String m_type;
|
||||
private final ServerComputer m_computer;
|
||||
|
||||
public ComputerPeripheral( String type, ServerComputer computer )
|
||||
{
|
||||
m_type = type;
|
||||
m_computer = computer;
|
||||
}
|
||||
|
||||
// IPeripheral implementation
|
||||
|
||||
@Override
|
||||
public String getType()
|
||||
{
|
||||
return m_type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getMethodNames()
|
||||
{
|
||||
return new String[] {
|
||||
"turnOn",
|
||||
"shutdown",
|
||||
"reboot",
|
||||
"getID",
|
||||
"isOn",
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] callMethod( IComputerAccess computer, ILuaContext context, int method, Object[] arguments ) throws LuaException
|
||||
{
|
||||
switch( method )
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
// turnOn
|
||||
m_computer.turnOn();
|
||||
return null;
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// shutdown
|
||||
m_computer.shutdown();
|
||||
return null;
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// reboot
|
||||
m_computer.reboot();
|
||||
return null;
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
// getID
|
||||
return new Object[] {
|
||||
m_computer.assignID()
|
||||
};
|
||||
}
|
||||
case 4:
|
||||
{
|
||||
// isOn
|
||||
return new Object[] { m_computer.isOn() };
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void attach( IComputerAccess computer )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void detach( IComputerAccess computer )
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals( IPeripheral other )
|
||||
{
|
||||
return (other != null && other.getClass() == this.getClass());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.computer.blocks;
|
||||
|
||||
import net.minecraft.util.IStringSerializable;
|
||||
|
||||
public enum ComputerState implements IStringSerializable
|
||||
{
|
||||
Off( "off" ),
|
||||
On( "on" ),
|
||||
Blinking( "blinking" );
|
||||
|
||||
private String m_name;
|
||||
|
||||
private ComputerState( String name )
|
||||
{
|
||||
m_name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName()
|
||||
{
|
||||
return m_name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return getName();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.computer.blocks;
|
||||
|
||||
import dan200.computercraft.shared.common.ITerminalTile;
|
||||
import dan200.computercraft.shared.computer.core.ComputerFamily;
|
||||
import dan200.computercraft.shared.computer.core.IComputer;
|
||||
|
||||
public interface IComputerTile extends ITerminalTile
|
||||
{
|
||||
public void setComputerID( int id );
|
||||
public void setLabel( String label );
|
||||
public IComputer getComputer();
|
||||
public IComputer createComputer();
|
||||
public ComputerFamily getFamily();
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.computer.blocks;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.shared.computer.apis.CommandAPI;
|
||||
import dan200.computercraft.shared.computer.core.IComputer;
|
||||
import dan200.computercraft.shared.computer.core.ServerComputer;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import net.minecraft.block.state.IBlockState;
|
||||
import net.minecraft.command.server.CommandBlockLogic;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.*;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class TileCommandComputer extends TileComputer
|
||||
{
|
||||
public class CommandSender extends CommandBlockLogic
|
||||
{
|
||||
private Map<Integer, String> m_outputTable;
|
||||
|
||||
public CommandSender()
|
||||
{
|
||||
m_outputTable = new HashMap<Integer, String>();
|
||||
}
|
||||
|
||||
public void clearOutput()
|
||||
{
|
||||
m_outputTable.clear();
|
||||
}
|
||||
|
||||
public Map<Integer, String> getOutput()
|
||||
{
|
||||
return m_outputTable;
|
||||
}
|
||||
|
||||
public Map<Integer, String> copyOutput()
|
||||
{
|
||||
return new HashMap<Integer, String>( m_outputTable );
|
||||
}
|
||||
|
||||
// ICommandSender
|
||||
|
||||
@Override
|
||||
public IChatComponent getDisplayName()
|
||||
{
|
||||
IComputer computer = TileCommandComputer.this.getComputer();
|
||||
if( computer != null )
|
||||
{
|
||||
String label = computer.getLabel();
|
||||
if( label != null )
|
||||
{
|
||||
return new ChatComponentText( computer.getLabel() );
|
||||
}
|
||||
}
|
||||
return new ChatComponentText( "@" );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addChatMessage( IChatComponent chatComponent )
|
||||
{
|
||||
m_outputTable.put( m_outputTable.size() + 1, chatComponent.getUnformattedText() );
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canCommandSenderUseCommand( int level, String command )
|
||||
{
|
||||
return level <= 2;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockPos getPosition()
|
||||
{
|
||||
return TileCommandComputer.this.getPos();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vec3 getPositionVector()
|
||||
{
|
||||
BlockPos pos = getPosition();
|
||||
return new Vec3( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 );
|
||||
}
|
||||
|
||||
@Override
|
||||
public World getEntityWorld()
|
||||
{
|
||||
return TileCommandComputer.this.worldObj;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Entity getCommandSenderEntity()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// CommandBlockLogic members intentionally left empty
|
||||
// The only reason we extend it at all is so that "gameRule commandBlockOutput" applies to us
|
||||
|
||||
@Override
|
||||
public void updateCommand()
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public int func_145751_f()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void func_145757_a( ByteBuf p_145757_1_ )
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private CommandSender m_commandSender;
|
||||
|
||||
public TileCommandComputer()
|
||||
{
|
||||
m_commandSender = new CommandSender();
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumFacing getDirection()
|
||||
{
|
||||
IBlockState state = getBlockState();
|
||||
return (EnumFacing)state.getValue( BlockCommandComputer.Properties.FACING );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDirection( EnumFacing dir )
|
||||
{
|
||||
if( dir.getAxis() == EnumFacing.Axis.Y )
|
||||
{
|
||||
dir = EnumFacing.NORTH;
|
||||
}
|
||||
setBlockState( getBlockState().withProperty( BlockCommandComputer.Properties.FACING, dir ) );
|
||||
updateInput();
|
||||
}
|
||||
|
||||
public CommandSender getCommandSender()
|
||||
{
|
||||
return m_commandSender;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ServerComputer createComputer( int instanceID, int id )
|
||||
{
|
||||
ServerComputer computer = super.createComputer( instanceID, id );
|
||||
computer.addAPI( new CommandAPI( this ) );
|
||||
return computer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUsable( EntityPlayer player, boolean ignoreRange )
|
||||
{
|
||||
MinecraftServer server = MinecraftServer.getServer();
|
||||
if( server == null || !server.isCommandBlockEnabled() )
|
||||
{
|
||||
player.addChatMessage( new ChatComponentTranslation( "advMode.notEnabled" ) );
|
||||
return false;
|
||||
}
|
||||
else if( ComputerCraft.canPlayerUseCommands( player ) && player.capabilities.isCreativeMode )
|
||||
{
|
||||
return super.isUsable( player, ignoreRange );
|
||||
}
|
||||
else
|
||||
{
|
||||
player.addChatMessage( new ChatComponentTranslation( "advMode.notAllowed" ) );
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.computer.blocks;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.shared.computer.core.ComputerFamily;
|
||||
import dan200.computercraft.shared.computer.core.IComputer;
|
||||
import dan200.computercraft.shared.computer.core.ServerComputer;
|
||||
import dan200.computercraft.shared.computer.items.ComputerItemFactory;
|
||||
import net.minecraft.block.state.IBlockState;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TileComputer extends TileComputerBase
|
||||
{
|
||||
// Statics
|
||||
|
||||
// Members
|
||||
|
||||
public TileComputer()
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ServerComputer createComputer( int instanceID, int id )
|
||||
{
|
||||
ComputerFamily family = getFamily();
|
||||
ServerComputer computer = new ServerComputer(
|
||||
worldObj,
|
||||
id,
|
||||
m_label,
|
||||
instanceID,
|
||||
family,
|
||||
ComputerCraft.terminalWidth_computer,
|
||||
ComputerCraft.terminalHeight_computer
|
||||
);
|
||||
computer.setPosition( getPos() );
|
||||
return computer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getDroppedItems( List<ItemStack> drops, int fortune, boolean creative, boolean silkTouch )
|
||||
{
|
||||
IComputer computer = getComputer();
|
||||
if( !creative || (computer != null && computer.getLabel() != null) )
|
||||
{
|
||||
drops.add( ComputerItemFactory.create( this ) );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getPickedItem()
|
||||
{
|
||||
return ComputerItemFactory.create( this );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void openGUI( EntityPlayer player )
|
||||
{
|
||||
ComputerCraft.openComputerGUI( player, this );
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void readDescription( NBTTagCompound nbttagcompound )
|
||||
{
|
||||
super.readDescription( nbttagcompound );
|
||||
updateBlock();
|
||||
}
|
||||
|
||||
public boolean isUseableByPlayer( EntityPlayer player )
|
||||
{
|
||||
return isUsable( player, false );
|
||||
}
|
||||
|
||||
// IDirectionalTile
|
||||
|
||||
@Override
|
||||
public EnumFacing getDirection()
|
||||
{
|
||||
IBlockState state = getBlockState();
|
||||
return (EnumFacing)state.getValue( BlockComputer.Properties.FACING );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDirection( EnumFacing dir )
|
||||
{
|
||||
if( dir.getAxis() == EnumFacing.Axis.Y )
|
||||
{
|
||||
dir = EnumFacing.NORTH;
|
||||
}
|
||||
setBlockState( getBlockState().withProperty( BlockComputer.Properties.FACING, dir ) );
|
||||
updateInput();
|
||||
}
|
||||
|
||||
// For legacy reasons, computers invert the meaning of "left" and "right"
|
||||
private static final int[] s_remapSide = { 0, 1, 2, 3, 5, 4 };
|
||||
|
||||
@Override
|
||||
protected int remapLocalSide( int localSide )
|
||||
{
|
||||
return s_remapSide[ localSide ];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.computer.blocks;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.shared.common.IDirectionalTile;
|
||||
import dan200.computercraft.shared.common.ITerminal;
|
||||
import dan200.computercraft.shared.common.TileGeneric;
|
||||
import dan200.computercraft.shared.computer.core.ClientComputer;
|
||||
import dan200.computercraft.shared.computer.core.ComputerFamily;
|
||||
import dan200.computercraft.shared.computer.core.IComputer;
|
||||
import dan200.computercraft.shared.computer.core.ServerComputer;
|
||||
import dan200.computercraft.shared.util.DirectionUtil;
|
||||
import dan200.computercraft.shared.util.PeripheralUtil;
|
||||
import dan200.computercraft.shared.util.RedstoneUtil;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.init.Items;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.util.ITickable;
|
||||
import net.minecraft.util.BlockPos;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
|
||||
public abstract class TileComputerBase extends TileGeneric
|
||||
implements IComputerTile, IDirectionalTile, ITickable
|
||||
{
|
||||
protected int m_instanceID;
|
||||
protected int m_computerID;
|
||||
protected String m_label;
|
||||
protected boolean m_on;
|
||||
protected boolean m_startOn;
|
||||
|
||||
protected TileComputerBase()
|
||||
{
|
||||
m_instanceID = -1;
|
||||
m_computerID = -1;
|
||||
m_label = null;
|
||||
m_on = false;
|
||||
m_startOn = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockComputerBase getBlock()
|
||||
{
|
||||
Block block = super.getBlock();
|
||||
if( block != null && block instanceof BlockComputerBase )
|
||||
{
|
||||
return (BlockComputerBase)block;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected void unload()
|
||||
{
|
||||
if( m_instanceID >= 0 )
|
||||
{
|
||||
if( !worldObj.isRemote )
|
||||
{
|
||||
ComputerCraft.serverComputerRegistry.remove( m_instanceID );
|
||||
}
|
||||
m_instanceID = -1;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy()
|
||||
{
|
||||
unload();
|
||||
for( EnumFacing dir : EnumFacing.VALUES )
|
||||
{
|
||||
RedstoneUtil.propogateRedstoneOutput( worldObj, getPos(), dir );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onChunkUnload()
|
||||
{
|
||||
unload();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invalidate()
|
||||
{
|
||||
unload();
|
||||
super.invalidate();
|
||||
}
|
||||
|
||||
public abstract void openGUI( EntityPlayer player );
|
||||
|
||||
protected boolean canNameWithTag( EntityPlayer player )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
protected boolean onDefaultComputerInteract( EntityPlayer player )
|
||||
{
|
||||
if( !worldObj.isRemote )
|
||||
{
|
||||
if( isUsable( player, false ) )
|
||||
{
|
||||
createServerComputer().turnOn();
|
||||
openGUI( player );
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onActivate( EntityPlayer player, EnumFacing side, float hitX, float hitY, float hitZ )
|
||||
{
|
||||
ItemStack currentItem = player.getCurrentEquippedItem();
|
||||
if( currentItem != null && currentItem.getItem() == Items.name_tag && canNameWithTag( player ) )
|
||||
{
|
||||
// Label to rename computer
|
||||
if( !worldObj.isRemote )
|
||||
{
|
||||
if( currentItem.hasDisplayName() )
|
||||
{
|
||||
setLabel( currentItem.getDisplayName() );
|
||||
}
|
||||
else
|
||||
{
|
||||
setLabel( null );
|
||||
}
|
||||
currentItem.stackSize--;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
else if( !player.isSneaking() )
|
||||
{
|
||||
// Regular right click to activate computer
|
||||
return onDefaultComputerInteract( player );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getRedstoneConnectivity( EnumFacing side )
|
||||
{
|
||||
int localDir = remapLocalSide( DirectionUtil.toLocal( this, side ) );
|
||||
return !isRedstoneBlockedOnSide( localDir );
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRedstoneOutput( EnumFacing side )
|
||||
{
|
||||
int localDir = remapLocalSide( DirectionUtil.toLocal( this, side ) );
|
||||
if( !isRedstoneBlockedOnSide( localDir ) )
|
||||
{
|
||||
if( worldObj != null && !worldObj.isRemote )
|
||||
{
|
||||
ServerComputer computer = getServerComputer();
|
||||
if( computer != null )
|
||||
{
|
||||
return computer.getRedstoneOutput( localDir );
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getBundledRedstoneConnectivity( EnumFacing side )
|
||||
{
|
||||
int localDir = remapLocalSide( DirectionUtil.toLocal( this, side ) );
|
||||
return !isRedstoneBlockedOnSide( localDir );
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBundledRedstoneOutput( EnumFacing side )
|
||||
{
|
||||
int localDir = remapLocalSide( DirectionUtil.toLocal( this, side ) );
|
||||
if( !isRedstoneBlockedOnSide( localDir ) )
|
||||
{
|
||||
if( !worldObj.isRemote )
|
||||
{
|
||||
ServerComputer computer = getServerComputer();
|
||||
if( computer != null )
|
||||
{
|
||||
return computer.getBundledRedstoneOutput( localDir );
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNeighbourChange()
|
||||
{
|
||||
updateInput();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update()
|
||||
{
|
||||
if( !worldObj.isRemote )
|
||||
{
|
||||
ServerComputer computer = createServerComputer();
|
||||
if( computer != null )
|
||||
{
|
||||
if( m_startOn )
|
||||
{
|
||||
computer.turnOn();
|
||||
m_startOn = false;
|
||||
}
|
||||
computer.keepAlive();
|
||||
if( computer.hasOutputChanged() )
|
||||
{
|
||||
updateOutput();
|
||||
}
|
||||
m_computerID = computer.getID();
|
||||
m_label = computer.getLabel();
|
||||
m_on = computer.isOn();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ClientComputer computer = createClientComputer();
|
||||
if( computer != null )
|
||||
{
|
||||
if( computer.hasOutputChanged() )
|
||||
{
|
||||
updateBlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToNBT( NBTTagCompound nbttagcompound )
|
||||
{
|
||||
super.writeToNBT( nbttagcompound );
|
||||
|
||||
// Save ID, label and power state
|
||||
if( m_computerID >= 0 )
|
||||
{
|
||||
nbttagcompound.setInteger( "computerID", m_computerID );
|
||||
}
|
||||
if( m_label != null )
|
||||
{
|
||||
nbttagcompound.setString( "label", m_label );
|
||||
}
|
||||
nbttagcompound.setBoolean( "on", m_on );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readFromNBT( NBTTagCompound nbttagcompound )
|
||||
{
|
||||
super.readFromNBT( nbttagcompound );
|
||||
|
||||
// Load ID
|
||||
int id = -1;
|
||||
if( nbttagcompound.hasKey( "computerID" ) )
|
||||
{
|
||||
// Post-1.6 computers
|
||||
id = nbttagcompound.getInteger( "computerID" );
|
||||
}
|
||||
else if( nbttagcompound.hasKey( "userDir" ) )
|
||||
{
|
||||
// Pre-1.6 computers
|
||||
String userDir = nbttagcompound.getString( "userDir" );
|
||||
try
|
||||
{
|
||||
id = Integer.parseInt( userDir );
|
||||
}
|
||||
catch( NumberFormatException e )
|
||||
{
|
||||
// Ignore badly formatted data
|
||||
}
|
||||
}
|
||||
m_computerID = id;
|
||||
|
||||
// Load label
|
||||
if( nbttagcompound.hasKey( "label" ) )
|
||||
{
|
||||
m_label = nbttagcompound.getString( "label" );
|
||||
}
|
||||
else
|
||||
{
|
||||
m_label = null;
|
||||
}
|
||||
|
||||
// Load power state
|
||||
m_startOn = nbttagcompound.getBoolean( "on" );
|
||||
m_on = m_startOn;
|
||||
}
|
||||
|
||||
protected boolean isPeripheralBlockedOnSide( int localSide )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
protected boolean isRedstoneBlockedOnSide( int localSide )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
protected int remapLocalSide( int localSide )
|
||||
{
|
||||
return localSide;
|
||||
}
|
||||
|
||||
public void updateInput()
|
||||
{
|
||||
if( worldObj == null || worldObj.isRemote )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Update redstone and peripherals
|
||||
ServerComputer computer = getServerComputer();
|
||||
if( computer != null )
|
||||
{
|
||||
BlockPos pos = computer.getPosition();
|
||||
for( EnumFacing dir : EnumFacing.VALUES )
|
||||
{
|
||||
BlockPos offset = pos.offset( dir );
|
||||
EnumFacing offsetSide = dir.getOpposite();
|
||||
int localDir = remapLocalSide( DirectionUtil.toLocal( this, dir ) );
|
||||
if( !isRedstoneBlockedOnSide( localDir ) )
|
||||
{
|
||||
computer.setRedstoneInput( localDir, RedstoneUtil.getRedstoneOutput( worldObj, offset, offsetSide ) );
|
||||
computer.setBundledRedstoneInput( localDir, RedstoneUtil.getBundledRedstoneOutput( worldObj, offset, offsetSide ) );
|
||||
}
|
||||
if( !isPeripheralBlockedOnSide( localDir ) )
|
||||
{
|
||||
computer.setPeripheral( localDir, PeripheralUtil.getPeripheral( worldObj, offset, offsetSide ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void updateOutput()
|
||||
{
|
||||
// Update redstone
|
||||
updateBlock();
|
||||
for( EnumFacing dir : EnumFacing.VALUES )
|
||||
{
|
||||
RedstoneUtil.propogateRedstoneOutput( worldObj, getPos(), dir );
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract ServerComputer createComputer( int instanceID, int id );
|
||||
|
||||
// ITerminalTile
|
||||
|
||||
@Override
|
||||
public ITerminal getTerminal()
|
||||
{
|
||||
return getComputer();
|
||||
}
|
||||
|
||||
// IComputerTile
|
||||
|
||||
@Override
|
||||
public void setComputerID( int id )
|
||||
{
|
||||
if( !worldObj.isRemote && m_computerID != id )
|
||||
{
|
||||
m_computerID = id;
|
||||
ServerComputer computer = getServerComputer();
|
||||
if( computer != null )
|
||||
{
|
||||
computer.setID( m_computerID );
|
||||
}
|
||||
markDirty();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLabel( String label )
|
||||
{
|
||||
if( !worldObj.isRemote )
|
||||
{
|
||||
createServerComputer().setLabel( label );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IComputer createComputer()
|
||||
{
|
||||
if( worldObj.isRemote )
|
||||
{
|
||||
return createClientComputer();
|
||||
}
|
||||
else
|
||||
{
|
||||
return createServerComputer();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IComputer getComputer()
|
||||
{
|
||||
if( worldObj.isRemote )
|
||||
{
|
||||
return getClientComputer();
|
||||
}
|
||||
else
|
||||
{
|
||||
return getServerComputer();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ComputerFamily getFamily()
|
||||
{
|
||||
BlockComputerBase block = getBlock();
|
||||
if( block != null )
|
||||
{
|
||||
return block.getFamily( worldObj, getPos() );
|
||||
}
|
||||
return ComputerFamily.Normal;
|
||||
}
|
||||
|
||||
public ServerComputer createServerComputer()
|
||||
{
|
||||
if( !worldObj.isRemote )
|
||||
{
|
||||
boolean changed = false;
|
||||
if( m_instanceID < 0 )
|
||||
{
|
||||
m_instanceID = ComputerCraft.serverComputerRegistry.getUnusedInstanceID();
|
||||
changed = true;
|
||||
}
|
||||
if( !ComputerCraft.serverComputerRegistry.contains( m_instanceID ) )
|
||||
{
|
||||
ServerComputer computer = createComputer( m_instanceID, m_computerID );
|
||||
ComputerCraft.serverComputerRegistry.add( m_instanceID, computer );
|
||||
changed = true;
|
||||
}
|
||||
if( changed )
|
||||
{
|
||||
updateBlock();
|
||||
updateInput();
|
||||
}
|
||||
return ComputerCraft.serverComputerRegistry.get( m_instanceID );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public ServerComputer getServerComputer()
|
||||
{
|
||||
if( !worldObj.isRemote )
|
||||
{
|
||||
return ComputerCraft.serverComputerRegistry.get( m_instanceID );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public ClientComputer createClientComputer()
|
||||
{
|
||||
if( worldObj.isRemote )
|
||||
{
|
||||
if( m_instanceID >= 0 )
|
||||
{
|
||||
if( !ComputerCraft.clientComputerRegistry.contains( m_instanceID ) )
|
||||
{
|
||||
ComputerCraft.clientComputerRegistry.add( m_instanceID, new ClientComputer( m_instanceID ) );
|
||||
}
|
||||
return ComputerCraft.clientComputerRegistry.get( m_instanceID );
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public ClientComputer getClientComputer()
|
||||
{
|
||||
if( worldObj.isRemote )
|
||||
{
|
||||
return ComputerCraft.clientComputerRegistry.get( m_instanceID );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Networking stuff
|
||||
|
||||
@Override
|
||||
public void writeDescription( NBTTagCompound nbttagcompound )
|
||||
{
|
||||
super.writeDescription( nbttagcompound );
|
||||
nbttagcompound.setInteger( "instanceID", createServerComputer().getInstanceID() );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readDescription( NBTTagCompound nbttagcompound )
|
||||
{
|
||||
super.readDescription( nbttagcompound );
|
||||
m_instanceID = nbttagcompound.getInteger( "instanceID" );
|
||||
}
|
||||
|
||||
protected void transferStateFrom( TileComputerBase copy )
|
||||
{
|
||||
if( copy.m_computerID != m_computerID || copy.m_instanceID != m_instanceID )
|
||||
{
|
||||
unload();
|
||||
m_instanceID = copy.m_instanceID;
|
||||
m_computerID = copy.m_computerID;
|
||||
m_label = copy.m_label;
|
||||
m_on = copy.m_on;
|
||||
m_startOn = copy.m_startOn;
|
||||
updateBlock();
|
||||
}
|
||||
copy.m_instanceID = -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.shared.computer.core;
|
||||
|
||||
import com.google.common.base.Objects;
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.shared.common.ClientTerminal;
|
||||
import dan200.computercraft.shared.network.ComputerCraftPacket;
|
||||
import dan200.computercraft.shared.network.INetworkedThing;
|
||||
import dan200.computercraft.shared.util.NBTUtil;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
|
||||
public class ClientComputer extends ClientTerminal
|
||||
implements IComputer, INetworkedThing
|
||||
{
|
||||
private final int m_instanceID;
|
||||
|
||||
private int m_computerID;
|
||||
private String m_label;
|
||||
private boolean m_on;
|
||||
private boolean m_blinking;
|
||||
private boolean m_changed;
|
||||
private NBTTagCompound m_userData;
|
||||
|
||||
private boolean m_changedLastFrame;
|
||||
|
||||
public ClientComputer( int instanceID )
|
||||
{
|
||||
super( false );
|
||||
m_instanceID = instanceID;
|
||||
|
||||
m_computerID = -1;
|
||||
m_label = null;
|
||||
m_on = false;
|
||||
m_blinking = false;
|
||||
m_changed = true;
|
||||
m_userData = null;
|
||||
m_changedLastFrame = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update()
|
||||
{
|
||||
super.update();
|
||||
m_changedLastFrame = m_changed;
|
||||
m_changed = false;
|
||||
}
|
||||
|
||||
public boolean hasOutputChanged()
|
||||
{
|
||||
return m_changedLastFrame;
|
||||
}
|
||||
|
||||
public NBTTagCompound getUserData()
|
||||
{
|
||||
return m_userData;
|
||||
}
|
||||
|
||||
public void requestState()
|
||||
{
|
||||
// Request state from server
|
||||
ComputerCraftPacket packet = new ComputerCraftPacket();
|
||||
packet.m_packetType = ComputerCraftPacket.RequestComputerUpdate;
|
||||
packet.m_dataInt = new int[] { getInstanceID() };
|
||||
ComputerCraft.sendToServer( packet );
|
||||
}
|
||||
|
||||
// IComputer
|
||||
|
||||
@Override
|
||||
public int getInstanceID()
|
||||
{
|
||||
return m_instanceID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getID()
|
||||
{
|
||||
return m_computerID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLabel()
|
||||
{
|
||||
return m_label;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOn()
|
||||
{
|
||||
return m_on;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCursorDisplayed()
|
||||
{
|
||||
return m_on && m_blinking;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void turnOn()
|
||||
{
|
||||
// Send turnOn to server
|
||||
ComputerCraftPacket packet = new ComputerCraftPacket();
|
||||
packet.m_packetType = ComputerCraftPacket.TurnOn;
|
||||
packet.m_dataInt = new int[] { m_instanceID };
|
||||
ComputerCraft.sendToServer( packet );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown()
|
||||
{
|
||||
// Send shutdown to server
|
||||
ComputerCraftPacket packet = new ComputerCraftPacket();
|
||||
packet.m_packetType = ComputerCraftPacket.Shutdown;
|
||||
packet.m_dataInt = new int[] { m_instanceID };
|
||||
ComputerCraft.sendToServer( packet );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reboot()
|
||||
{
|
||||
// Send reboot to server
|
||||
ComputerCraftPacket packet = new ComputerCraftPacket();
|
||||
packet.m_packetType = ComputerCraftPacket.Reboot;
|
||||
packet.m_dataInt = new int[] { m_instanceID };
|
||||
ComputerCraft.sendToServer( packet );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void queueEvent( String event )
|
||||
{
|
||||
queueEvent( event, null );
|
||||
}
|
||||
|
||||
@Override
|
||||
public void queueEvent( String event, Object[] arguments )
|
||||
{
|
||||
// Send event to server
|
||||
ComputerCraftPacket packet = new ComputerCraftPacket();
|
||||
packet.m_packetType = ComputerCraftPacket.QueueEvent;
|
||||
packet.m_dataInt = new int[] { m_instanceID };
|
||||
packet.m_dataString = new String[] { event };
|
||||
if( arguments != null )
|
||||
{
|
||||
packet.m_dataNBT = NBTUtil.encodeObjects( arguments );
|
||||
}
|
||||
ComputerCraft.sendToServer( packet );
|
||||
}
|
||||
|
||||
public void readDescription( NBTTagCompound nbttagcompound )
|
||||
{
|
||||
super.readDescription( nbttagcompound );
|
||||
|
||||
int oldID = m_computerID;
|
||||
String oldLabel = m_label;
|
||||
boolean oldOn = m_on;
|
||||
boolean oldBlinking = m_blinking;
|
||||
NBTTagCompound oldUserData = m_userData;
|
||||
|
||||
m_computerID = nbttagcompound.getInteger( "id" );
|
||||
m_label = nbttagcompound.hasKey( "label" ) ? nbttagcompound.getString( "label" ) : null;
|
||||
m_on = nbttagcompound.getBoolean( "on" );
|
||||
m_blinking = nbttagcompound.getBoolean( "blinking" );
|
||||
if( nbttagcompound.hasKey( "userData" ) )
|
||||
{
|
||||
m_userData = (NBTTagCompound)(nbttagcompound.getCompoundTag( "userData" )).copy();
|
||||
}
|
||||
else
|
||||
{
|
||||
m_userData = null;
|
||||
}
|
||||
|
||||
if( m_computerID != oldID || m_on != oldOn || m_blinking != oldBlinking || !Objects.equal( m_label, oldLabel ) || !Objects.equal( m_userData, oldUserData ) )
|
||||
{
|
||||
m_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handlePacket( ComputerCraftPacket packet, EntityPlayer sender )
|
||||
{
|
||||
switch( packet.m_packetType )
|
||||
{
|
||||
case ComputerCraftPacket.ComputerChanged:
|
||||
{
|
||||
readDescription( packet.m_dataNBT );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1123 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user