1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2025-10-15 14:07:38 +00:00

Compare commits

...

41 Commits

Author SHA1 Message Date
SquidDev
ed69495b03 Bump version 2019-01-11 21:13:51 +00:00
SquidDev
66b61d4e9e Add a config option for HTTP timeout too 2019-01-11 21:11:22 +00:00
SquidDev
8dd084ac5c A couple of minor changes to HTTP limiting
- We now error if there are too many websockets, instead of queuing
   them up. As these have a more explicit "lifetime", it could be
   confusing if http.websocket just blocks indefinitely.
 - Fix a CCME when cleaning up resources.
2019-01-11 12:07:56 +00:00
SquidDev
932f8a44fc WIP: Http rework (#98)
- Move all HTTP tasks to a unified "MonitoredResource" model. This
   provides a uniform way of tracking object's lifetimes and disposing
   of them when complete.

 - Rewrite HTTP requests to use Netty instead of standard Java. This
   offers several advantages:
    - We have access to more HTTP verbs (mostly PATCH).
    - We can now do http -> https redirects.
    - We no longer need to spawn in a new thread for each HTTP request.
      While we do need to run some tasks off-thread in order to resolve
      IPs, it's generally a much shorter task, and so is less likely to
      inflate the thread pool.

 - Introduce several limits for the http API:
    - There's a limit on how many HTTP requests and websockets may exist
      at the same time. If the limit is reached, additional ones will be
      queued up until pending requests have finished.
    - HTTP requests may upload a maximum of 4Mib and download a maximum
      of 16Mib (configurable).

 - .getResponseCode now returns the status text, as well as the status
   code.
2019-01-11 11:33:05 +00:00
SquidDev
101b3500cc Add back several more methods for Plethora
While Plethora has been updated to no longer require these, it's
probably worth keeping them around a little longer, as people may not
upgrade them in sync.
2019-01-05 20:57:32 +00:00
SquidDev
a777801e15 Enable the debug library by default
We've had this on SC for most of a year now (and SC 1 for most of its
lifetime) and not seen any issues. I'm fairly confident that it does not
allow breaking the sandbox.
2019-01-05 20:18:30 +00:00
SquidDev
0d6787641a Clean up our handling of configuration files
- Move configuration loading into a separate file, just so it doesn't
   clutter up ComputerCraft.java.
 - Normalise property names, so they're all snake_case.
 - Split properties into separate categories (http, turtle, peripheral),
   so the main one is less cluttered.
 - Define an explicit ordering of each category.
2019-01-05 20:12:02 +00:00
SquidDev
744bba300e A couple of enhancements to websockets
- Provide whether a message was binary or text in websocket_message
   and handle.receive(). (Fixes #96)
 - Provide an optional reason and status code within the websocket_close
   event.

Off topic, but also cleanup the file handles a little.
2019-01-05 18:58:23 +00:00
SquidDev
34d43d8273 Make entity in bounds selectors more restrictive
This means we can remove some additional predicates we have in place,
and hopefully make things faster as less entities are added to the list.
2019-01-03 22:20:50 +00:00
SquidDev
7bc9745c7a Remove redundant line in copyright header
Really should have noticed this when committing it.
2019-01-03 11:02:21 +00:00
SquidDev
b414cba681 Add a method stub for OpenComputers
Fixes #94
2019-01-02 17:37:16 +00:00
SquidDev
1c9110b927 Happy new year! 2019-01-01 01:10:18 +00:00
SquidDev
325459e336 Fix binary handles reading in multiples of 8192 2018-12-31 09:41:58 +00:00
SquidDev
ee3347afbd A whole bunch of refomatting
- Remove redundant constructors and super calls
 - Standardise naming of texture fields
 - Always use postfix notations for loops
 - Cleanup several peripheral classes
2018-12-30 16:42:41 +00:00
SquidDev
27aaec9a82 Move GUI constructors into the main GUI handler
We use @SideOnly to ensure classes aren't loaded on dedicated servers.

Also a tiny bit of cleanup to change several GUIs just to accept
containers.
2018-12-29 17:13:10 +00:00
SquidDev
929f23fd2d Share some map-like-item rendering code
Just refactors the hand rendering methods into a shared superclass
2018-12-29 16:42:02 +00:00
SquidDev
8422a40c69 Revert a couple of changes to be backwards compatible
- Restore ComputerState to the previous location
 - Add a stub constructor for GuiComputer
2018-12-29 14:36:03 +00:00
SquidDev
ca334e7e5c A couple of minor reformats
- nbttagcompount -> nbt. It's shorter, and hopefully will avoid
   ambiguities with 'tag' in 1.13+.
 - Remove several redundant != null checks.
2018-12-29 14:01:00 +00:00
SquidDev
54acf1d087 Sync computer state through TE data
Previously we would send computer state (labels, id, on/off) through the
ClientComputer rather than as part of the TE description. While this
mostly worked fine, it did end up making things more complex than they
needed to be.

We sync most data to the tile each tick, so there's little risk of
things getting out of date.
2018-12-29 12:44:43 +00:00
SquidDev
42d3901ee3 Move from FMLEventChannel to SimpleNetworkWrapper
- Split each network packet into it's own individual IMessage class.
 - Move the TextTable into separate classes for server and client based
   rendering.
2018-12-29 12:44:18 +00:00
SquidDev
f8b328a048 Move drop consumer code into a separate class
This has always been separate from turtles, so there is no reason to
keep it there.
2018-12-28 12:47:44 +00:00
SquidDev
41a320e9a4 Move API registration into separate classes
There's several reasons for this change:
 - Try to make ComputerCraft.java less monolithic by moving
   functionality into separate module-specific classes.
 - Hopefully make the core class less Minecraft dependent, meaning
   emulators are a little less dependent on anything outside of /core.

Note we still need /some/ methods in the main ComputerCraft class in
order to maintain backwards compatibility with Plethora and
Computronics.
2018-12-28 12:40:33 +00:00
SquidDev
57fb77d7fe Refactor common inventory code into a shared interface
Many bits of IInventory (open/close, fields, etc...) are not actually
needed most implementations, so we can clean things up a little with a
common interface.
2018-12-28 11:39:59 +00:00
SquidDev
b59dcbfc0e Remove "client" turtle brains.
These were only used for the vision camera, and so are rather pointless
now.
2018-12-27 13:10:13 +00:00
SquidDev
618c534d81 Move most recipe registration to JSON
We need this for 1.13+, so might as well get it over with.
2018-12-27 12:16:11 +00:00
SquidDev
26ba61097b Move several methods out of the proxy
Some methods act the same on both sides, and so can be in utility
classes. Others are only needed on one side, and so do not really need
to be part of the proxy.

 - Remove TurtleVisionCamera. It would be possible to add this back in
   the future, but for now it is unused and so should be removed.
 - Move frame info (cursor blink, current render frame) into a
   FrameInfo class.
 - Move record methods (name, playing a record) into a RecordUtil class.
2018-12-27 11:58:08 +00:00
SquidDev
2c87e66db8 Move several methods from TileGeneric to blocks
- getPickBlock is now implemented directly on computers and turtles,
   rather than on the tile.
 - Bounding boxes are handled on the block rather than tile. This ends
   up being a little ugly in the case of BlockPeripheral, but it's not
   the end of the world.
 - Explosion resistance is only implemented for turtles now.
2018-12-27 11:32:29 +00:00
SquidDev
f61f7df2d8 Replace "cable variant" with a block model
- Replace BlockCableCableVariant with a boolean, removing any custom
   logic around it.
 - Replace our previous cable Forge-blockstate with a vanilla one, which
   handles cable connections in the model logic.
2018-12-27 10:21:57 +00:00
SquidDev
364d31465e Move modem code into separate packages
Things were shared between common and modem, which just ended up making
things very complicated.
2018-12-27 10:14:22 +00:00
SquidDev
4c7ac50dd8 Fix a rather silly typo
I wonder if it'd be possible to extend LuaCheck to detect such cases?
2018-12-27 09:10:06 +00:00
SquidDev
37e25136ed Replace our ItemOverrideList overrides with property getters
This ends up being slightly cleaner as we can rely on Minecraft's own
model dependency system. Also reduces reliance on Forge's APIs, which
_potentially_ makes porting a little easier.
2018-12-26 18:36:41 +00:00
SquidDev
d9f03f3ec7 Make the test-file directory when running tests 2018-12-26 10:53:56 +00:00
SquidDev
4d5c52bc63 Replace WorldUtil methods with builtin alternatives
- Replace most 0 <= y < world.getHeight() checks with
  world.isBlockValid.
 - Remove several "in bounds" checks, as they'll be handled by later
   calls.
2018-12-26 10:28:32 +00:00
SquidDev
a1c4a9fb58 Replace DirectionUtil methods with builtin equivalents 2018-12-26 09:31:15 +00:00
SquidDev
031f17c98e Remove a couple of redundant commands
- Remove the two redstone commands. These are not used (maybe only by
   CCEdu), and so are somewhat redundant.
 - Inline the select command, converting it to a lambda.
 - Inline the attack/dig commands, as they did little more than wrap the
   tool command.
2018-12-26 09:21:33 +00:00
SquidDev
4ead319092 Remove direct support for beginner's turtles
As CCEdu has not been updated, and is unlikely to be updated as Dan does
not have the rights to open source it, we're removing explicit support
for now.

If an alternative arises in the future, it would be good to support, but
in a way which requires less workarounds in CC's core.
2018-12-26 09:13:15 +00:00
SquidDev
dd6bab5413 Move some shared upgrade code into a base class
Most upgrades provides a couple of constant getters (upgrade ID,
adjective, crafting item). We move the getters into a parent class and
pass the values in via the constructor instead.

Also do a tiny bit of cleanup to the upgrades. Mostly just reducing
nesting, renaming fields, etc...
2018-12-26 09:01:03 +00:00
SquidDev
5b48a0fa5f Fix a couple of issues with FileSystemMounts
- Only generate resource pack mounts if the desired directory exists.
 - Allow mounting files, as well as directories (fixes #90).

As always, also a wee bit of cleanup to some of the surrounding code.
2018-12-24 15:22:19 +00:00
SquidDev
2032e7a83a Reformat everything
It's been a long time comin'
But tonight is the end of the war, my friend
Tomorrow only one style will remain.
2018-12-23 17:46:58 +00:00
theoriginalbit
72b9d3d802 Add custom code style settings
This formats the Java and JSON code to be as close to the existing style
as possible.
2018-12-23 17:45:04 +00:00
SquidDev
70cb8ae16c Add back the previous widget methods for back compat
Previously introduced in f765b6a487.

Fixes #87
2018-12-23 16:55:25 +00:00
417 changed files with 9777 additions and 9544 deletions

11
.gitignore vendored
View File

@@ -1,12 +1,17 @@
# Build directories
/classes
/logs
/build
/out
# Runtime directories
/run
/run-*
/test-files
*.ipr
*.iws
*.iml
.idea
.gradle
/luaj-2.0.3/lib
/luaj-2.0.3/*.jar
*.DS_Store
/test-files

View File

@@ -23,7 +23,7 @@ apply plugin: 'org.ajoberstar.grgit'
apply plugin: 'maven-publish'
apply plugin: 'maven'
version = "1.80pr1.12"
version = "1.80pr1.13"
group = "org.squiddev"
archivesBaseName = "cc-tweaked"

61
codeStyleSettings.xml Normal file
View File

@@ -0,0 +1,61 @@
<code_scheme name="Project" version="173">
<JSON>
<option name="OBJECT_WRAPPING" value="1" />
<option name="ARRAY_WRAPPING" value="1" />
</JSON>
<JavaCodeStyleSettings>
<option name="PACKAGES_TO_USE_IMPORT_ON_DEMAND">
<value />
</option>
<option name="JD_P_AT_EMPTY_LINES" value="false" />
<option name="JD_PRESERVE_LINE_FEEDS" value="true" />
</JavaCodeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
<option name="BRACE_STYLE" value="2" />
<option name="CLASS_BRACE_STYLE" value="2" />
<option name="METHOD_BRACE_STYLE" value="2" />
<option name="LAMBDA_BRACE_STYLE" value="5" />
<option name="ELSE_ON_NEW_LINE" value="true" />
<option name="CATCH_ON_NEW_LINE" value="true" />
<option name="FINALLY_ON_NEW_LINE" value="true" />
<option name="SPACE_WITHIN_METHOD_CALL_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_METHOD_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_IF_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_WHILE_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_FOR_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_TRY_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_CATCH_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_SWITCH_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_SYNCHRONIZED_PARENTHESES" value="true" />
<option name="SPACE_WITHIN_ARRAY_INITIALIZER_BRACES" value="true" />
<option name="SPACE_BEFORE_IF_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_WHILE_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_FOR_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_TRY_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_CATCH_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_SWITCH_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_SYNCHRONIZED_PARENTHESES" value="false" />
<option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
<option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" />
<option name="KEEP_SIMPLE_LAMBDAS_IN_ONE_LINE" value="true" />
<option name="KEEP_SIMPLE_CLASSES_IN_ONE_LINE" value="true" />
<option name="IF_BRACE_FORCE" value="1" />
<option name="DOWHILE_BRACE_FORCE" value="1" />
<option name="WHILE_BRACE_FORCE" value="1" />
<option name="FOR_BRACE_FORCE" value="1" />
<option name="SPACE_WITHIN_ANNOTATION_PARENTHESES" value="true" />
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JSON">
<option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
<option name="SPACE_WITHIN_BRACKETS" value="true" />
<option name="SPACE_WITHIN_BRACES" value="true" />
<indentOptions>
<option name="INDENT_SIZE" value="4" />
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
</codeStyleSettings>
</code_scheme>

View File

@@ -1,13 +1,11 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft;
import com.google.common.base.CaseFormat;
import com.google.common.base.Converter;
import dan200.computercraft.api.filesystem.IMount;
import dan200.computercraft.api.filesystem.IWritableMount;
import dan200.computercraft.api.lua.ILuaAPIFactory;
@@ -24,12 +22,14 @@ import dan200.computercraft.api.redstone.IBundledRedstoneProvider;
import dan200.computercraft.api.turtle.ITurtleUpgrade;
import dan200.computercraft.api.turtle.event.TurtleAction;
import dan200.computercraft.core.apis.AddressPredicate;
import dan200.computercraft.core.apis.ApiFactories;
import dan200.computercraft.core.apis.http.websocket.Websocket;
import dan200.computercraft.core.filesystem.ComboMount;
import dan200.computercraft.core.filesystem.FileMount;
import dan200.computercraft.core.filesystem.FileSystemMount;
import dan200.computercraft.core.terminal.Terminal;
import dan200.computercraft.core.tracking.Tracking;
import dan200.computercraft.shared.common.DefaultBundledRedstoneProvider;
import dan200.computercraft.shared.*;
import dan200.computercraft.shared.computer.blocks.BlockCommandComputer;
import dan200.computercraft.shared.computer.blocks.BlockComputer;
import dan200.computercraft.shared.computer.blocks.TileComputer;
@@ -41,14 +41,12 @@ 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.common.BlockWiredModemFull;
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.modem.wired.BlockCable;
import dan200.computercraft.shared.peripheral.modem.wired.BlockWiredModemFull;
import dan200.computercraft.shared.peripheral.modem.wireless.BlockAdvancedModem;
import dan200.computercraft.shared.peripheral.modem.wireless.WirelessNetwork;
import dan200.computercraft.shared.peripheral.printer.TilePrinter;
import dan200.computercraft.shared.pocket.items.ItemPocketComputer;
import dan200.computercraft.shared.pocket.peripherals.PocketModem;
@@ -60,55 +58,43 @@ 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.InventoryUtil;
import dan200.computercraft.shared.util.WorldUtil;
import dan200.computercraft.shared.util.IoUtil;
import dan200.computercraft.shared.wired.CapabilityWiredElement;
import dan200.computercraft.shared.wired.WiredNode;
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.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.config.ConfigCategory;
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.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nonnull;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.util.*;
import java.util.function.Function;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.ServiceConfigurationError;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
///////////////
// UNIVERSAL //
///////////////
@Mod(
modid = ComputerCraft.MOD_ID, name = "CC: Tweaked", version = "${version}",
guiFactory = "dan200.computercraft.client.gui.GuiConfigCC$Factory",
@@ -129,8 +115,8 @@ public class ComputerCraft
public static final int viewComputerGUIID = 110;
// Configuration options
private static final String[] DEFAULT_HTTP_WHITELIST = new String[] { "*" };
private static final String[] DEFAULT_HTTP_BLACKLIST = new String[] {
public static final String[] DEFAULT_HTTP_WHITELIST = new String[] { "*" };
public static final String[] DEFAULT_HTTP_BLACKLIST = new String[] {
"127.0.0.0/8",
"10.0.0.0/8",
"172.16.0.0/12",
@@ -138,17 +124,34 @@ public class ComputerCraft
"fd00::/8",
};
public static int computerSpaceLimit = 1000 * 1000;
public static int floppySpaceLimit = 125 * 1000;
public static int maximumFilesOpen = 128;
public static boolean disable_lua51_features = false;
public static String default_computer_settings = "";
public static boolean debug_enable = true;
public static int computer_threads = 1;
public static boolean logPeripheralErrors = false;
public static boolean http_enable = true;
public static boolean http_websocket_enable = true;
public static AddressPredicate http_whitelist = new AddressPredicate( DEFAULT_HTTP_WHITELIST );
public static AddressPredicate http_blacklist = new AddressPredicate( DEFAULT_HTTP_BLACKLIST );
public static boolean disable_lua51_features = false;
public static String default_computer_settings = "";
public static boolean debug_enable = false;
public static int computer_threads = 1;
public static boolean logPeripheralErrors = false;
public static int httpTimeout = 30000;
public static int httpMaxRequests = 16;
public static long httpMaxDownload = 16 * 1024 * 1024;
public static long httpMaxUpload = 4 * 1024 * 1024;
public static int httpMaxWebsockets = 4;
public static int httpMaxWebsocketMessage = Websocket.MAX_MESSAGE_SIZE;
public static boolean enableCommandBlock = false;
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 maxNotesPerTick = 8;
public static boolean turtlesNeedFuel = true;
public static int turtleFuelLimit = 20000;
public static int advancedTurtleFuelLimit = 100000;
@@ -165,17 +168,6 @@ public class ComputerCraft
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 maximumFilesOpen = 128;
public static int maxNotesPerTick = 8;
// Blocks and Items
public static class Blocks
{
@@ -219,45 +211,12 @@ public class ComputerCraft
public static PocketSpeaker pocketSpeaker;
}
public static class Config {
public static Configuration config;
public static Property http_enable;
public static Property http_websocket_enable;
public static Property http_whitelist;
public static Property http_blacklist;
public static Property disable_lua51_features;
public static Property default_computer_settings;
public static Property debug_enable;
public static Property computer_threads;
public static Property logPeripheralErrors;
public static Property enableCommandBlock;
public static Property turtlesNeedFuel;
public static Property turtleFuelLimit;
public static Property advancedTurtleFuelLimit;
public static Property turtlesObeyBlockProtection;
public static Property turtlesCanPush;
public static Property turtleDisabledActions;
public static Property modem_range;
public static Property modem_highAltitudeRange;
public static Property modem_rangeDuringStorm;
public static Property modem_highAltitudeRangeDuringStorm;
public static Property computerSpaceLimit;
public static Property floppySpaceLimit;
public static Property maximumFilesOpen;
public static Property maxNotesPerTick;
}
// Registries
public static ClientComputerRegistry clientComputerRegistry = new ClientComputerRegistry();
public static ServerComputerRegistry serverComputerRegistry = new ServerComputerRegistry();
// Networking
public static FMLEventChannel networkEventChannel;
public static SimpleNetworkWrapper networkWrapper;
// Creative
public static CreativeTabMain mainCreativeTab;
@@ -265,13 +224,8 @@ public class ComputerCraft
// Logging
public static Logger log;
// API users
private static List<IPeripheralProvider> peripheralProviders = new ArrayList<>();
private static List<IBundledRedstoneProvider> bundledRedstoneProviders = new ArrayList<>();
private static List<IMediaProvider> mediaProviders = new ArrayList<>();
private static List<ITurtlePermissionProvider> permissionProviders = new ArrayList<>();
private static final Map<String, IPocketUpgrade> pocketUpgrades = new HashMap<>();
private static final Set<ILuaAPIFactory> apiFactories = new LinkedHashSet<>();
// Peripheral providers. This is still here to ensure compatibility with Plethora and Computronics
public static List<IPeripheralProvider> peripheralProviders = new ArrayList<>();
// Implementation
@Mod.Instance( value = ComputerCraft.MOD_ID )
@@ -283,179 +237,21 @@ public class ComputerCraft
@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 )
{
log = event.getModLog();
// Load config
Config.config = new Configuration( event.getSuggestedConfigurationFile() );
loadConfig();
Config.load( event.getSuggestedConfigurationFile() );
// Setup network
networkEventChannel = NetworkRegistry.INSTANCE.newEventDrivenChannel( "CC" );
networkEventChannel.register( new PacketHandler() );
networkWrapper = NetworkRegistry.INSTANCE.newSimpleChannel( ComputerCraft.MOD_ID );
proxy.preInit();
turtleProxy.preInit();
}
public static void loadConfig()
{
Config.config.load();
Config.http_enable = Config.config.get( Configuration.CATEGORY_GENERAL, "http_enable", http_enable );
Config.http_enable.setComment( "Enable the \"http\" API on Computers (see \"http_whitelist\" and \"http_blacklist\" for more fine grained control than this)" );
Config.http_websocket_enable = Config.config.get( Configuration.CATEGORY_GENERAL, "http_websocket_enable", http_websocket_enable );
Config.http_websocket_enable.setComment( "Enable use of http websockets. This requires the \"http_enable\" option to also be true." );
{
ConfigCategory category = Config.config.getCategory( Configuration.CATEGORY_GENERAL );
Property currentProperty = category.get( "http_whitelist" );
if( currentProperty != null && !currentProperty.isList() ) category.remove( "http_whitelist" );
Config.http_whitelist = Config.config.get( Configuration.CATEGORY_GENERAL, "http_whitelist", DEFAULT_HTTP_WHITELIST );
if( currentProperty != null && !currentProperty.isList() )
{
Config.http_whitelist.setValues( currentProperty.getString().split( ";" ) );
}
}
Config.http_whitelist.setComment( "A list of wildcards for domains or IP ranges that can be accessed through the \"http\" API on Computers.\n" +
"Set this to \"*\" to access to the entire internet. Example: \"*.pastebin.com\" will restrict access to just subdomains of pastebin.com.\n" +
"You can use domain names (\"pastebin.com\"), wilcards (\"*.pastebin.com\") or CIDR notation (\"127.0.0.0/8\")." );
Config.http_blacklist = Config.config.get( Configuration.CATEGORY_GENERAL, "http_blacklist", DEFAULT_HTTP_BLACKLIST );
Config.http_blacklist.setComment( "A list of wildcards for domains or IP ranges that cannot be accessed through the \"http\" API on Computers.\n" +
"If this is empty then all whitelisted domains will be accessible. Example: \"*.github.com\" will block access to all subdomains of github.com.\n" +
"You can use domain names (\"pastebin.com\"), wilcards (\"*.pastebin.com\") or CIDR notation (\"127.0.0.0/8\")." );
Config.disable_lua51_features = Config.config.get( Configuration.CATEGORY_GENERAL, "disable_lua51_features", disable_lua51_features );
Config.disable_lua51_features.setComment( "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." );
Config.default_computer_settings = Config.config.get( Configuration.CATEGORY_GENERAL, "default_computer_settings", default_computer_settings );
Config.default_computer_settings.setComment( "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" );
Config.debug_enable = Config.config.get( Configuration.CATEGORY_GENERAL, "debug_enable", debug_enable );
Config.debug_enable.setComment( "Enable Lua's debug library. Whilst this should be safe for general use, it may allow players to interact with other computers. Enable at your own risk." );
Config.computer_threads = Config.config.get( Configuration.CATEGORY_GENERAL, "computer_threads", computer_threads );
Config.computer_threads
.setMinValue( 1 )
.setRequiresWorldRestart( true )
.setComment( "Set the number of threads computers can run on. A higher number means more computers can run at once, but may induce lag.\n" +
"Please note that some mods may not work with a thread count higher than 1. Use with caution." );
Config.logPeripheralErrors = Config.config.get( Configuration.CATEGORY_GENERAL, "logPeripheralErrors", logPeripheralErrors );
Config.logPeripheralErrors.setComment( "Log exceptions thrown by peripherals and other Lua objects.\n" +
"This makes it easier for mod authors to debug problems, but may result in log spam should people use buggy methods." );
Config.enableCommandBlock = Config.config.get( Configuration.CATEGORY_GENERAL, "enableCommandBlock", enableCommandBlock );
Config.enableCommandBlock.setComment( "Enable Command Block peripheral support" );
Config.modem_range = Config.config.get( Configuration.CATEGORY_GENERAL, "modem_range", modem_range );
Config.modem_range.setComment( "The range of Wireless Modems at low altitude in clear weather, in meters" );
Config.modem_highAltitudeRange = Config.config.get( Configuration.CATEGORY_GENERAL, "modem_highAltitudeRange", modem_highAltitudeRange );
Config.modem_highAltitudeRange.setComment( "The range of Wireless Modems at maximum altitude in clear weather, in meters" );
Config.modem_rangeDuringStorm = Config.config.get( Configuration.CATEGORY_GENERAL, "modem_rangeDuringStorm", modem_rangeDuringStorm );
Config.modem_rangeDuringStorm.setComment( "The range of Wireless Modems at low altitude in stormy weather, in meters" );
Config.modem_highAltitudeRangeDuringStorm = Config.config.get( Configuration.CATEGORY_GENERAL, "modem_highAltitudeRangeDuringStorm", modem_highAltitudeRangeDuringStorm );
Config.modem_highAltitudeRangeDuringStorm.setComment( "The range of Wireless Modems at maximum altitude in stormy weather, in meters" );
Config.computerSpaceLimit = Config.config.get( Configuration.CATEGORY_GENERAL, "computerSpaceLimit", computerSpaceLimit );
Config.computerSpaceLimit.setComment( "The disk space limit for computers and turtles, in bytes" );
Config.floppySpaceLimit = Config.config.get( Configuration.CATEGORY_GENERAL, "floppySpaceLimit", floppySpaceLimit );
Config.floppySpaceLimit.setComment( "The disk space limit for floppy disks, in bytes" );
Config.turtlesNeedFuel = Config.config.get( Configuration.CATEGORY_GENERAL, "turtlesNeedFuel", turtlesNeedFuel );
Config.turtlesNeedFuel.setComment( "Set whether Turtles require fuel to move" );
Config.maximumFilesOpen = Config.config.get(Configuration.CATEGORY_GENERAL, "maximumFilesOpen", maximumFilesOpen);
Config.maximumFilesOpen.setComment( "Set how many files a computer can have open at the same time. Set to 0 for unlimited." );
Config.turtleFuelLimit = Config.config.get( Configuration.CATEGORY_GENERAL, "turtleFuelLimit", turtleFuelLimit );
Config.turtleFuelLimit.setComment( "The fuel limit for Turtles" );
Config.advancedTurtleFuelLimit = Config.config.get( Configuration.CATEGORY_GENERAL, "advancedTurtleFuelLimit", advancedTurtleFuelLimit );
Config.advancedTurtleFuelLimit.setComment( "The fuel limit for Advanced Turtles" );
Config.turtlesObeyBlockProtection = Config.config.get( Configuration.CATEGORY_GENERAL, "turtlesObeyBlockProtection", turtlesObeyBlockProtection );
Config.turtlesObeyBlockProtection.setComment( "If set to true, Turtles will be unable to build, dig, or enter protected areas (such as near the server spawn point)" );
Config.turtlesCanPush = Config.config.get( Configuration.CATEGORY_GENERAL, "turtlesCanPush", turtlesCanPush );
Config.turtlesCanPush.setComment( "If set to true, Turtles will push entities out of the way instead of stopping if there is space to do so" );
Config.turtleDisabledActions = Config.config.get( Configuration.CATEGORY_GENERAL, "turtle_disabled_actions", new String[ 0 ] );
Config.turtleDisabledActions.setComment( "A list of turtle actions which are disabled." );
Config.maxNotesPerTick = Config.config.get( Configuration.CATEGORY_GENERAL, "maxNotesPerTick", maxNotesPerTick );
Config.maxNotesPerTick.setComment( "Maximum amount of notes a speaker can play at once" );
for (Property property : Config.config.getCategory( Configuration.CATEGORY_GENERAL ).getOrderedValues())
{
property.setLanguageKey( "gui.computercraft:config." + CaseFormat.LOWER_CAMEL.to( CaseFormat.LOWER_UNDERSCORE, property.getName() ) );
}
syncConfig();
}
public static void syncConfig() {
http_enable = Config.http_enable.getBoolean();
http_websocket_enable = Config.http_websocket_enable.getBoolean();
http_whitelist = new AddressPredicate( Config.http_whitelist.getStringList() );
http_blacklist = new AddressPredicate( Config.http_blacklist.getStringList() );
disable_lua51_features = Config.disable_lua51_features.getBoolean();
default_computer_settings = Config.default_computer_settings.getString();
debug_enable = Config.debug_enable.getBoolean();
computer_threads = Config.computer_threads.getInt();
logPeripheralErrors = Config.logPeripheralErrors.getBoolean();
enableCommandBlock = Config.enableCommandBlock.getBoolean();
modem_range = Math.min( Config.modem_range.getInt(), 100000 );
modem_highAltitudeRange = Math.min( Config.modem_highAltitudeRange.getInt(), 100000 );
modem_rangeDuringStorm = Math.min( Config.modem_rangeDuringStorm.getInt(), 100000 );
modem_highAltitudeRangeDuringStorm = Math.min( Config.modem_highAltitudeRangeDuringStorm.getInt(), 100000 );
computerSpaceLimit = Config.computerSpaceLimit.getInt();
floppySpaceLimit = Config.floppySpaceLimit.getInt();
maximumFilesOpen = Math.max( 0, Config.maximumFilesOpen.getInt() );
turtlesNeedFuel = Config.turtlesNeedFuel.getBoolean();
turtleFuelLimit = Config.turtleFuelLimit.getInt();
advancedTurtleFuelLimit = Config.advancedTurtleFuelLimit.getInt();
turtlesObeyBlockProtection = Config.turtlesObeyBlockProtection.getBoolean();
turtlesCanPush = Config.turtlesCanPush.getBoolean();
turtleDisabledActions.clear();
Converter<String, String> converter = CaseFormat.LOWER_CAMEL.converterTo( CaseFormat.UPPER_UNDERSCORE );
for( String value : Config.turtleDisabledActions.getStringList() )
{
try
{
turtleDisabledActions.add( TurtleAction.valueOf( converter.convert( value ) ) );
}
catch( IllegalArgumentException e )
{
ComputerCraft.log.error( "Unknown turtle action " + value );
}
}
maxNotesPerTick = Math.max(1, Config.maxNotesPerTick.getInt());
Config.config.save();
}
@Mod.EventHandler
public void init( FMLInitializationEvent event )
{
@@ -496,36 +292,6 @@ public class ComputerCraft
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 Object getFixedWidthFontRenderer()
{
return proxy.getFixedWidthFontRenderer();
}
public static void playRecord( SoundEvent record, String recordInfo, World world, BlockPos pos )
{
proxy.playRecord( record, recordInfo, world, pos );
}
public static String getRecordInfo( @Nonnull ItemStack recordStack )
{
return proxy.getRecordInfo( recordStack );
}
public static void openDiskDriveGUI( EntityPlayer player, TileDiskDrive drive )
{
BlockPos pos = drive.getPos();
@@ -578,12 +344,12 @@ public class ComputerCraft
);
}
public static File getBaseDir()
private static File getBaseDir()
{
return FMLCommonHandler.instance().getMinecraftServerInstance().getFile(".");
return FMLCommonHandler.instance().getMinecraftServerInstance().getDataDirectory();
}
public static File getResourcePackDir()
private static File getResourcePackDir()
{
return new File( getBaseDir(), "resourcepacks" );
}
@@ -593,36 +359,24 @@ public class ComputerCraft
return proxy.getWorldDir( world );
}
private static FMLProxyPacket encode( ComputerCraftPacket packet )
public static void sendToPlayer( EntityPlayer player, IMessage packet )
{
PacketBuffer buffer = new PacketBuffer( Unpooled.buffer() );
packet.toBytes( buffer );
return new FMLProxyPacket( buffer, "CC" );
networkWrapper.sendTo( packet, (EntityPlayerMP) player );
}
public static void sendToPlayer( EntityPlayer player, ComputerCraftPacket packet )
public static void sendToAllPlayers( IMessage packet )
{
networkEventChannel.sendTo( encode( packet ), (EntityPlayerMP)player );
networkWrapper.sendToAll( packet );
}
public static void sendToAllPlayers( ComputerCraftPacket packet )
public static void sendToServer( IMessage packet )
{
networkEventChannel.sendToAll( encode( packet ) );
networkWrapper.sendToServer( packet );
}
public static void sendToServer( ComputerCraftPacket packet )
public static void sendToAllAround( IMessage packet, NetworkRegistry.TargetPoint point )
{
networkEventChannel.sendToServer( encode( packet ) );
}
public static void sendToAllAround( ComputerCraftPacket packet, NetworkRegistry.TargetPoint point )
{
networkEventChannel.sendToAllAround( encode( packet ), point );
}
public static void handlePacket( ComputerCraftPacket packet, EntityPlayer player )
{
proxy.handlePacket( packet, player );
networkWrapper.sendToAllAround( packet, point );
}
public static boolean canPlayerUseCommands( EntityPlayer player )
@@ -635,136 +389,49 @@ public class ComputerCraft
return false;
}
public static boolean isPlayerOpped( EntityPlayer player )
{
MinecraftServer server = player.getServer();
if( server != null )
{
return server.getPlayerList().getOppedPlayers().getEntry( player.getGameProfile() ) != null;
}
return false;
}
@Deprecated
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 = player.getServer();
if( server != null && !world.isRemote )
{
if( server.isBlockProtected( world, pos, player ) )
{
return false;
}
}
for( ITurtlePermissionProvider provider : permissionProviders )
{
if( !provider.isBlockEnterable( world, pos ) )
{
return false;
}
}
return true;
}
public static boolean isBlockEditable( World world, BlockPos pos, EntityPlayer player )
{
MinecraftServer server = player.getServer();
if( server != null && !world.isRemote )
{
if( server.isBlockProtected( world, pos, player ) )
{
return false;
}
}
for( ITurtlePermissionProvider provider : permissionProviders )
{
if( !provider.isBlockEditable( world, pos ) )
{
return false;
}
}
return true;
TurtlePermissions.register( provider );
}
@Deprecated
public static void registerPocketUpgrade( IPocketUpgrade upgrade )
{
String id = upgrade.getUpgradeID().toString();
IPocketUpgrade existing = pocketUpgrades.get( id );
if( existing != null )
{
throw new RuntimeException( "Error registering '" + upgrade.getUnlocalisedAdjective() + " pocket computer'. UpgradeID '" + id + "' is already registered by '" + existing.getUnlocalisedAdjective() + " pocket computer'" );
}
pocketUpgrades.put( id, upgrade );
dan200.computercraft.shared.PocketUpgrades.register( upgrade );
}
@Deprecated
public static void registerPeripheralProvider( IPeripheralProvider provider )
{
if( provider != null && !peripheralProviders.contains( provider ) )
{
peripheralProviders.add( provider );
}
Peripherals.register( provider );
}
@Deprecated
public static void registerBundledRedstoneProvider( IBundledRedstoneProvider provider )
{
if( provider != null && !bundledRedstoneProviders.contains( provider ) )
{
bundledRedstoneProviders.add( provider );
}
BundledRedstone.register( provider );
}
@Deprecated
public static void registerMediaProvider( IMediaProvider provider )
{
if( provider != null && !mediaProviders.contains( provider ) )
{
mediaProviders.add( provider );
}
MediaProviders.register( provider );
}
public static void registerAPIFactory( ILuaAPIFactory provider )
@Deprecated
public static void registerAPIFactory( ILuaAPIFactory factory )
{
if( provider != null )
{
apiFactories.add( provider );
}
ApiFactories.register( factory );
}
@Deprecated
public static IWiredNode createWiredNodeForElement( IWiredElement element )
{
return new WiredNode( element );
}
public static IPeripheral getPeripheralAt( World world, BlockPos pos, EnumFacing side )
{
// Try the handlers in order:
for( IPeripheralProvider peripheralProvider : peripheralProviders )
{
try
{
IPeripheral peripheral = peripheralProvider.getPeripheral( world, pos, side );
if( peripheral != null )
{
return peripheral;
}
}
catch( Exception e )
{
ComputerCraft.log.error( "Peripheral provider " + peripheralProvider + " errored.", e );
}
}
return null;
}
@Deprecated
public static IWiredElement getWiredElementAt( IBlockAccess world, BlockPos pos, EnumFacing side )
{
TileEntity tile = world.getTileEntity( pos );
@@ -773,122 +440,25 @@ public class ComputerCraft
: null;
}
@Deprecated
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;
for( IBundledRedstoneProvider bundledRedstoneProvider : bundledRedstoneProviders )
{
try
{
int signal = bundledRedstoneProvider.getBundledRedstoneOutput( world, pos, side );
if( signal >= 0 )
{
if( combinedSignal < 0 )
{
combinedSignal = (signal & 0xffff);
}
else
{
combinedSignal = combinedSignal | (signal & 0xffff);
}
}
}
catch( Exception e )
{
ComputerCraft.log.error( "Bundled redstone provider " + bundledRedstoneProvider + " errored.", e );
}
}
return combinedSignal;
}
public static IMedia getMedia( @Nonnull ItemStack stack )
{
if( !stack.isEmpty() )
{
// Try the handlers in order:
for( IMediaProvider mediaProvider : mediaProviders )
{
try
{
IMedia media = mediaProvider.getMedia( stack );
if( media != null )
{
return media;
}
}
catch( Exception e )
{
// mod misbehaved, ignore it
ComputerCraft.log.error( "Media provider " + mediaProvider + " errored.", e );
}
}
return null;
}
return null;
}
public static IPocketUpgrade getPocketUpgrade(String id) {
return pocketUpgrades.get( id );
}
public static IPocketUpgrade getPocketUpgrade( @Nonnull ItemStack stack )
{
if( stack.isEmpty() ) return null;
for (IPocketUpgrade upgrade : pocketUpgrades.values())
{
ItemStack craftingStack = upgrade.getCraftingItem();
if( !craftingStack.isEmpty() && InventoryUtil.areItemsStackable( stack, craftingStack ) )
{
return upgrade;
}
}
return null;
}
public static Iterable<IPocketUpgrade> getVanillaPocketUpgrades() {
List<IPocketUpgrade> upgrades = new ArrayList<>();
for(IPocketUpgrade upgrade : pocketUpgrades.values()) {
if(upgrade instanceof PocketModem || upgrade instanceof PocketSpeaker) {
upgrades.add( upgrade );
}
}
return upgrades;
return BundledRedstone.getDefaultOutput( world, pos, side );
}
@Deprecated
public static IPacketNetwork getWirelessNetwork()
{
return WirelessNetwork.getUniversal();
}
public static Iterable<ILuaAPIFactory> getAPIFactories()
{
return apiFactories;
}
@Deprecated
public static int createUniqueNumberedSaveDir( World world, String parentSubPath )
{
return IDAssigner.getNextIDFromDirectory(new File(getWorldDir(world), parentSubPath));
return IDAssigner.getNextIDFromDirectory( new File( getWorldDir( world ), parentSubPath ) );
}
@Deprecated
public static IWritableMount createSaveDirMount( World world, String subPath, long capacity )
{
try
@@ -901,6 +471,7 @@ public class ComputerCraft
}
}
@Deprecated
public static IMount createResourceMount( Class<?> modClass, String domain, String subPath )
{
// Start building list of mounts
@@ -949,7 +520,7 @@ public class ComputerCraft
{
// Mount a resource pack from a jar
FileSystem fs = FileSystems.newFileSystem( resourcePack.toPath(), ComputerCraft.class.getClassLoader() );
mounts.add( new FileSystemMount( fs, subPath ) );
if( Files.exists( fs.getPath( subPath ) ) ) mounts.add( new FileSystemMount( fs, subPath ) );
}
else
{
@@ -972,7 +543,7 @@ public class ComputerCraft
// Return the combination of all the mounts found
if( mounts.size() >= 2 )
{
IMount[] mountArray = new IMount[ mounts.size() ];
IMount[] mountArray = new IMount[mounts.size()];
mounts.toArray( mountArray );
return new ComboMount( mountArray );
}
@@ -1036,12 +607,12 @@ public class ComputerCraft
}
else
{
IOUtils.closeQuietly( zipFile );
IoUtil.closeQuietly( zipFile );
}
}
catch( IOException e )
{
if( zipFile != null ) IOUtils.closeQuietly( zipFile );
if( zipFile != null ) IoUtil.closeQuietly( zipFile );
}
}
}
@@ -1078,16 +649,22 @@ public class ComputerCraft
}
URL url;
try {
try
{
url = new URL( path );
} catch (MalformedURLException e1) {
}
catch( MalformedURLException e1 )
{
return null;
}
File file;
try {
try
{
file = new File( url.toURI() );
} catch(URISyntaxException e) {
}
catch( URISyntaxException e )
{
file = new File( url.getPath() );
}
return file;
@@ -1096,51 +673,51 @@ public class ComputerCraft
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(), "../.." );
int bangIndex = path.indexOf( "!" );
return bangIndex >= 0 ? null : new File( new File( path ).getParentFile(), "../.." );
}
@Deprecated
public static void registerTurtleUpgrade( ITurtleUpgrade upgrade )
{
turtleProxy.registerTurtleUpgrade( upgrade );
TurtleUpgrades.register( upgrade );
}
//region Compatibility
@Deprecated
public static IMedia getMedia( ItemStack stack )
{
return MediaProviders.get( stack );
}
@Deprecated
public static IPocketUpgrade getPocketUpgrade( ItemStack stack )
{
return dan200.computercraft.shared.PocketUpgrades.get( stack );
}
@Deprecated
public static ITurtleUpgrade getTurtleUpgrade( ItemStack stack )
{
return TurtleUpgrades.get( stack );
}
@Deprecated
public static IPocketUpgrade getPocketUpgrade( String id )
{
return dan200.computercraft.shared.PocketUpgrades.get( id );
}
@Deprecated
public static ITurtleUpgrade getTurtleUpgrade( String id )
{
return turtleProxy.getTurtleUpgrade( id );
return TurtleUpgrades.get( id );
}
public static ITurtleUpgrade getTurtleUpgrade( int legacyID )
@Deprecated
public static IPeripheral getPeripheralAt( World world, BlockPos pos, EnumFacing side )
{
return turtleProxy.getTurtleUpgrade( legacyID );
}
public static ITurtleUpgrade getTurtleUpgrade( @Nonnull ItemStack item )
{
return turtleProxy.getTurtleUpgrade( item );
}
public static void addAllUpgradedTurtles( NonNullList<ItemStack> list )
{
turtleProxy.addAllUpgradedTurtles( list );
}
public static void setDropConsumer( Entity entity, Function<ItemStack, ItemStack> consumer )
{
turtleProxy.setDropConsumer( entity, consumer );
}
public static void setDropConsumer( World world, BlockPos pos, Function<ItemStack, ItemStack> consumer )
{
turtleProxy.setDropConsumer( world, pos, consumer );
}
public static List<ItemStack> clearDropConsumer( )
{
return turtleProxy.clearDropConsumer();
return Peripherals.getPeripheral( world, pos, side );
}
//endregion
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/
@@ -49,9 +49,12 @@ public final class ComputerCraftAPI
findCC();
if( computerCraft_getVersion != null )
{
try {
return (String)computerCraft_getVersion.invoke( null );
} catch (Exception e) {
try
{
return (String) computerCraft_getVersion.invoke( null );
}
catch( Exception e )
{
// It failed
}
}
@@ -82,9 +85,12 @@ public final class ComputerCraftAPI
findCC();
if( computerCraft_createUniqueNumberedSaveDir != null )
{
try {
return (Integer)computerCraft_createUniqueNumberedSaveDir.invoke( null, world, parentSubPath );
} catch (Exception e) {
try
{
return (Integer) computerCraft_createUniqueNumberedSaveDir.invoke( null, world, parentSubPath );
}
catch( Exception e )
{
// It failed
}
}
@@ -115,9 +121,12 @@ public final class ComputerCraftAPI
findCC();
if( computerCraft_createSaveDirMount != null )
{
try {
return (IWritableMount)computerCraft_createSaveDirMount.invoke( null, world, subPath, capacity );
} catch (Exception e){
try
{
return (IWritableMount) computerCraft_createSaveDirMount.invoke( null, world, subPath, capacity );
}
catch( Exception e )
{
// It failed
}
}
@@ -148,9 +157,12 @@ public final class ComputerCraftAPI
findCC();
if( computerCraft_createResourceMount != null )
{
try {
return (IMount)computerCraft_createResourceMount.invoke( null, modClass, domain, subPath );
} catch (Exception e){
try
{
return (IMount) computerCraft_createResourceMount.invoke( null, modClass, domain, subPath );
}
catch( Exception e )
{
// It failed
}
}
@@ -158,20 +170,23 @@ public final class ComputerCraftAPI
}
/**
* Registers a peripheral handler to convert blocks into {@link IPeripheral} implementations.
* Registers a peripheral provider to convert blocks into {@link IPeripheral} implementations.
*
* @param handler The peripheral provider to register.
* @param provider The peripheral provider to register.
* @see dan200.computercraft.api.peripheral.IPeripheral
* @see dan200.computercraft.api.peripheral.IPeripheralProvider
*/
public static void registerPeripheralProvider( @Nonnull IPeripheralProvider handler )
public static void registerPeripheralProvider( @Nonnull IPeripheralProvider provider )
{
findCC();
if ( computerCraft_registerPeripheralProvider != null)
if( computerCraft_registerPeripheralProvider != null )
{
try {
computerCraft_registerPeripheralProvider.invoke( null, handler );
} catch (Exception e){
try
{
computerCraft_registerPeripheralProvider.invoke( null, provider );
}
catch( Exception e )
{
// It failed
}
}
@@ -192,9 +207,12 @@ public final class ComputerCraftAPI
findCC();
if( computerCraft_registerTurtleUpgrade != null )
{
try {
try
{
computerCraft_registerTurtleUpgrade.invoke( null, upgrade );
} catch( Exception e ) {
}
catch( Exception e )
{
// It failed
}
}
@@ -202,19 +220,22 @@ public final class ComputerCraftAPI
}
/**
* Registers a bundled redstone handler to provide bundled redstone output for blocks.
* Registers a bundled redstone provider to provide bundled redstone output for blocks.
*
* @param handler The bundled redstone provider to register.
* @param provider The bundled redstone provider to register.
* @see dan200.computercraft.api.redstone.IBundledRedstoneProvider
*/
public static void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider handler )
public static void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider )
{
findCC();
if( computerCraft_registerBundledRedstoneProvider != null )
{
try {
computerCraft_registerBundledRedstoneProvider.invoke( null, handler );
} catch (Exception e) {
try
{
computerCraft_registerBundledRedstoneProvider.invoke( null, provider );
}
catch( Exception e )
{
// It failed
}
}
@@ -235,9 +256,12 @@ public final class ComputerCraftAPI
findCC();
if( computerCraft_getDefaultBundledRedstoneOutput != null )
{
try {
return (Integer)computerCraft_getDefaultBundledRedstoneOutput.invoke( null, world, pos, side );
} catch (Exception e){
try
{
return (Integer) computerCraft_getDefaultBundledRedstoneOutput.invoke( null, world, pos, side );
}
catch( Exception e )
{
// It failed
}
}
@@ -245,40 +269,46 @@ public final class ComputerCraftAPI
}
/**
* Registers a media handler to provide {@link IMedia} implementations for Items
* Registers a media provider to provide {@link IMedia} implementations for Items
*
* @param handler The media provider to register.
* @param provider The media provider to register.
* @see dan200.computercraft.api.media.IMediaProvider
*/
public static void registerMediaProvider( @Nonnull IMediaProvider handler )
public static void registerMediaProvider( @Nonnull IMediaProvider provider )
{
findCC();
if( computerCraft_registerMediaProvider != null )
{
try {
computerCraft_registerMediaProvider.invoke( null, handler );
} catch (Exception e){
try
{
computerCraft_registerMediaProvider.invoke( null, provider );
}
catch( Exception e )
{
// It failed
}
}
}
/**
* Registers a permission handler to restrict where turtles can move or build.
* Registers a permission provider to restrict where turtles can move or build.
*
* @param handler The turtle permission provider to register.
* @param provider The turtle permission provider to register.
* @see dan200.computercraft.api.permissions.ITurtlePermissionProvider
* @deprecated Prefer using {@link dan200.computercraft.api.turtle.event.TurtleBlockEvent} or the standard Forge events.
*/
@Deprecated
public static void registerPermissionProvider( @Nonnull ITurtlePermissionProvider handler )
public static void registerPermissionProvider( @Nonnull ITurtlePermissionProvider provider )
{
findCC();
if( computerCraft_registerPermissionProvider != null )
{
try {
computerCraft_registerPermissionProvider.invoke( null, handler );
} catch (Exception e) {
try
{
computerCraft_registerPermissionProvider.invoke( null, provider );
}
catch( Exception e )
{
// It failed
}
}
@@ -287,10 +317,14 @@ public final class ComputerCraftAPI
public static void registerPocketUpgrade( @Nonnull IPocketUpgrade upgrade )
{
findCC();
if(computerCraft_registerPocketUpgrade != null) {
try {
if( computerCraft_registerPocketUpgrade != null )
{
try
{
computerCraft_registerPocketUpgrade.invoke( null, upgrade );
} catch (Exception e) {
}
catch( Exception e )
{
// It failed
}
}
@@ -309,7 +343,9 @@ public final class ComputerCraftAPI
try
{
return (IPacketNetwork) computerCraft_getWirelessNetwork.invoke( null );
} catch (Exception e) {
}
catch( Exception e )
{
// It failed;
}
}
@@ -394,12 +430,14 @@ public final class ComputerCraftAPI
private static void findCC()
{
if( !ccSearched ) {
try {
if( !ccSearched )
{
try
{
computerCraft = Class.forName( "dan200.computercraft.ComputerCraft" );
computerCraft_getVersion = findCCMethod( "getVersion", new Class<?>[]{
computerCraft_getVersion = findCCMethod( "getVersion", new Class<?>[] {
} );
computerCraft_createUniqueNumberedSaveDir = findCCMethod( "createUniqueNumberedSaveDir", new Class<?>[]{
computerCraft_createUniqueNumberedSaveDir = findCCMethod( "createUniqueNumberedSaveDir", new Class<?>[] {
World.class, String.class
} );
computerCraft_createSaveDirMount = findCCMethod( "createSaveDirMount", new Class<?>[] {
@@ -437,12 +475,16 @@ public final class ComputerCraftAPI
computerCraft_createWiredNodeForElement = findCCMethod( "createWiredNodeForElement", new Class<?>[] {
IWiredElement.class
} );
computerCraft_getWiredElementAt = findCCMethod( "getWiredElementAt", new Class<?>[]{
computerCraft_getWiredElementAt = findCCMethod( "getWiredElementAt", new Class<?>[] {
IBlockAccess.class, BlockPos.class, EnumFacing.class
} );
} catch( Exception e ) {
}
catch( Exception e )
{
System.out.println( "ComputerCraftAPI: ComputerCraft not found." );
} finally {
}
finally
{
ccSearched = true;
}
}
@@ -450,13 +492,12 @@ public final class ComputerCraftAPI
private static Method findCCMethod( String name, Class<?>[] args )
{
try {
if( computerCraft != null )
{
return computerCraft.getMethod( name, args );
}
return null;
} catch( NoSuchMethodException e ) {
try
{
return computerCraft != null ? computerCraft.getMethod( name, args ) : null;
}
catch( NoSuchMethodException e )
{
System.out.println( "ComputerCraftAPI: ComputerCraft method " + name + " not found." );
return null;
}

View File

@@ -1,3 +1,9 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. 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;

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,3 +1,9 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.lua;
import dan200.computercraft.api.filesystem.IFileSystem;

View File

@@ -1,7 +1,7 @@
/*
* 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
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. 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;

View File

@@ -1,3 +1,9 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.lua;
import dan200.computercraft.api.ComputerCraftAPI;

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,7 +1,7 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.network;

View File

@@ -1,7 +1,7 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.network;

View File

@@ -1,7 +1,7 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.network;

View File

@@ -1,7 +1,7 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.network;

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,3 +1,9 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.network.wired;
import dan200.computercraft.api.ComputerCraftAPI;

View File

@@ -1,3 +1,9 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.network.wired;
import dan200.computercraft.api.peripheral.IPeripheral;

View File

@@ -1,3 +1,9 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.network.wired;
import dan200.computercraft.api.peripheral.IPeripheral;

View File

@@ -1,3 +1,9 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.network.wired;
import dan200.computercraft.api.network.IPacketNetwork;

View File

@@ -1,3 +1,9 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.network.wired;
import dan200.computercraft.api.network.IPacketSender;

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/
@@ -39,7 +39,10 @@ public interface IComputerAccess
* @see IMount
*/
@Nullable
String mount( @Nonnull String desiredLocation, @Nonnull IMount mount );
default String mount( @Nonnull String desiredLocation, @Nonnull IMount mount )
{
return mount( desiredLocation, mount, getAttachmentName() );
}
/**
* Mount a mount onto the computer's file system in a read only mode.
@@ -75,7 +78,10 @@ public interface IComputerAccess
* @see IMount
*/
@Nullable
String mountWritable( @Nonnull String desiredLocation, @Nonnull IWritableMount mount );
default String mountWritable( @Nonnull String desiredLocation, @Nonnull IWritableMount mount )
{
return mountWritable( desiredLocation, mount, getAttachmentName() );
}
/**
* Mount a mount onto the computer's file system in a writable mode.

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,3 +1,9 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.pocket;
import dan200.computercraft.api.peripheral.IPeripheral;

View File

@@ -1,3 +1,9 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.pocket;
import dan200.computercraft.api.ComputerCraftAPI;

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,3 +1,9 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle.event;
import dan200.computercraft.api.turtle.ITurtleAccess;

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,3 +1,9 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle.event;
import dan200.computercraft.api.turtle.ITurtleAccess;

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -1,6 +1,6 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2019. 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.
*/

View File

@@ -0,0 +1,81 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client;
import dan200.computercraft.shared.command.text.ChatHelpers;
import dan200.computercraft.shared.command.text.TableBuilder;
import dan200.computercraft.shared.command.text.TableFormatter;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiNewChat;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextFormatting;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nullable;
public class ClientTableFormatter implements TableFormatter
{
public static final ClientTableFormatter INSTANCE = new ClientTableFormatter();
private static Int2IntOpenHashMap lastHeights = new Int2IntOpenHashMap();
private FontRenderer renderer()
{
return Minecraft.getMinecraft().fontRenderer;
}
@Override
@Nullable
public ITextComponent getPadding( ITextComponent component, int width )
{
int extraWidth = width - getWidth( component );
if( extraWidth <= 0 ) return null;
FontRenderer renderer = renderer();
float spaceWidth = renderer.getCharWidth( ' ' );
int spaces = MathHelper.floor( extraWidth / spaceWidth );
int extra = extraWidth - (int) (spaces * spaceWidth);
return ChatHelpers.coloured( StringUtils.repeat( ' ', spaces ) + StringUtils.repeat( (char) 712, extra ), TextFormatting.GRAY );
}
@Override
public int getColumnPadding()
{
return 3;
}
@Override
public int getWidth( ITextComponent component )
{
return renderer().getStringWidth( component.getFormattedText() );
}
@Override
public void writeLine( int id, ITextComponent component )
{
Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessageWithOptionalDeletion( component, id );
}
@Override
public int display( TableBuilder table )
{
GuiNewChat chat = Minecraft.getMinecraft().ingameGUI.getChatGUI();
int lastHeight = lastHeights.get( table.getId() );
int height = TableFormatter.super.display( table );
lastHeights.put( table.getId(), height );
for( int i = height; i < lastHeight; i++ ) chat.deleteChatLine( i + table.getId() );
return height;
}
}

View File

@@ -0,0 +1,49 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
public class FrameInfo
{
private static final FrameInfo instance = new FrameInfo();
public static FrameInfo instance()
{
return instance;
}
private int tick;
private long renderFrame;
private FrameInfo()
{
}
public boolean getGlobalCursorBlink()
{
return (tick / 8) % 2 == 0;
}
public long getRenderFrame()
{
return renderFrame;
}
@SubscribeEvent
public void onTick( TickEvent.ClientTickEvent event )
{
if( event.phase == TickEvent.Phase.START ) tick++;
}
@SubscribeEvent
public void onRenderTick( TickEvent.RenderTickEvent event )
{
if( event.phase == TickEvent.Phase.START ) renderFrame++;
}
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -8,6 +8,7 @@ package dan200.computercraft.client.gui;
import dan200.computercraft.core.terminal.TextBuffer;
import dan200.computercraft.shared.util.Palette;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
@@ -20,22 +21,30 @@ import java.util.Arrays;
public class FixedWidthFontRenderer
{
private static ResourceLocation font = new ResourceLocation( "computercraft", "textures/gui/term_font.png" );
public static ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/term_background.png" );
private static final ResourceLocation FONT = new ResourceLocation( "computercraft", "textures/gui/term_font.png" );
public static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/term_background.png" );
public static int FONT_HEIGHT = 9;
public static int FONT_WIDTH = 6;
public static final int FONT_HEIGHT = 9;
public static final int FONT_WIDTH = 6;
private TextureManager m_textureManager;
private static FixedWidthFontRenderer instance;
public FixedWidthFontRenderer( TextureManager textureManager )
public static FixedWidthFontRenderer instance()
{
m_textureManager = textureManager;
if( instance != null ) return instance;
return instance = new FixedWidthFontRenderer();
}
private final TextureManager m_textureManager;
private FixedWidthFontRenderer()
{
m_textureManager = Minecraft.getMinecraft().getTextureManager();
}
private static void greyscaleify( double[] rgb )
{
Arrays.fill( rgb, ( rgb[0] + rgb[1] + rgb[2] ) / 3.0f );
Arrays.fill( rgb, (rgb[0] + rgb[1] + rgb[2]) / 3.0f );
}
private void drawChar( BufferBuilder renderer, double x, double y, int index, int color, Palette p, boolean greyscale )
@@ -44,13 +53,13 @@ public class FixedWidthFontRenderer
int row = index / 16;
double[] colour = p.getColour( 15 - color );
if(greyscale)
if( greyscale )
{
greyscaleify( colour );
}
float r = (float)colour[0];
float g = (float)colour[1];
float b = (float)colour[2];
float r = (float) colour[0];
float g = (float) colour[1];
float b = (float) colour[2];
int xStart = 1 + column * (FONT_WIDTH + 2);
int yStart = 1 + row * (FONT_HEIGHT + 2);
@@ -66,13 +75,13 @@ public class FixedWidthFontRenderer
private void drawQuad( BufferBuilder renderer, double x, double y, int color, double width, Palette p, boolean greyscale )
{
double[] colour = p.getColour( 15 - color );
if(greyscale)
if( greyscale )
{
greyscaleify( colour );
}
float r = (float)colour[0];
float g = (float)colour[1];
float b = (float)colour[2];
float r = (float) colour[0];
float g = (float) colour[1];
float b = (float) colour[2];
renderer.pos( x, y, 0.0 ).color( r, g, b, 1.0f ).endVertex();
renderer.pos( x, y + FONT_HEIGHT, 0.0 ).color( r, g, b, 1.0f ).endVertex();
@@ -96,7 +105,7 @@ public class FixedWidthFontRenderer
if( leftMarginSize > 0.0 )
{
int colour1 = "0123456789abcdef".indexOf( backgroundColour.charAt( 0 ) );
if( colour1 < 0 || (greyScale && !isGreyScale(colour1)) )
if( colour1 < 0 || (greyScale && !isGreyScale( colour1 )) )
{
colour1 = 15;
}
@@ -105,7 +114,7 @@ public class FixedWidthFontRenderer
if( rightMarginSize > 0.0 )
{
int colour2 = "0123456789abcdef".indexOf( backgroundColour.charAt( backgroundColour.length() - 1 ) );
if( colour2 < 0 || (greyScale && !isGreyScale(colour2)) )
if( colour2 < 0 || (greyScale && !isGreyScale( colour2 )) )
{
colour2 = 15;
}
@@ -114,7 +123,7 @@ public class FixedWidthFontRenderer
for( int i = 0; i < backgroundColour.length(); i++ )
{
int colour = "0123456789abcdef".indexOf( backgroundColour.charAt( i ) );
if( colour < 0 || ( greyScale && !isGreyScale( colour ) ) )
if( colour < 0 || (greyScale && !isGreyScale( colour )) )
{
colour = 15;
}
@@ -135,7 +144,7 @@ public class FixedWidthFontRenderer
{
// Switch colour
int colour = "0123456789abcdef".indexOf( textColour.charAt( i ) );
if( colour < 0 || ( greyScale && !isGreyScale( colour ) ) )
if( colour < 0 || (greyScale && !isGreyScale( colour )) )
{
colour = 0;
}
@@ -157,26 +166,26 @@ public class FixedWidthFontRenderer
if( backgroundColour != null )
{
// Bind the background texture
m_textureManager.bindTexture( background );
m_textureManager.bindTexture( BACKGROUND );
// Draw the quads
drawStringBackgroundPart( x, y, backgroundColour, leftMarginSize, rightMarginSize, greyScale, p );
}
// Draw text
if( s != null && textColour != null )
{
// Bind the font texture
bindFont();
// Draw the quads
drawStringTextPart( x, y, s, textColour, greyScale, p );
}
}
public int getStringWidth(String s)
public int getStringWidth( String s )
{
if(s == null)
if( s == null )
{
return 0;
}
@@ -185,7 +194,7 @@ public class FixedWidthFontRenderer
public void bindFont()
{
m_textureManager.bindTexture( font );
m_textureManager.bindTexture( FONT );
GlStateManager.glTexParameteri( GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP );
}
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -9,6 +9,7 @@ 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.ClientComputer;
import dan200.computercraft.shared.computer.core.ComputerFamily;
import dan200.computercraft.shared.computer.core.IComputer;
import dan200.computercraft.shared.computer.inventory.ContainerComputer;
@@ -23,17 +24,17 @@ 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/corners_advanced.png" );
private static final ResourceLocation backgroundCommand = new ResourceLocation( "computercraft", "textures/gui/corners_command.png" );
private static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/corners.png" );
private static final ResourceLocation BACKGROUND_ADVANCED = new ResourceLocation( "computercraft", "textures/gui/corners_advanced.png" );
private static final ResourceLocation BACKGROUND_COMMAND = new ResourceLocation( "computercraft", "textures/gui/corners_command.png" );
private final ComputerFamily m_family;
private final IComputer m_computer;
private final ClientComputer m_computer;
private final int m_termWidth;
private final int m_termHeight;
private WidgetTerminal m_terminal;
public GuiComputer( Container container, ComputerFamily family, IComputer computer, int termWidth, int termHeight )
public GuiComputer( Container container, ComputerFamily family, ClientComputer computer, int termWidth, int termHeight )
{
super( container );
m_family = family;
@@ -43,12 +44,18 @@ public class GuiComputer extends GuiContainer
m_terminal = null;
}
@Deprecated
public GuiComputer( Container container, ComputerFamily family, IComputer computer, int termWidth, int termHeight )
{
this( container, family, (ClientComputer) computer, termWidth, termHeight );
}
public GuiComputer( TileComputer computer )
{
this(
new ContainerComputer( computer ),
computer.getFamily(),
computer.createComputer(),
computer.createClientComputer(),
ComputerCraft.terminalWidth_computer,
ComputerCraft.terminalHeight_computer
);
@@ -87,7 +94,7 @@ public class GuiComputer extends GuiContainer
}
@Override
protected void keyTyped(char c, int k) throws IOException
protected void keyTyped( char c, int k ) throws IOException
{
if( k == 1 )
{
@@ -95,7 +102,7 @@ public class GuiComputer extends GuiContainer
}
else
{
if( m_terminal.keyTyped( c, k ) ) keyHandled = true;
if( m_terminal.onKeyTyped( c, k ) ) keyHandled = true;
}
}
@@ -123,11 +130,11 @@ public class GuiComputer extends GuiContainer
public void handleKeyboardInput() throws IOException
{
super.handleKeyboardInput();
if( m_terminal.handleKeyboardInput() ) keyHandled = true;
if( m_terminal.onKeyboardInput() ) keyHandled = true;
}
@Override
protected void drawGuiContainerForegroundLayer(int par1, int par2)
protected void drawGuiContainerForegroundLayer( int par1, int par2 )
{
}
@@ -148,9 +155,9 @@ public class GuiComputer extends GuiContainer
// Draw background
drawDefaultBackground();
// Draw terminal
// 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 )
@@ -158,30 +165,30 @@ public class GuiComputer extends GuiContainer
case Normal:
default:
{
this.mc.getTextureManager().bindTexture( background );
this.mc.getTextureManager().bindTexture( BACKGROUND );
break;
}
case Advanced:
{
this.mc.getTextureManager().bindTexture( backgroundAdvanced );
this.mc.getTextureManager().bindTexture( BACKGROUND_ADVANCED );
break;
}
case Command:
{
this.mc.getTextureManager().bindTexture( backgroundCommand );
this.mc.getTextureManager().bindTexture( BACKGROUND_COMMAND );
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 - 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, 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);
drawTexturedModalRect( startX - 12, startY, 0, 28, 12, endY - startY );
drawTexturedModalRect( endX, startY, 36, 28, 12, endY - startY );
}
}

View File

@@ -1,34 +1,25 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.gui;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.shared.Config;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.fml.client.IModGuiFactory;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.IConfigElement;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class GuiConfigCC extends GuiConfig
{
public GuiConfigCC( GuiScreen parentScreen )
{
super( parentScreen, getConfigElements(), ComputerCraft.MOD_ID, false, false, "CC: Tweaked" );
}
private static List<IConfigElement> getConfigElements()
{
ArrayList<IConfigElement> elements = new ArrayList<>();
for (Property property : ComputerCraft.Config.config.getCategory( Configuration.CATEGORY_GENERAL ).getOrderedValues())
{
elements.add( new ConfigElement( property ) );
}
return elements;
super( parentScreen, Config.getConfigElements(), ComputerCraft.MOD_ID, false, false, "CC: Tweaked" );
}
public static class Factory

View File

@@ -1,54 +1,52 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. 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 static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/diskdrive.png" );
private TileDiskDrive m_diskDrive;
private final ContainerDiskDrive m_container;
public GuiDiskDrive( InventoryPlayer inventoryplayer, TileDiskDrive diskDrive )
public GuiDiskDrive( ContainerDiskDrive container )
{
super( new ContainerDiskDrive(inventoryplayer, diskDrive) );
m_diskDrive = diskDrive;
super( container );
m_container = container;
}
@Override
protected void drawGuiContainerForegroundLayer(int par1, int par2)
protected void drawGuiContainerForegroundLayer( int par1, int par2 )
{
String title = m_diskDrive.getDisplayName().getUnformattedText();
fontRenderer.drawString( title, (xSize - fontRenderer.getStringWidth(title)) / 2, 6, 0x404040 );
fontRenderer.drawString( I18n.format("container.inventory"), 8, (ySize - 96) + 2, 0x404040 );
String title = m_container.getDiskDrive().getDisplayName().getUnformattedText();
fontRenderer.drawString( title, (xSize - fontRenderer.getStringWidth( title )) / 2, 6, 0x404040 );
fontRenderer.drawString( I18n.format( "container.inventory" ), 8, (ySize - 96) + 2, 0x404040 );
}
@Override
protected void drawGuiContainerBackgroundLayer(float f, int i, int j)
protected void drawGuiContainerBackgroundLayer( float f, int i, int j )
{
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
this.mc.getTextureManager().bindTexture( background );
this.mc.getTextureManager().bindTexture( BACKGROUND );
int l = (width - xSize) / 2;
int i1 = (height - ySize) / 2;
drawTexturedModalRect(l, i1, 0, 0, xSize, ySize);
drawTexturedModalRect( l, i1, 0, 0, xSize, ySize );
}
@Override
public void drawScreen( int mouseX, int mouseY, float partialTicks)
public void drawScreen( int mouseX, int mouseY, float partialTicks )
{
drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
renderHoveredToolTip(mouseX, mouseY);
super.drawScreen( mouseX, mouseY, partialTicks );
renderHoveredToolTip( mouseX, mouseY );
}
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/

View File

@@ -1,62 +1,58 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. 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;
private static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/printer.png" );
public GuiPrinter(InventoryPlayer inventoryplayer, TilePrinter printer)
private final ContainerPrinter m_container;
public GuiPrinter( ContainerPrinter container )
{
super(new ContainerPrinter(inventoryplayer, printer));
m_printer = printer;
m_container = (ContainerPrinter)inventorySlots;
super( container );
m_container = container;
}
@Override
protected void drawGuiContainerForegroundLayer(int par1, int par2)
protected void drawGuiContainerForegroundLayer( int par1, int par2 )
{
String title = m_printer.getDisplayName().getUnformattedText();
fontRenderer.drawString( title, (xSize - fontRenderer.getStringWidth(title)) / 2, 6, 0x404040 );
fontRenderer.drawString( I18n.format("container.inventory"), 8, (ySize - 96) + 2, 0x404040 );
String title = m_container.getPrinter().getDisplayName().getUnformattedText();
fontRenderer.drawString( title, (xSize - fontRenderer.getStringWidth( title )) / 2, 6, 0x404040 );
fontRenderer.drawString( I18n.format( "container.inventory" ), 8, (ySize - 96) + 2, 0x404040 );
}
@Override
protected void drawGuiContainerBackgroundLayer(float f, int i, int j)
protected void drawGuiContainerBackgroundLayer( float f, int i, int j )
{
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
this.mc.getTextureManager().bindTexture( background );
this.mc.getTextureManager().bindTexture( BACKGROUND );
int startX = (width - xSize) / 2;
int startY = (height - ySize) / 2;
drawTexturedModalRect(startX, startY, 0, 0, xSize, ySize);
drawTexturedModalRect( startX, startY, 0, 0, xSize, ySize );
boolean printing = m_container.isPrinting();
if( printing )
{
drawTexturedModalRect(startX + 34, startY + 21, 176, 0, 25, 45);
drawTexturedModalRect( startX + 34, startY + 21, 176, 0, 25, 45 );
}
}
@Override
public void drawScreen( int mouseX, int mouseY, float partialTicks)
public void drawScreen( int mouseX, int mouseY, float partialTicks )
{
drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
renderHoveredToolTip(mouseX, mouseY);
super.drawScreen( mouseX, mouseY, partialTicks );
renderHoveredToolTip( mouseX, mouseY );
}
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -30,42 +30,24 @@ public class GuiPrintout extends GuiContainer
super( container );
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 ] );
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_colours = new TextBuffer[colours.length];
for( int i = 0; i < m_colours.length; i++ ) m_colours[i] = new TextBuffer( colours[i] );
m_page = 0;
m_pages = Math.max( m_text.length / ItemPrintout.LINES_PER_PAGE, 1 );
m_book = ItemPrintout.getType( container.getStack() ) == ItemPrintout.Type.Book;
}
@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
{

View File

@@ -1,24 +1,21 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. 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.ClientComputer;
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.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;
@@ -26,32 +23,23 @@ 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/turtle_advanced.png" );
protected World m_world;
protected ContainerTurtle m_container;
private static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/turtle.png" );
private static final ResourceLocation BACKGROUND_ADVANCED = new ResourceLocation( "computercraft", "textures/gui/turtle_advanced.png" );
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() ) );
}
private ContainerTurtle m_container;
protected GuiTurtle( World world, TileTurtle turtle, ContainerTurtle container )
private final ComputerFamily m_family;
private final ClientComputer m_computer;
private WidgetTerminal m_terminalGui;
public GuiTurtle( TileTurtle turtle, ContainerTurtle container )
{
super( container );
m_world = world;
m_container = container;
m_family = turtle.getFamily();
m_turtle = turtle.getAccess();
m_computer = turtle.createComputer();
m_computer = turtle.getClientComputer();
xSize = 254;
ySize = 217;
}
@@ -60,10 +48,10 @@ public class GuiTurtle extends GuiContainer
public void initGui()
{
super.initGui();
Keyboard.enableRepeatEvents(true);
Keyboard.enableRepeatEvents( true );
m_terminalGui = new WidgetTerminal(
( width - xSize ) / 2 + 8,
( height - ySize ) / 2 + 8,
(width - xSize) / 2 + 8,
(height - ySize) / 2 + 8,
ComputerCraft.terminalWidth_turtle,
ComputerCraft.terminalHeight_turtle,
() -> m_computer,
@@ -76,7 +64,7 @@ public class GuiTurtle extends GuiContainer
public void onGuiClosed()
{
super.onGuiClosed();
Keyboard.enableRepeatEvents(false);
Keyboard.enableRepeatEvents( false );
}
@Override
@@ -87,7 +75,7 @@ public class GuiTurtle extends GuiContainer
}
@Override
protected void keyTyped(char c, int k) throws IOException
protected void keyTyped( char c, int k ) throws IOException
{
if( k == 1 )
{
@@ -95,17 +83,17 @@ public class GuiTurtle extends GuiContainer
}
else
{
if( m_terminalGui.keyTyped( c, k ) ) keyHandled = true;
if( m_terminalGui.onKeyTyped( c, k ) ) keyHandled = true;
}
}
@Override
protected void mouseClicked(int x, int y, int button) throws IOException
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
{
@@ -119,23 +107,23 @@ public class GuiTurtle extends GuiContainer
public void handleKeyboardInput() throws IOException
{
super.handleKeyboardInput();
if( m_terminalGui.handleKeyboardInput() ) keyHandled = true;
if( m_terminalGui.onKeyboardInput() ) keyHandled = true;
}
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);
int slotX = (slot % 4);
int slotY = (slot / 4);
this.mc.getTextureManager().bindTexture( advanced ? BACKGROUND_ADVANCED : BACKGROUND );
drawTexturedModalRect( x + m_container.m_turtleInvStartX - 2 + slotX * 18, y + m_container.m_playerInvStartY - 2 + slotY * 18, 0, 217, 24, 24 );
}
}
@@ -145,22 +133,22 @@ public class GuiTurtle extends GuiContainer
// 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 );
this.mc.getTextureManager().bindTexture( advanced ? BACKGROUND_ADVANCED : BACKGROUND );
int x = (width - xSize) / 2;
int y = (height - ySize) / 2;
drawTexturedModalRect(x, y, 0, 0, xSize, ySize);
drawTexturedModalRect( x, y, 0, 0, xSize, ySize );
drawSelectionSlot( advanced );
}
@Override
public void drawScreen( int mouseX, int mouseY, float partialTicks)
public void drawScreen( int mouseX, int mouseY, float partialTicks )
{
drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
renderHoveredToolTip(mouseX, mouseY);
super.drawScreen( mouseX, mouseY, partialTicks );
renderHoveredToolTip( mouseX, mouseY );
}
}

View File

@@ -1,22 +1,13 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. 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.*;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import javax.annotation.Nonnull;
public abstract class Widget extends Gui
{
@@ -65,17 +56,29 @@ public abstract class Widget extends Gui
{
}
public boolean handleKeyboardInput()
public boolean onKeyboardInput()
{
return false;
}
@Deprecated
public void handleKeyboardInput()
{
onKeyboardInput();
}
public void mouseClicked( int mouseX, int mouseY, int mouseButton )
{
}
public boolean keyTyped( char c, int k )
public boolean onKeyTyped( char c, int k )
{
return false;
}
@Deprecated
public void keyTyped( char c, int k )
{
onKeyTyped( c, k );
}
}

View File

@@ -1,12 +1,12 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. 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.FrameInfo;
import dan200.computercraft.client.gui.FixedWidthFontRenderer;
import dan200.computercraft.core.terminal.Terminal;
import dan200.computercraft.core.terminal.TextBuffer;
@@ -18,15 +18,15 @@ 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;
import static dan200.computercraft.client.gui.FixedWidthFontRenderer.BACKGROUND;
public class WidgetTerminal extends Widget
{
private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/term_background.png" );
private static final float TERMINATE_TIME = 0.5f;
private final IComputerContainer m_computer;
@@ -84,7 +84,7 @@ public class WidgetTerminal extends Widget
}
@Override
public boolean keyTyped( char ch, int key )
public boolean onKeyTyped( char ch, int key )
{
if( m_focus )
{
@@ -122,8 +122,8 @@ public class WidgetTerminal extends Widget
}
// Queue the "paste" event
queueEvent( "paste", new Object[]{
clipboard
queueEvent( "paste", new Object[] {
clipboard
} );
}
}
@@ -143,7 +143,7 @@ public class WidgetTerminal extends Widget
}
// Queue the "key" event
queueEvent( "key", new Object[]{
queueEvent( "key", new Object[] {
key, repeat
} );
handled = true;
@@ -152,7 +152,7 @@ public class WidgetTerminal extends Widget
if( (ch >= 32 && ch <= 126) || (ch >= 160 && ch <= 255) ) // printable chars in byte range
{
// Queue the "char" event
queueEvent( "char", new Object[]{
queueEvent( "char", new Object[] {
Character.toString( ch )
} );
handled = true;
@@ -161,7 +161,7 @@ public class WidgetTerminal extends Widget
return handled;
}
}
return false;
}
@@ -171,7 +171,7 @@ public class WidgetTerminal extends Widget
if( mouseX >= getXPosition() && mouseX < getXPosition() + getWidth() &&
mouseY >= getYPosition() && mouseY < getYPosition() + getHeight() )
{
if( !m_focus && button == 0)
if( !m_focus && button == 0 )
{
m_focus = true;
}
@@ -184,12 +184,12 @@ public class WidgetTerminal extends Widget
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;
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[]{
computer.queueEvent( "mouse_click", new Object[] {
button + 1, charX + 1, charY + 1
} );
@@ -210,7 +210,7 @@ public class WidgetTerminal extends Widget
}
@Override
public boolean handleKeyboardInput()
public boolean onKeyboardInput()
{
boolean handled = false;
for( int i = m_keysDown.size() - 1; i >= 0; --i )
@@ -222,7 +222,7 @@ public class WidgetTerminal extends Widget
if( m_focus )
{
// Queue the "key_up" event
queueEvent( "key_up", new Object[]{
queueEvent( "key_up", new Object[] {
key
} );
handled = true;
@@ -244,8 +244,8 @@ public class WidgetTerminal extends Widget
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;
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 );
@@ -253,7 +253,7 @@ public class WidgetTerminal extends Widget
{
if( m_focus )
{
computer.queueEvent( "mouse_up", new Object[]{
computer.queueEvent( "mouse_up", new Object[] {
m_lastClickButton + 1, charX + 1, charY + 1
} );
}
@@ -270,20 +270,20 @@ public class WidgetTerminal extends Widget
{
if( wheelChange < 0 )
{
computer.queueEvent( "mouse_scroll", new Object[]{
1, charX + 1, charY + 1
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
computer.queueEvent( "mouse_scroll", new Object[] {
-1, charX + 1, charY + 1
} );
}
if( m_lastClickButton >= 0 && ( charX != m_lastClickX || charY != m_lastClickY ) )
if( m_lastClickButton >= 0 && (charX != m_lastClickX || charY != m_lastClickY) )
{
computer.queueEvent( "mouse_drag", new Object[]{
computer.queueEvent( "mouse_drag", new Object[] {
m_lastClickButton + 1, charX + 1, charY + 1
} );
m_lastClickX = charX;
@@ -296,10 +296,10 @@ public class WidgetTerminal extends Widget
@Override
public void update()
{
{
// Handle special keys
if( m_focus && (Keyboard.isKeyDown( 29 ) || Keyboard.isKeyDown( 157 )) )
{
{
// Ctrl+T for terminate
if( Keyboard.isKeyDown( 20 ) )
{
@@ -316,9 +316,9 @@ public class WidgetTerminal extends Widget
{
m_terminateTimer = 0.0f;
}
// Ctrl+R for reboot
if( Keyboard.isKeyDown(19) )
if( Keyboard.isKeyDown( 19 ) )
{
if( m_rebootTimer < TERMINATE_TIME )
{
@@ -339,7 +339,7 @@ public class WidgetTerminal extends Widget
}
// Ctrl+S for shutdown
if( Keyboard.isKeyDown(31) )
if( Keyboard.isKeyDown( 31 ) )
{
if( m_shutdownTimer < TERMINATE_TIME )
{
@@ -377,7 +377,7 @@ public class WidgetTerminal extends Widget
{
// Draw the screen contents
IComputer computer = m_computer.getComputer();
Terminal terminal = ( computer != null ) ? computer.getTerminal() : null;
Terminal terminal = (computer != null) ? computer.getTerminal() : null;
if( terminal != null )
{
// Draw the terminal
@@ -387,8 +387,8 @@ public class WidgetTerminal extends Widget
// 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();
FixedWidthFontRenderer fontRenderer = FixedWidthFontRenderer.instance();
boolean tblink = m_focus && terminal.getCursorBlink() && FrameInfo.instance().getGlobalCursorBlink();
int tw = terminal.getWidth();
int th = terminal.getHeight();
int tx = terminal.getCursorX();
@@ -405,11 +405,11 @@ public class WidgetTerminal extends Widget
}
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, palette );
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, palette );
}
// Draw lines
for( int line = 0; line < th; ++line )
for( int line = 0; line < th; line++ )
{
TextBuffer text = terminal.getLine( line );
TextBuffer colour = terminal.getTextColourLine( line );
@@ -424,25 +424,27 @@ public class WidgetTerminal extends Widget
TextBuffer cursorColour = new TextBuffer( "0123456789abcdef".charAt( terminal.getTextColour() ), 1 );
fontRenderer.drawString(
cursor,
x + FixedWidthFontRenderer.FONT_WIDTH * tx,
startY + m_topMargin + FixedWidthFontRenderer.FONT_HEIGHT * ty,
cursorColour, null,
0, 0,
greyscale,
palette
cursor,
x + FixedWidthFontRenderer.FONT_WIDTH * tx,
startY + m_topMargin + FixedWidthFontRenderer.FONT_HEIGHT * ty,
cursorColour, null,
0, 0,
greyscale,
palette
);
}
} else
}
else
{
// Draw a black background
mc.getTextureManager().bindTexture( 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
}
finally
{
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -11,7 +11,6 @@ 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 dan200.computercraft.shared.turtle.items.ItemTurtleBase;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
@@ -36,17 +35,16 @@ import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import javax.annotation.Nonnull;
public class CCTurtleProxyClient extends CCTurtleProxyCommon
{
// IComputerCraftProxy implementation
@Override
@Override
public void preInit()
{
{
super.preInit();
// Setup client forge handlers
@@ -102,7 +100,7 @@ public class CCTurtleProxyClient extends CCTurtleProxyCommon
private void registerItemModel( Item item, ItemMeshDefinition definition, String[] names )
{
ResourceLocation[] resources = new ResourceLocation[names.length];
for( int i=0; i<names.length; ++i )
for( int i = 0; i < names.length; i++ )
{
resources[i] = new ResourceLocation( "computercraft:" + names[i] );
}
@@ -141,20 +139,11 @@ public class CCTurtleProxyClient extends CCTurtleProxyCommon
IResourceManager resourceManager = Minecraft.getMinecraft().getResourceManager();
if( resourceManager instanceof SimpleReloadableResourceManager )
{
SimpleReloadableResourceManager reloadableResourceManager = (SimpleReloadableResourceManager)resourceManager;
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 )
{

View File

@@ -1,92 +1,54 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. 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.ClientTableFormatter;
import dan200.computercraft.client.FrameInfo;
import dan200.computercraft.client.render.*;
import dan200.computercraft.shared.command.CommandCopy;
import dan200.computercraft.shared.command.ContainerViewComputer;
import dan200.computercraft.shared.computer.blocks.ComputerState;
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.core.IComputer;
import dan200.computercraft.shared.computer.items.ItemComputer;
import dan200.computercraft.shared.media.inventory.ContainerHeldItem;
import dan200.computercraft.shared.command.text.TableBuilder;
import dan200.computercraft.shared.media.items.ItemDiskLegacy;
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.modem.TileCable;
import dan200.computercraft.shared.peripheral.modem.wired.TileCable;
import dan200.computercraft.shared.peripheral.monitor.ClientMonitor;
import dan200.computercraft.shared.peripheral.monitor.TileMonitor;
import dan200.computercraft.shared.peripheral.printer.TilePrinter;
import dan200.computercraft.shared.pocket.inventory.ContainerPocketComputer;
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 dan200.computercraft.shared.util.Colour;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiNewChat;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.color.IItemColor;
import net.minecraft.client.util.ITooltipFlag;
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.util.EnumHand;
import net.minecraft.util.IThreadListener;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.World;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderHandEvent;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
{
private static Int2IntOpenHashMap lastCounts = new Int2IntOpenHashMap();
private long m_tick;
private long m_renderFrame;
private FixedWidthFontRenderer m_fixedWidthFontRenderer;
// IComputerCraftProxy implementation
@Override
public void preInit()
{
super.preInit();
m_tick = 0;
m_renderFrame = 0;
// Setup client forge handlers
registerForgeHandlers();
@@ -99,20 +61,7 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
public void registerModels( ModelRegistryEvent event )
{
// Register item models
registerItemModel( ComputerCraft.Blocks.computer, new ItemMeshDefinition()
{
private ModelResourceLocation computer = new ModelResourceLocation( "computercraft:computer", "inventory" );
private ModelResourceLocation advanced_computer = new ModelResourceLocation( "computercraft:advanced_computer", "inventory" );
@Nonnull
@Override
public ModelResourceLocation getModelLocation( @Nonnull ItemStack stack )
{
ItemComputer itemComputer = (ItemComputer) stack.getItem();
ComputerFamily family = itemComputer.getFamily( stack.getItemDamage() );
return ( family == ComputerFamily.Advanced ) ? advanced_computer : computer;
}
}, new String[]{ "computer", "advanced_computer" } );
registerItemModel( ComputerCraft.Blocks.computer, "computer" );
registerItemModel( ComputerCraft.Blocks.peripheral, 0, "peripheral" );
registerItemModel( ComputerCraft.Blocks.peripheral, 1, "wireless_modem" );
registerItemModel( ComputerCraft.Blocks.peripheral, 2, "monitor" );
@@ -131,72 +80,7 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
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:pocket_computer", "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 advanced_pocket_computer_off = new ModelResourceLocation( "computercraft:advanced_pocket_computer", "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 colour_pocket_computer_off = new ModelResourceLocation( "computercraft:pocket_computer_colour", "inventory" );
private ModelResourceLocation colour_pocket_computer_on = new ModelResourceLocation( "computercraft:pocket_computer_colour_on", "inventory" );
private ModelResourceLocation colour_pocket_computer_blinking = new ModelResourceLocation( "computercraft:pocket_computer_colour_blinking", "inventory" );
@Nonnull
@Override
public ModelResourceLocation getModelLocation( @Nonnull ItemStack stack )
{
ItemPocketComputer itemPocketComputer = (ItemPocketComputer) stack.getItem();
ComputerState state = itemPocketComputer.getState( stack );
if( itemPocketComputer.getColour( stack ) == -1 )
{
switch( itemPocketComputer.getFamily( stack ) )
{
case Advanced:
switch( state )
{
case Off:
default:
return advanced_pocket_computer_off;
case On:
return advanced_pocket_computer_on;
case Blinking:
return advanced_pocket_computer_blinking;
}
case Normal:
default:
switch( state )
{
case Off:
default:
return pocket_computer_off;
case On:
return pocket_computer_on;
case Blinking:
return pocket_computer_blinking;
}
}
}
else
{
switch( state )
{
case Off:
default:
return colour_pocket_computer_off;
case On:
return colour_pocket_computer_on;
case Blinking:
return colour_pocket_computer_blinking;
}
}
}
}, new String[] {
"pocket_computer", "pocket_computer_on", "pocket_computer_blinking",
"advanced_pocket_computer", "advanced_pocket_computer_on", "advanced_pocket_computer_blinking",
"pocket_computer_colour", "pocket_computer_colour_on", "pocket_computer_colour_blinking",
} );
registerItemModel( ComputerCraft.Items.pocketComputer, "pocket_computer" );
}
@Override
@@ -206,7 +90,6 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
// Load textures
Minecraft mc = Minecraft.getMinecraft();
m_fixedWidthFontRenderer = new FixedWidthFontRenderer( mc.getTextureManager() );
// Setup
mc.getItemColors().registerItemColorHandler( new DiskColorHandler( ComputerCraft.Items.disk ), ComputerCraft.Items.disk );
@@ -271,322 +154,37 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
} );
}
private void registerItemModel( Block block, ItemMeshDefinition definition, String[] names )
{
registerItemModel( Item.getItemFromBlock( block ), definition, names );
}
private void registerItemModel( Item item, ItemMeshDefinition definition, String[] names )
{
ResourceLocation[] resources = new ResourceLocation[names.length];
for( int i=0; i<resources.length; ++i )
{
resources[i] = new ResourceLocation( "computercraft", names[i] );
}
ModelBakery.registerItemVariants( item, resources );
ModelLoader.setCustomMeshDefinition( 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 Object getFixedWidthFontRenderer()
{
return m_fixedWidthFontRenderer;
}
@Override
public String getRecordInfo( @Nonnull ItemStack recordStack )
{
List<String> info = new ArrayList<>( 1 );
recordStack.getItem().addInformation( recordStack, null, info, ITooltipFlag.TooltipFlags.NORMAL );
if( info.size() > 0 ) {
return info.get( 0 );
} else {
return super.getRecordInfo( recordStack );
}
}
@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( EntityPlayer player, EnumHand hand )
{
ContainerHeldItem container = new ContainerHeldItem( player, hand );
if( container.getStack().getItem() instanceof ItemPrintout )
{
return new GuiPrintout( container );
}
return null;
}
@Override
public Object getPocketComputerGUI( EntityPlayer player, EnumHand hand )
{
ContainerPocketComputer container = new ContainerPocketComputer( player, hand );
if( container.getStack().getItem() instanceof ItemPocketComputer )
{
return new GuiPocketComputer( container );
}
return null;
}
@Override
public Object getComputerGUI( IComputer computer, int width, int height, ComputerFamily family )
{
ContainerViewComputer container = new ContainerViewComputer( computer );
return new GuiComputer( container, family, computer, width, height );
}
@Override
public File getWorldDir( World world )
{
return world.getSaveHandler().getWorldDirectory();
}
@Override
public void handlePacket( final ComputerCraftPacket packet, final EntityPlayer player )
{
switch( packet.m_packetType )
{
case ComputerCraftPacket.ComputerChanged:
case ComputerCraftPacket.ComputerTerminalChanged:
case ComputerCraftPacket.ComputerDeleted:
case ComputerCraftPacket.PlayRecord:
case ComputerCraftPacket.PostChat:
{
// Packet from Server to Client
IThreadListener listener = Minecraft.getMinecraft();
if( listener != null )
{
if( listener.isCallingFromMinecraftThread() )
{
processPacket( packet, player );
}
else
{
listener.addScheduledTask( () -> 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:
case ComputerCraftPacket.ComputerTerminalChanged:
{
int instanceID = packet.m_dataInt[ 0 ];
if( !ComputerCraft.clientComputerRegistry.contains( instanceID ) )
{
ComputerCraft.clientComputerRegistry.add( instanceID, new ClientComputer( instanceID ) );
}
ComputerCraft.clientComputerRegistry.get( instanceID ).handlePacket( packet, player );
break;
}
case ComputerCraftPacket.ComputerDeleted:
{
int instanceID = packet.m_dataInt[ 0 ];
if( ComputerCraft.clientComputerRegistry.contains( instanceID ) )
{
ComputerCraft.clientComputerRegistry.remove( instanceID );
}
break;
}
case ComputerCraftPacket.PlayRecord:
{
BlockPos pos = new BlockPos( packet.m_dataInt[ 0 ], packet.m_dataInt[ 1 ], packet.m_dataInt[ 2 ] );
Minecraft mc = Minecraft.getMinecraft();
if( packet.m_dataInt.length > 3 )
{
SoundEvent sound = SoundEvent.REGISTRY.getObjectById( packet.m_dataInt[ 3 ] );
mc.world.playRecord( pos, sound );
mc.ingameGUI.setRecordPlayingMessage( packet.m_dataString[ 0 ] );
}
else
{
mc.world.playRecord( pos, null );
}
break;
}
case ComputerCraftPacket.PostChat:
{
/*
This allows us to send delete chat messages of the same "category" as the previous one.
It's used by the various /computercraft commands to avoid filling the chat with repetitive
messages.
*/
int id = packet.m_dataInt[0];
ITextComponent[] components = new ITextComponent[packet.m_dataString.length];
for( int i = 0; i < packet.m_dataString.length; i++ )
{
components[i] = ITextComponent.Serializer.jsonToComponent( packet.m_dataString[i] );
}
GuiNewChat chat = Minecraft.getMinecraft().ingameGUI.getChatGUI();
// Keep track of how many lines we wrote last time, deleting any extra ones.
int lastCount = lastCounts.get( id );
for( int i = components.length; i < lastCount; i++ ) chat.deleteChatLine( i + id );
lastCounts.put( id, components.length );
// Add new lines
for( int i = 0; i < components.length; i++ )
{
chat.printChatMessageWithOptionalDeletion( components[i], id + i );
}
break;
}
}
}
private void registerForgeHandlers()
{
ForgeHandlers handlers = new ForgeHandlers();
MinecraftForge.EVENT_BUS.register( handlers );
MinecraftForge.EVENT_BUS.register( new ForgeHandlers() );
MinecraftForge.EVENT_BUS.register( new RenderOverlayCable() );
MinecraftForge.EVENT_BUS.register( new ItemPocketRenderer() );
MinecraftForge.EVENT_BUS.register( new ItemPrintoutRenderer() );
MinecraftForge.EVENT_BUS.register( FrameInfo.instance() );
}
@Override
public void playRecordClient( BlockPos pos, SoundEvent record, String info )
{
Minecraft mc = Minecraft.getMinecraft();
mc.world.playRecord( pos, record );
if( info != null ) mc.ingameGUI.setRecordPlayingMessage( info );
}
@Override
public void showTableClient( TableBuilder table )
{
ClientTableFormatter.INSTANCE.display( table );
}
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.getEntityPlayer().isUser() && mc.getRenderViewEntity() instanceof TurtleVisionCamera )
{
// HACK: Force the 'livingPlayer' variable to the player, this ensures the entity is drawn
//event.getRenderer().getRenderManager().livingPlayer = event.getEntityPlayer();
}
}
@SubscribeEvent
public void onRenderPlayer( RenderPlayerEvent.Post event )
{
Minecraft mc = Minecraft.getMinecraft();
if( event.getEntityPlayer().isUser() && mc.getRenderViewEntity() instanceof TurtleVisionCamera )
{
// HACK: Restore the 'livingPlayer' variable to what it was before the RenderPlayerEvent.Pre hack
//event.getRenderer().getRenderManager().livingPlayer = mc.getRenderViewEntity();
}
}
@SubscribeEvent
public void onPreRenderGameOverlay( RenderGameOverlayEvent.Pre event )
{
Minecraft mc = Minecraft.getMinecraft();
if( mc.getRenderViewEntity() instanceof TurtleVisionCamera )
{
switch( event.getType() )
{
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++;
}
}
@SubscribeEvent
public void onWorldUnload( WorldEvent.Unload event )
{
@@ -597,7 +195,7 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
}
}
@SideOnly(Side.CLIENT)
@SideOnly( Side.CLIENT )
private static class DiskColorHandler implements IItemColor
{
private final ItemDiskLegacy disk;

View File

@@ -0,0 +1,118 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.render;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.ItemRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumHandSide;
import net.minecraft.util.math.MathHelper;
public abstract class ItemMapLikeRenderer
{
/**
* The main rendering method for the item
*
* @param stack The stack to render
* @see ItemRenderer#renderMapFirstPerson(ItemStack)
*/
protected abstract void renderItem( ItemStack stack );
protected void renderItemFirstPerson( EnumHand hand, float pitch, float equipProgress, float swingProgress, ItemStack stack )
{
EntityPlayer player = Minecraft.getMinecraft().player;
GlStateManager.pushMatrix();
if( hand == EnumHand.MAIN_HAND && player.getHeldItemOffhand().isEmpty() )
{
renderItemFirstPersonCenter( pitch, equipProgress, swingProgress, stack );
}
else
{
renderItemFirstPersonSide(
hand == EnumHand.MAIN_HAND ? player.getPrimaryHand() : player.getPrimaryHand().opposite(),
equipProgress, swingProgress, stack
);
}
GlStateManager.popMatrix();
}
/**
* Renders the item to one side of the player.
*
* @param side The side to render on
* @param equipProgress The equip progress of this item
* @param swingProgress The swing progress of this item
* @param stack The stack to render
* @see ItemRenderer#renderMapFirstPersonSide(float, EnumHandSide, float, ItemStack)
*/
private void renderItemFirstPersonSide( EnumHandSide side, float equipProgress, float swingProgress, ItemStack stack )
{
Minecraft minecraft = Minecraft.getMinecraft();
float offset = side == EnumHandSide.RIGHT ? 1f : -1f;
GlStateManager.translate( offset * 0.125f, -0.125f, 0f );
// If the player is not invisible then render a single arm
if( !minecraft.player.isInvisible() )
{
GlStateManager.pushMatrix();
GlStateManager.rotate( offset * 10f, 0f, 0f, 1f );
minecraft.getItemRenderer().renderArmFirstPerson( equipProgress, swingProgress, side );
GlStateManager.popMatrix();
}
// Setup the appropriate transformations. This is just copied from the
// corresponding method in ItemRenderer.
GlStateManager.pushMatrix();
GlStateManager.translate( offset * 0.51f, -0.08f + equipProgress * -1.2f, -0.75f );
float f1 = MathHelper.sqrt( swingProgress );
float f2 = MathHelper.sin( f1 * (float) Math.PI );
float f3 = -0.5f * f2;
float f4 = 0.4f * MathHelper.sin( f1 * ((float) Math.PI * 2f) );
float f5 = -0.3f * MathHelper.sin( swingProgress * (float) Math.PI );
GlStateManager.translate( offset * f3, f4 - 0.3f * f2, f5 );
GlStateManager.rotate( f2 * -45f, 1f, 0f, 0f );
GlStateManager.rotate( offset * f2 * -30f, 0f, 1f, 0f );
renderItem( stack );
GlStateManager.popMatrix();
}
/**
* Render an item in the middle of the screen
*
* @param pitch The pitch of the player
* @param equipProgress The equip progress of this item
* @param swingProgress The swing progress of this item
* @param stack The stack to render
* @see ItemRenderer#renderMapFirstPerson(float, float, float)
*/
private void renderItemFirstPersonCenter( float pitch, float equipProgress, float swingProgress, ItemStack stack )
{
ItemRenderer itemRenderer = Minecraft.getMinecraft().getItemRenderer();
// Setup the appropriate transformations. This is just copied from the
// corresponding method in ItemRenderer.
float swingRt = MathHelper.sqrt( swingProgress );
float tX = -0.2f * MathHelper.sin( swingProgress * (float) Math.PI );
float tZ = -0.4f * MathHelper.sin( swingRt * (float) Math.PI );
GlStateManager.translate( 0f, -tX / 2f, tZ );
float pitchAngle = itemRenderer.getMapAngleFromPitch( pitch );
GlStateManager.translate( 0f, 0.04f + equipProgress * -1.2f + pitchAngle * -0.5f, -0.72f );
GlStateManager.rotate( pitchAngle * -85f, 1f, 0f, 0f );
itemRenderer.renderArms();
float rX = MathHelper.sin( swingRt * (float) Math.PI );
GlStateManager.rotate( rX * 20f, 1f, 0f, 0f );
GlStateManager.scale( 2f, 2f, 2f );
renderItem( stack );
}
}

View File

@@ -1,7 +1,13 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.render;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.client.FrameInfo;
import dan200.computercraft.client.gui.FixedWidthFontRenderer;
import dan200.computercraft.core.terminal.Terminal;
import dan200.computercraft.core.terminal.TextBuffer;
@@ -10,17 +16,12 @@ import dan200.computercraft.shared.pocket.items.ItemPocketComputer;
import dan200.computercraft.shared.util.Palette;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.ItemRenderer;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumHandSide;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.event.RenderSpecificHandEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
@@ -34,8 +35,8 @@ import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_WIDTH;
/**
* Emulates map rendering for pocket computers
*/
@SideOnly(Side.CLIENT)
public class ItemPocketRenderer
@SideOnly( Side.CLIENT )
public class ItemPocketRenderer extends ItemMapLikeRenderer
{
@SubscribeEvent
public void renderItem( RenderSpecificHandEvent event )
@@ -44,38 +45,11 @@ public class ItemPocketRenderer
if( !(stack.getItem() instanceof ItemPocketComputer) ) return;
event.setCanceled( true );
EntityPlayer player = Minecraft.getMinecraft().player;
GlStateManager.pushMatrix();
if( event.getHand() == EnumHand.MAIN_HAND && player.getHeldItemOffhand().isEmpty() )
{
renderItemFirstCentre(
event.getInterpolatedPitch(),
event.getEquipProgress(),
event.getSwingProgress(),
stack
);
}
else
{
renderItemFirstPersonSide(
event.getHand() == EnumHand.MAIN_HAND ? player.getPrimaryHand() : player.getPrimaryHand().opposite(),
event.getEquipProgress(),
event.getSwingProgress(),
stack
);
}
GlStateManager.popMatrix();
renderItemFirstPerson( event.getHand(), event.getInterpolatedPitch(), event.getEquipProgress(), event.getSwingProgress(), event.getItemStack() );
}
/**
* The main rendering method for pocket computers and their associated terminal
*
* @param stack The stack to render
* @see ItemRenderer#renderMapFirstPerson(ItemStack)
*/
private void renderPocketComputerItem( ItemStack stack )
@Override
protected void renderItem( ItemStack stack )
{
// Setup various transformations. Note that these are partially adapated from the corresponding method
// in ItemRenderer
@@ -89,8 +63,8 @@ public class ItemPocketRenderer
ClientComputer computer = pocketComputer.createClientComputer( stack );
{
// First render the background item. We use the item's model rather than a direct texture as this ensures
// we display the pocket light and other such decorations.
// First render the background item. We use the item's model rather than a direct texture as this ensures
// we display the pocket light and other such decorations.
GlStateManager.pushMatrix();
GlStateManager.scale( 1.0f, -1.0f, 1.0f );
@@ -153,12 +127,12 @@ public class ItemPocketRenderer
int startX = (max - width) / 2 + margin;
int startY = (max - height) / 2 + margin;
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer) ComputerCraft.getFixedWidthFontRenderer();
FixedWidthFontRenderer fontRenderer = FixedWidthFontRenderer.instance();
boolean greyscale = !computer.isColour();
Palette palette = terminal.getPalette();
// Render the actual text
for( int line = 0; line < th; ++line )
for( int line = 0; line < th; line++ )
{
TextBuffer text = terminal.getLine( line );
TextBuffer colour = terminal.getTextColourLine( line );
@@ -171,7 +145,7 @@ public class ItemPocketRenderer
// And render the cursor;
int tx = terminal.getCursorX(), ty = terminal.getCursorY();
if( terminal.getCursorBlink() && ComputerCraft.getGlobalCursorBlink() &&
if( terminal.getCursorBlink() && FrameInfo.instance().getGlobalCursorBlink() &&
tx >= 0 && ty >= 0 && tx < tw && ty < th )
{
TextBuffer cursorColour = new TextBuffer( "0123456789abcdef".charAt( terminal.getTextColour() ), 1 );
@@ -189,76 +163,4 @@ public class ItemPocketRenderer
GlStateManager.enableLighting();
}
/**
* Renders a pocket computer to one side of the player.
*
* @param side The side to render on
* @param equipProgress The equip progress of this item
* @param swingProgress The swing progress of this item
* @param stack The stack to render
* @see ItemRenderer#renderMapFirstPersonSide(float, EnumHandSide, float, ItemStack)
*/
private void renderItemFirstPersonSide( EnumHandSide side, float equipProgress, float swingProgress, ItemStack stack )
{
Minecraft minecraft = Minecraft.getMinecraft();
float offset = side == EnumHandSide.RIGHT ? 1f : -1f;
GlStateManager.translate( offset * 0.125f, -0.125f, 0f );
// If the player is not invisible then render a single arm
if( !minecraft.player.isInvisible() )
{
GlStateManager.pushMatrix();
GlStateManager.rotate( offset * 10f, 0f, 0f, 1f );
minecraft.getItemRenderer().renderArmFirstPerson( equipProgress, swingProgress, side );
GlStateManager.popMatrix();
}
// Setup the appropriate transformations. This is just copied from the
// corresponding method in ItemRenderer.
GlStateManager.pushMatrix();
GlStateManager.translate( offset * 0.51f, -0.08f + equipProgress * -1.2f, -0.75f );
float f1 = MathHelper.sqrt( swingProgress );
float f2 = MathHelper.sin( f1 * (float) Math.PI );
float f3 = -0.5f * f2;
float f4 = 0.4f * MathHelper.sin( f1 * ((float) Math.PI * 2f) );
float f5 = -0.3f * MathHelper.sin( swingProgress * (float) Math.PI );
GlStateManager.translate( offset * f3, f4 - 0.3f * f2, f5 );
GlStateManager.rotate( f2 * -45f, 1f, 0f, 0f );
GlStateManager.rotate( offset * f2 * -30f, 0f, 1f, 0f );
renderPocketComputerItem( stack );
GlStateManager.popMatrix();
}
/**
* Render an item in the middle of the screen
*
* @param pitch The pitch of the player
* @param equipProgress The equip progress of this item
* @param swingProgress The swing progress of this item
* @param stack The stack to render
* @see ItemRenderer#renderMapFirstPerson(float, float, float)
*/
private void renderItemFirstCentre( float pitch, float equipProgress, float swingProgress, ItemStack stack )
{
ItemRenderer itemRenderer = Minecraft.getMinecraft().getItemRenderer();
// Setup the appropriate transformations. This is just copied from the
// corresponding method in ItemRenderer.
float swingRt = MathHelper.sqrt( swingProgress );
float tX = -0.2f * MathHelper.sin( swingProgress * (float) Math.PI );
float tZ = -0.4f * MathHelper.sin( swingRt * (float) Math.PI );
GlStateManager.translate( 0f, -tX / 2f, tZ );
float pitchAngle = itemRenderer.getMapAngleFromPitch( pitch );
GlStateManager.translate( 0f, 0.04f + equipProgress * -1.2f + pitchAngle * -0.5f, -0.72f );
GlStateManager.rotate( pitchAngle * -85f, 1f, 0f, 0f );
itemRenderer.renderArms();
float rX = MathHelper.sin( swingRt * (float) Math.PI );
GlStateManager.rotate( rX * 20f, 1f, 0f, 0f );
GlStateManager.scale( 2f, 2f, 2f );
renderPocketComputerItem( stack );
}
}

View File

@@ -1,15 +1,15 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.render;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.shared.media.items.ItemPrintout;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.ItemRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumHandSide;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.client.event.RenderItemInFrameEvent;
import net.minecraftforge.client.event.RenderSpecificHandEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
@@ -20,7 +20,7 @@ import static dan200.computercraft.client.render.PrintoutRenderer.*;
import static dan200.computercraft.shared.media.items.ItemPrintout.LINES_PER_PAGE;
import static dan200.computercraft.shared.media.items.ItemPrintout.LINE_MAX_LENGTH;
public class ItemPrintoutRenderer
public class ItemPrintoutRenderer extends ItemMapLikeRenderer
{
@SubscribeEvent
public void onRenderInHand( RenderSpecificHandEvent event )
@@ -30,104 +30,11 @@ public class ItemPrintoutRenderer
event.setCanceled( true );
EntityPlayer player = Minecraft.getMinecraft().player;
GlStateManager.pushMatrix();
if( event.getHand() == EnumHand.MAIN_HAND && player.getHeldItemOffhand().isEmpty() )
{
renderPrintoutFirstPersonCentre(
event.getInterpolatedPitch(),
event.getEquipProgress(),
event.getSwingProgress(),
stack
);
}
else
{
renderPrintoutFirstPersonSide(
event.getHand() == EnumHand.MAIN_HAND ? player.getPrimaryHand() : player.getPrimaryHand().opposite(),
event.getEquipProgress(),
event.getSwingProgress(),
stack
);
}
GlStateManager.popMatrix();
renderItemFirstPerson( event.getHand(), event.getInterpolatedPitch(), event.getEquipProgress(), event.getSwingProgress(), event.getItemStack() );
}
/**
* Renders a pocket computer to one side of the player.
*
* @param side The side to render on
* @param equipProgress The equip progress of this item
* @param swingProgress The swing progress of this item
* @param stack The stack to render
* @see ItemRenderer#renderMapFirstPersonSide(float, EnumHandSide, float, ItemStack)
*/
private void renderPrintoutFirstPersonSide( EnumHandSide side, float equipProgress, float swingProgress, ItemStack stack )
{
Minecraft minecraft = Minecraft.getMinecraft();
float offset = side == EnumHandSide.RIGHT ? 1f : -1f;
GlStateManager.translate( offset * 0.125f, -0.125f, 0f );
// If the player is not invisible then render a single arm
if( !minecraft.player.isInvisible() )
{
GlStateManager.pushMatrix();
GlStateManager.rotate( offset * 10f, 0f, 0f, 1f );
minecraft.getItemRenderer().renderArmFirstPerson( equipProgress, swingProgress, side );
GlStateManager.popMatrix();
}
// Setup the appropriate transformations. This is just copied from the
// corresponding method in ItemRenderer.
GlStateManager.pushMatrix();
GlStateManager.translate( offset * 0.51f, -0.08f + equipProgress * -1.2f, -0.75f );
float f1 = MathHelper.sqrt( swingProgress );
float f2 = MathHelper.sin( f1 * (float) Math.PI );
float f3 = -0.5f * f2;
float f4 = 0.4f * MathHelper.sin( f1 * ((float) Math.PI * 2f) );
float f5 = -0.3f * MathHelper.sin( swingProgress * (float) Math.PI );
GlStateManager.translate( offset * f3, f4 - 0.3f * f2, f5 );
GlStateManager.rotate( f2 * -45f, 1f, 0f, 0f );
GlStateManager.rotate( offset * f2 * -30f, 0f, 1f, 0f );
renderPrintoutFirstPerson( stack );
GlStateManager.popMatrix();
}
/**
* Render an item in the middle of the screen
*
* @param pitch The pitch of the player
* @param equipProgress The equip progress of this item
* @param swingProgress The swing progress of this item
* @param stack The stack to render
* @see ItemRenderer#renderMapFirstPerson(float, float, float)
*/
private void renderPrintoutFirstPersonCentre( float pitch, float equipProgress, float swingProgress, ItemStack stack )
{
ItemRenderer itemRenderer = Minecraft.getMinecraft().getItemRenderer();
// Setup the appropriate transformations. This is just copied from the
// corresponding method in ItemRenderer.
float swingRt = MathHelper.sqrt( swingProgress );
float tX = -0.2f * MathHelper.sin( swingProgress * (float) Math.PI );
float tZ = -0.4f * MathHelper.sin( swingRt * (float) Math.PI );
GlStateManager.translate( 0f, -tX / 2f, tZ );
float pitchAngle = itemRenderer.getMapAngleFromPitch( pitch );
GlStateManager.translate( 0f, 0.04f + equipProgress * -1.2f + pitchAngle * -0.5f, -0.72f );
GlStateManager.rotate( pitchAngle * -85f, 1f, 0f, 0f );
itemRenderer.renderArms();
float rX = MathHelper.sin( swingRt * (float) Math.PI );
GlStateManager.rotate( rX * 20f, 1f, 0f, 0f );
GlStateManager.scale( 2f, 2f, 2f );
renderPrintoutFirstPerson( stack );
}
private static void renderPrintoutFirstPerson( ItemStack stack )
@Override
protected void renderItem( ItemStack stack )
{
// Setup various transformations. Note that these are partially adapated from the corresponding method
// in ItemRenderer.renderMapFirstPerson

View File

@@ -1,3 +1,9 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.render;
import net.minecraft.client.renderer.block.model.BakedQuad;
@@ -85,8 +91,8 @@ public final class ModelTransformer
private final Matrix4f normalMatrix;
private int vertexIndex = 0, elementIndex = 0;
private final Point3f[] before = new Point3f[ 4 ];
private final Point3f[] after = new Point3f[ 4 ];
private final Point3f[] before = new Point3f[4];
private final Point3f[] after = new Point3f[4];
public NormalAwareTransformer( IVertexConsumer parent, Matrix4f positionMatrix, Matrix4f normalMatrix )
{
@@ -96,7 +102,7 @@ public final class ModelTransformer
}
@Override
public void setQuadOrientation( EnumFacing orientation )
public void setQuadOrientation( @Nonnull EnumFacing orientation )
{
super.setQuadOrientation( orientation == null ? orientation : TRSRTransformation.rotate( positionMatrix, orientation ) );
}
@@ -112,13 +118,13 @@ public final class ModelTransformer
Point3f newVec = new Point3f();
positionMatrix.transform( vec, newVec );
float[] newData = new float[ 4 ];
float[] newData = new float[4];
newVec.get( newData );
super.put( element, newData );
before[ vertexIndex ] = vec;
after[ vertexIndex ] = newVec;
before[vertexIndex] = vec;
after[vertexIndex] = newVec;
break;
}
case NORMAL:
@@ -126,7 +132,7 @@ public final class ModelTransformer
Vector3f vec = new Vector3f( data );
normalMatrix.transform( vec );
float[] newData = new float[ 4 ];
float[] newData = new float[4];
vec.get( newData );
super.put( element, newData );
break;
@@ -150,17 +156,17 @@ public final class ModelTransformer
Vector3f crossBefore = new Vector3f(), crossAfter = new Vector3f();
// Determine what cross product we expect to have
temp1.sub( before[ 1 ], before[ 0 ] );
temp2.sub( before[ 1 ], before[ 2 ] );
temp1.sub( before[1], before[0] );
temp2.sub( before[1], before[2] );
crossBefore.cross( temp1, temp2 );
normalMatrix.transform( crossBefore );
// And determine what cross product we actually have
temp1.sub( after[ 1 ], after[ 0 ] );
temp2.sub( after[ 1 ], after[ 2 ] );
temp1.sub( after[1], after[0] );
temp2.sub( after[1], after[2] );
crossAfter.cross( temp1, temp2 );
// If the angle between expected and actual cross product is greater than
// If the angle between expected and actual cross product is greater than
// pi/2 radians then we will need to reorder our quads.
return Math.abs( crossBefore.angle( crossAfter ) ) >= Math.PI / 2;
}
@@ -189,7 +195,7 @@ public final class ModelTransformer
private BakedQuadBuilder( VertexFormat format )
{
this.format = format;
this.vertexData = new int[ format.getSize() ];
this.vertexData = new int[format.getSize()];
}
@Nonnull
@@ -241,9 +247,9 @@ public final class ModelTransformer
int length = vertexData.length / 4;
for( int i = 0; i < length; i++ )
{
int temp = vertexData[ a * length + i ];
vertexData[ a * length + i ] = vertexData[ b * length + i ];
vertexData[ b * length + i ] = temp;
int temp = vertexData[a * length + i];
vertexData[a * length + i] = vertexData[b * length + i];
vertexData[b * length + i] = temp;
}
}

View File

@@ -1,6 +1,11 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. 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.TextBuffer;
import dan200.computercraft.shared.util.Palette;
@@ -55,11 +60,11 @@ public class PrintoutRenderer
public static void drawText( int x, int y, int start, TextBuffer[] text, TextBuffer[] colours )
{
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer) ComputerCraft.getFixedWidthFontRenderer();
FixedWidthFontRenderer fontRenderer = FixedWidthFontRenderer.instance();
for( int line = 0; line < LINES_PER_PAGE && line < text.length; ++line )
for( int line = 0; line < LINES_PER_PAGE && line < text.length; line++ )
{
fontRenderer.drawString( text[ start + line ], x, y + line * FONT_HEIGHT, colours[ start + line ], null, 0, 0, false, Palette.DEFAULT );
fontRenderer.drawString( text[start + line], x, y + line * FONT_HEIGHT, colours[start + line], null, 0, 0, false, Palette.DEFAULT );
}
}
@@ -69,11 +74,11 @@ public class PrintoutRenderer
GlStateManager.enableBlend();
GlStateManager.enableTexture2D();
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer) ComputerCraft.getFixedWidthFontRenderer();
FixedWidthFontRenderer fontRenderer = FixedWidthFontRenderer.instance();
for( int line = 0; line < LINES_PER_PAGE && line < text.length; ++line )
for( int line = 0; line < LINES_PER_PAGE && line < text.length; line++ )
{
fontRenderer.drawString( new TextBuffer( text[ start + line ] ), x, y + line * FONT_HEIGHT, new TextBuffer( colours[ start + line ] ), null, 0, 0, false, Palette.DEFAULT );
fontRenderer.drawString( new TextBuffer( text[start + line] ), x, y + line * FONT_HEIGHT, new TextBuffer( colours[start + line] ), null, 0, 0, false, Palette.DEFAULT );
}
}
@@ -106,7 +111,7 @@ public class PrintoutRenderer
// Draw centre panel (just stretched texture, sorry).
drawTexture( buffer,
x - offset, y, z - 0.02, X_SIZE + offset * 2, Y_SIZE,
COVER_X + COVER_SIZE / 2, COVER_SIZE, COVER_SIZE, Y_SIZE
COVER_X + COVER_SIZE / 2.0f, COVER_SIZE, COVER_SIZE, Y_SIZE
);
double borderX = left;
@@ -120,7 +125,7 @@ public class PrintoutRenderer
}
// Left half
drawTexture( buffer, x, y, z, X_FOLD_SIZE * 2, 0, X_SIZE / 2, Y_SIZE );
drawTexture( buffer, x, y, z, X_FOLD_SIZE * 2, 0, X_SIZE / 2.0f, Y_SIZE );
for( int n = 0; n <= leftPages; n++ )
{
drawTexture( buffer,
@@ -132,7 +137,7 @@ public class PrintoutRenderer
}
// Right half
drawTexture( buffer, x + X_SIZE / 2, y, z, X_FOLD_SIZE * 2 + X_SIZE / 2, 0, X_SIZE / 2, Y_SIZE );
drawTexture( buffer, x + X_SIZE / 2.0f, y, z, X_FOLD_SIZE * 2 + X_SIZE / 2.0f, 0, X_SIZE / 2.0f, Y_SIZE );
for( int n = 0; n <= rightPages; n++ )
{
drawTexture( buffer,

View File

@@ -1,9 +1,15 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.render;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.shared.peripheral.PeripheralType;
import dan200.computercraft.shared.peripheral.common.BlockCable;
import dan200.computercraft.shared.peripheral.modem.TileCable;
import dan200.computercraft.shared.peripheral.modem.wired.BlockCable;
import dan200.computercraft.shared.peripheral.modem.wired.CableBounds;
import dan200.computercraft.shared.util.WorldUtil;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.BufferBuilder;
@@ -12,7 +18,6 @@ import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
@@ -24,8 +29,8 @@ import org.lwjgl.opengl.GL11;
public class RenderOverlayCable
{
private static final float EXPAND = 0.002f;
private static final double MIN = TileCable.MIN - EXPAND;
private static final double MAX = TileCable.MAX + EXPAND;
private static final double MIN = CableBounds.MIN - EXPAND;
private static final double MAX = CableBounds.MAX + EXPAND;
@SubscribeEvent
public void drawHighlight( DrawBlockHighlightEvent event )
@@ -38,13 +43,10 @@ public class RenderOverlayCable
IBlockState state = world.getBlockState( pos );
if( state.getBlock() != ComputerCraft.Blocks.cable ) return;
TileEntity tile = world.getTileEntity( pos );
if( tile == null || !(tile instanceof TileCable) ) return;
state = state.getActualState( world, pos );
event.setCanceled( true );
TileCable cable = (TileCable) tile;
PeripheralType type = cable.getPeripheralType();
PeripheralType type = ComputerCraft.Blocks.cable.getPeripheralType( state );
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0 );
@@ -63,9 +65,9 @@ public class RenderOverlayCable
GlStateManager.translate( -x + pos.getX(), -y + pos.getY(), -z + pos.getZ() );
}
if( type != PeripheralType.Cable && WorldUtil.isVecInsideInclusive( cable.getModemBounds(), event.getTarget().hitVec.subtract( pos.getX(), pos.getY(), pos.getZ() ) ) )
if( type != PeripheralType.Cable && WorldUtil.isVecInsideInclusive( CableBounds.getModemBounds( state ), event.getTarget().hitVec.subtract( pos.getX(), pos.getY(), pos.getZ() ) ) )
{
RenderGlobal.drawSelectionBoundingBox( cable.getModemBounds(), 0, 0, 0, 0.4f );
RenderGlobal.drawSelectionBoundingBox( CableBounds.getModemBounds( state ), 0, 0, 0, 0.4f );
}
else
{

View File

@@ -1,18 +1,25 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.render;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.shared.peripheral.PeripheralType;
import dan200.computercraft.shared.peripheral.common.BlockCable;
import dan200.computercraft.shared.peripheral.common.BlockCableModemVariant;
import dan200.computercraft.shared.peripheral.modem.TileCable;
import dan200.computercraft.shared.peripheral.modem.wired.BlockCable;
import dan200.computercraft.shared.peripheral.modem.wired.BlockCableModemVariant;
import dan200.computercraft.shared.peripheral.modem.wired.CableBounds;
import dan200.computercraft.shared.peripheral.modem.wired.TileCable;
import dan200.computercraft.shared.util.WorldUtil;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
@@ -52,7 +59,7 @@ public class TileEntityCableRenderer extends TileEntitySpecialRenderer<TileCable
if( block != ComputerCraft.Blocks.cable ) return;
state = state.getActualState( world, pos );
if( te.getPeripheralType() != PeripheralType.Cable && WorldUtil.isVecInsideInclusive( te.getModemBounds(), hit.hitVec.subtract( pos.getX(), pos.getY(), pos.getZ() ) ) )
if( te.getPeripheralType() != PeripheralType.Cable && WorldUtil.isVecInsideInclusive( CableBounds.getModemBounds( state ), hit.hitVec.subtract( pos.getX(), pos.getY(), pos.getZ() ) ) )
{
state = block.getDefaultState().withProperty( BlockCable.Properties.MODEM, state.getValue( BlockCable.Properties.MODEM ) );
}

View File

@@ -1,12 +1,12 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.render;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.client.FrameInfo;
import dan200.computercraft.client.gui.FixedWidthFontRenderer;
import dan200.computercraft.core.terminal.Terminal;
import dan200.computercraft.core.terminal.TextBuffer;
@@ -28,10 +28,6 @@ import org.lwjgl.opengl.GL11;
public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMonitor>
{
public TileEntityMonitorRenderer()
{
}
@Override
public void render( TileMonitor tileEntity, double posX, double posY, double posZ, float f, int i, float f2 )
{
@@ -51,9 +47,9 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
BlockPos monitorPos = monitor.getPos();
// Ensure each monitor terminal is rendered only once. We allow rendering a specific tile
// multiple times in a single frame to ensure compatibility with shaders which may run a
// multiple times in a single frame to ensure compatibility with shaders which may run a
// pass multiple times.
long renderFrame = ComputerCraft.getRenderFrame();
long renderFrame = FrameInfo.instance().getRenderFrame();
if( originTerminal.lastRenderFrame == renderFrame && !monitorPos.equals( originTerminal.lastRenderPos ) )
{
return;
@@ -70,7 +66,7 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
// Determine orientation
EnumFacing dir = origin.getDirection();
EnumFacing front = origin.getFront();
float yaw = DirectionUtil.toYawAngle( dir );
float yaw = dir.getHorizontalAngle();
float pitch = DirectionUtil.toPitchAngle( front );
GlStateManager.pushMatrix();
@@ -85,8 +81,8 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
(origin.getHeight() - 0.5) - (TileMonitor.RENDER_BORDER + TileMonitor.RENDER_MARGIN),
0.5
);
double xSize = origin.getWidth() - 2.0 * ( TileMonitor.RENDER_MARGIN + TileMonitor.RENDER_BORDER );
double ySize = origin.getHeight() - 2.0 * ( TileMonitor.RENDER_MARGIN + TileMonitor.RENDER_BORDER );
double xSize = origin.getWidth() - 2.0 * (TileMonitor.RENDER_MARGIN + TileMonitor.RENDER_BORDER);
double ySize = origin.getHeight() - 2.0 * (TileMonitor.RENDER_MARGIN + TileMonitor.RENDER_BORDER);
// Get renderers
Minecraft mc = Minecraft.getMinecraft();
@@ -121,17 +117,17 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
int height = terminal.getHeight();
int cursorX = terminal.getCursorX();
int cursorY = terminal.getCursorY();
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer) ComputerCraft.getFixedWidthFontRenderer();
FixedWidthFontRenderer fontRenderer = FixedWidthFontRenderer.instance();
GlStateManager.pushMatrix();
try
{
double xScale = xSize / ( width * FixedWidthFontRenderer.FONT_WIDTH );
double yScale = ySize / ( height * FixedWidthFontRenderer.FONT_HEIGHT );
double xScale = xSize / (width * FixedWidthFontRenderer.FONT_WIDTH);
double yScale = ySize / (height * FixedWidthFontRenderer.FONT_HEIGHT);
GlStateManager.scale( xScale, -yScale, 1.0 );
// Draw background
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.background );
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.BACKGROUND );
if( redraw )
{
// Build background display list
@@ -158,14 +154,14 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
}
// Backgrounds
for( int y = 0; y < height; ++y )
for( int y = 0; y < height; y++ )
{
fontRenderer.drawStringBackgroundPart(
0, FixedWidthFontRenderer.FONT_HEIGHT * y,
terminal.getBackgroundColourLine( y ),
marginXSize, marginXSize,
greyscale,
palette
0, FixedWidthFontRenderer.FONT_HEIGHT * y,
terminal.getBackgroundColourLine( y ),
marginXSize, marginXSize,
greyscale,
palette
);
}
}
@@ -186,14 +182,14 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
try
{
// Lines
for( int y = 0; y < height; ++y )
for( int y = 0; y < height; y++ )
{
fontRenderer.drawStringTextPart(
0, FixedWidthFontRenderer.FONT_HEIGHT * y,
terminal.getLine( y ),
terminal.getTextColourLine( y ),
greyscale,
palette
0, FixedWidthFontRenderer.FONT_HEIGHT * y,
terminal.getLine( y ),
terminal.getTextColourLine( y ),
greyscale,
palette
);
}
}
@@ -219,13 +215,13 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
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,
palette
cursor,
FixedWidthFontRenderer.FONT_WIDTH * cursorX,
FixedWidthFontRenderer.FONT_HEIGHT * cursorY,
cursorColour, null,
0, 0,
greyscale,
palette
);
}
}
@@ -234,7 +230,7 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
GlStateManager.glEndList();
}
}
if( ComputerCraft.getGlobalCursorBlink() )
if( FrameInfo.instance().getGlobalCursorBlink() )
{
GlStateManager.callList( originTerminal.renderDisplayLists[2] );
GlStateManager.resetColor();
@@ -248,7 +244,7 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
else
{
// Draw a big black quad
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.background );
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.BACKGROUND );
final Colour colour = Colour.Black;
final float r = colour.getR();
@@ -274,7 +270,7 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
GlStateManager.colorMask( false, false, false, false );
try
{
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.background );
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.BACKGROUND );
renderer.begin( GL11.GL_TRIANGLE_STRIP, DefaultVertexFormats.POSITION );
renderer.pos( -TileMonitor.RENDER_MARGIN, TileMonitor.RENDER_MARGIN, 0.0 ).endVertex();
renderer.pos( -TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).endVertex();

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -10,7 +10,6 @@ import dan200.computercraft.api.turtle.ITurtleUpgrade;
import dan200.computercraft.api.turtle.TurtleSide;
import dan200.computercraft.shared.computer.core.ComputerFamily;
import dan200.computercraft.shared.turtle.blocks.TileTurtle;
import dan200.computercraft.shared.turtle.entity.TurtleVisionCamera;
import dan200.computercraft.shared.util.Holiday;
import dan200.computercraft.shared.util.HolidayUtil;
import net.minecraft.block.state.IBlockState;
@@ -28,7 +27,6 @@ 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.renderer.vertex.VertexFormat;
import net.minecraft.entity.Entity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
@@ -44,36 +42,15 @@ import java.util.List;
public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurtle>
{
private static ModelResourceLocation NORMAL_TURTLE_MODEL = new ModelResourceLocation( "computercraft:turtle", "inventory" );
private static ModelResourceLocation ADVANCED_TURTLE_MODEL = new ModelResourceLocation( "computercraft:turtle_advanced", "inventory" );
private static ModelResourceLocation COLOUR_TURTLE_MODEL = new ModelResourceLocation( "computercraft:turtle_white", "inventory" );
private static ModelResourceLocation BEGINNER_TURTLE_MODEL = new ModelResourceLocation( "computercraftedu:CC-TurtleJunior", "inventory" );
private static ModelResourceLocation BEGINNER_TURTLE_COLOUR_MODEL = new ModelResourceLocation( "computercraftedu:turtleJunior_white", "inventory" );
private static ModelResourceLocation ELF_OVERLAY_MODEL = new ModelResourceLocation( "computercraft:turtle_elf_overlay", "inventory" );
public TileEntityTurtleRenderer()
{
}
private static final ModelResourceLocation NORMAL_TURTLE_MODEL = new ModelResourceLocation( "computercraft:turtle", "inventory" );
private static final ModelResourceLocation ADVANCED_TURTLE_MODEL = new ModelResourceLocation( "computercraft:turtle_advanced", "inventory" );
private static final ModelResourceLocation COLOUR_TURTLE_MODEL = new ModelResourceLocation( "computercraft:turtle_white", "inventory" );
private static final ModelResourceLocation ELF_OVERLAY_MODEL = new ModelResourceLocation( "computercraft:turtle_elf_overlay", "inventory" );
@Override
public void render( TileTurtle tileEntity, double posX, double posY, double posZ, float f, int i, float f2 )
{
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 );
}
if( tileEntity != null ) renderTurtleAt( tileEntity, posX, posY, posZ, f, i );
}
public static ModelResourceLocation getTurtleModel( ComputerFamily family, boolean coloured )
@@ -85,8 +62,6 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
return coloured ? COLOUR_TURTLE_MODEL : NORMAL_TURTLE_MODEL;
case Advanced:
return coloured ? COLOUR_TURTLE_MODEL : ADVANCED_TURTLE_MODEL;
case Beginners:
return coloured ? BEGINNER_TURTLE_COLOUR_MODEL : BEGINNER_TURTLE_MODEL;
}
}
@@ -96,7 +71,7 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
{
return new ModelResourceLocation( overlay, "inventory" );
}
else if( christmas && family != ComputerFamily.Beginners )
else if( christmas )
{
return ELF_OVERLAY_MODEL;
}
@@ -192,7 +167,7 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
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 );
Pair<IBakedModel, Matrix4f> pair = upgrade.getModel( turtle.getAccess(), side );
if( pair != null )
{
if( pair.getRight() != null )
@@ -236,7 +211,7 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
BufferBuilder buffer = tessellator.getBuffer();
VertexFormat format = DefaultVertexFormats.ITEM;
buffer.begin( GL11.GL_QUADS, format );
for (BakedQuad quad : quads)
for( BakedQuad quad : quads )
{
VertexFormat quadFormat = quad.getFormat();
if( quadFormat != format )
@@ -250,7 +225,7 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
if( quad.hasTintIndex() && tints != null )
{
int index = quad.getTintIndex();
if( index >= 0 && index < tints.length ) colour = tints[ index ] | 0xFF000000;
if( index >= 0 && index < tints.length ) colour = tints[index] | 0xFF000000;
}
LightUtil.renderQuadColor( buffer, quad, colour );

View File

@@ -1,3 +1,9 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.render;
import net.minecraft.block.state.IBlockState;

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -75,25 +75,17 @@ public class TurtleSmartItemModel implements IBakedModel, ISelectiveResourceRelo
@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 &&
otherCombo.m_flip == m_flip )
{
return true;
}
}
return false;
if( other == this ) return true;
if( !(other instanceof TurtleModelCombination) ) return false;
TurtleModelCombination otherCombo = (TurtleModelCombination) other;
return 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 &&
otherCombo.m_flip == m_flip;
}
@Override

View File

@@ -1,3 +1,9 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.apis;
import com.google.common.net.InetAddresses;
@@ -32,8 +38,8 @@ public class AddressPredicate
for( int i = 0; i < entry.length; i++ )
{
int value = 0xFF & entry[ i ];
if( value < (0xFF & min[ i ]) || value > (0xFF & max[ i ]) ) return false;
int value = 0xFF & entry[i];
if( value < (0xFF & min[i]) || value > (0xFF & max[i]) ) return false;
}
return true;
@@ -85,13 +91,13 @@ public class AddressPredicate
{
if( size <= 0 )
{
minBytes[ i ] &= 0;
maxBytes[ i ] |= 0xFF;
minBytes[i] &= 0;
maxBytes[i] |= 0xFF;
}
else if( size < 8 )
{
minBytes[ i ] &= 0xFF << (8 - size);
maxBytes[ i ] |= ~(0xFF << (8 - size));
minBytes[i] &= 0xFF << (8 - size);
maxBytes[i] |= ~(0xFF << (8 - size));
}
size -= 8;
@@ -157,12 +163,8 @@ public class AddressPredicate
if( matchesAddress( address ) ) return true;
// If we're an IPv4 address in disguise then let's check that.
if( address instanceof Inet6Address && InetAddresses.is6to4Address( (Inet6Address) address )
&& matchesAddress( InetAddresses.get6to4IPv4Address( (Inet6Address) address ) ) )
{
return true;
}
return address instanceof Inet6Address && InetAddresses.is6to4Address( (Inet6Address) address )
&& matchesAddress( InetAddresses.get6to4IPv4Address( (Inet6Address) address ) );
return false;
}
}

View File

@@ -0,0 +1,36 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.apis;
import com.google.common.base.Preconditions;
import dan200.computercraft.api.lua.ILuaAPIFactory;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
public final class ApiFactories
{
private ApiFactories()
{
}
private static final Collection<ILuaAPIFactory> factories = new LinkedHashSet<>();
private static final Collection<ILuaAPIFactory> factoriesView = Collections.unmodifiableCollection( factories );
public static void register( @Nonnull ILuaAPIFactory factory )
{
Preconditions.checkNotNull( factory, "provider cannot be null" );
factories.add( factory );
}
public static Iterable<ILuaAPIFactory> getAll()
{
return factoriesView;
}
}

View File

@@ -1,3 +1,9 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.apis;
import dan200.computercraft.api.lua.LuaException;
@@ -58,7 +64,7 @@ public final class ArgumentHelper
public static double getNumber( @Nonnull Object[] args, int index ) throws LuaException
{
if( index >= args.length ) throw badArgument( index, "number", "nil" );
Object value = args[ index ];
Object value = args[index];
if( value instanceof Number )
{
return ((Number) value).doubleValue();
@@ -77,7 +83,7 @@ public final class ArgumentHelper
public static long getLong( @Nonnull Object[] args, int index ) throws LuaException
{
if( index >= args.length ) throw badArgument( index, "number", "nil" );
Object value = args[ index ];
Object value = args[index];
if( value instanceof Number )
{
return checkReal( index, (Number) value ).longValue();
@@ -96,7 +102,7 @@ public final class ArgumentHelper
public static boolean getBoolean( @Nonnull Object[] args, int index ) throws LuaException
{
if( index >= args.length ) throw badArgument( index, "boolean", "nil" );
Object value = args[ index ];
Object value = args[index];
if( value instanceof Boolean )
{
return (Boolean) value;
@@ -111,7 +117,7 @@ public final class ArgumentHelper
public static String getString( @Nonnull Object[] args, int index ) throws LuaException
{
if( index >= args.length ) throw badArgument( index, "string", "nil" );
Object value = args[ index ];
Object value = args[index];
if( value instanceof String )
{
return (String) value;
@@ -122,12 +128,12 @@ public final class ArgumentHelper
}
}
@SuppressWarnings("unchecked")
@SuppressWarnings( "unchecked" )
@Nonnull
public static Map<Object, Object> getTable( @Nonnull Object[] args, int index ) throws LuaException
{
if( index >= args.length ) throw badArgument( index, "table", "nil" );
Object value = args[ index ];
Object value = args[index];
if( value instanceof Map )
{
return (Map<Object, Object>) value;
@@ -140,7 +146,7 @@ public final class ArgumentHelper
public static double optNumber( @Nonnull Object[] args, int index, double def ) throws LuaException
{
Object value = index < args.length ? args[ index ] : null;
Object value = index < args.length ? args[index] : null;
if( value == null )
{
return def;
@@ -162,7 +168,7 @@ public final class ArgumentHelper
public static long optLong( @Nonnull Object[] args, int index, long def ) throws LuaException
{
Object value = index < args.length ? args[ index ] : null;
Object value = index < args.length ? args[index] : null;
if( value == null )
{
return def;
@@ -184,7 +190,7 @@ public final class ArgumentHelper
public static boolean optBoolean( @Nonnull Object[] args, int index, boolean def ) throws LuaException
{
Object value = index < args.length ? args[ index ] : null;
Object value = index < args.length ? args[index] : null;
if( value == null )
{
return def;
@@ -201,7 +207,7 @@ public final class ArgumentHelper
public static String optString( @Nonnull Object[] args, int index, String def ) throws LuaException
{
Object value = index < args.length ? args[ index ] : null;
Object value = index < args.length ? args[index] : null;
if( value == null )
{
return def;
@@ -216,10 +222,10 @@ public final class ArgumentHelper
}
}
@SuppressWarnings("unchecked")
@SuppressWarnings( "unchecked" )
public static Map<Object, Object> optTable( @Nonnull Object[] args, int index, Map<Object, Object> def ) throws LuaException
{
Object value = index < args.length ? args[ index ] : null;
Object value = index < args.length ? args[index] : null;
if( value == null )
{
return def;

View File

@@ -1,135 +0,0 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.apis;
import dan200.computercraft.api.lua.ILuaAPI;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.ILuaObject;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.core.terminal.TextBuffer;
import javax.annotation.Nonnull;
import static dan200.computercraft.core.apis.ArgumentHelper.getString;
import static dan200.computercraft.core.apis.ArgumentHelper.optInt;
public class BufferAPI implements ILuaAPI
{
private static class BufferLuaObject implements ILuaObject
{
private TextBuffer m_buffer;
public BufferLuaObject( TextBuffer buffer )
{
m_buffer = buffer;
}
@Nonnull
@Override
public String[] getMethodNames()
{
return new String[] {
"len",
"tostring",
"read",
"write",
"fill"
};
}
@Override
public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull 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 = optInt( arguments, 0, 0 );
int end = optInt( arguments, 1, m_buffer.length() );
return new Object[] { m_buffer.read( start, end ) };
}
case 3:
{
// write
String text = getString( arguments, 0 );
int start = optInt( arguments, 1, 0 );
int end = optInt( arguments, 2, start + text.length() );
m_buffer.write( text, start, end );
return null;
}
case 4:
{
// fill
String text = getString( arguments, 0 );
int start = optInt( arguments, 1, 0 );
int end = optInt( arguments, 2, m_buffer.length() );
m_buffer.fill( text, start, end );
return null;
}
default:
{
return null;
}
}
}
}
public BufferAPI( IAPIEnvironment _env )
{
}
@Override
public String[] getNames()
{
return new String[] {
"buffer"
};
}
@Nonnull
@Override
public String[] getMethodNames()
{
return new String[] {
"new"
};
}
@Override
public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull Object[] arguments ) throws LuaException, InterruptedException
{
switch( method )
{
case 0:
{
String text = getString( arguments, 0 );
int repetitions = optInt( arguments, 1, 1 );
if( repetitions < 0 )
{
throw ArgumentHelper.badArgument( 1, "positive number", Integer.toString( repetitions ) );
}
TextBuffer buffer = new TextBuffer( text, repetitions );
return new Object[] { new BufferLuaObject( buffer ) };
}
default:
{
return null;
}
}
}
}

View File

@@ -1,5 +1,12 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.apis;
import com.google.common.base.Preconditions;
import dan200.computercraft.api.filesystem.IMount;
import dan200.computercraft.api.filesystem.IWritableMount;
import dan200.computercraft.api.peripheral.IComputerAccess;
@@ -11,6 +18,7 @@ import dan200.computercraft.core.filesystem.FileSystemException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public abstract class ComputerAccess implements IComputerAccess, IComputerOwned
@@ -33,22 +41,17 @@ public abstract class ComputerAccess implements IComputerAccess, IComputerOwned
m_mounts.clear();
}
@Override
public String mount( @Nonnull String desiredLoc, @Nonnull IMount mount )
{
return mount( desiredLoc, mount, getAttachmentName() );
}
@Override
public synchronized String mount( @Nonnull String desiredLoc, @Nonnull IMount mount, @Nonnull String driveName )
{
Objects.requireNonNull( desiredLoc, "desiredLocation cannot be null" );
Objects.requireNonNull( mount, "mount cannot be null" );
Objects.requireNonNull( driveName, "driveName cannot be null" );
// Mount the location
String location;
FileSystem fileSystem = m_environment.getFileSystem();
if( fileSystem == null )
{
throw new IllegalStateException( "File system has not been created" );
}
if( fileSystem == null ) throw new IllegalStateException( "File system has not been created" );
synchronized( fileSystem )
{
@@ -64,29 +67,22 @@ public abstract class ComputerAccess implements IComputerAccess, IComputerOwned
}
}
}
if( location != null )
{
m_mounts.add( location );
}
return location;
}
@Override
public String mountWritable( @Nonnull String desiredLoc, @Nonnull IWritableMount mount )
{
return mountWritable( desiredLoc, mount, getAttachmentName() );
if( location != null ) m_mounts.add( location );
return location;
}
@Override
public synchronized String mountWritable( @Nonnull String desiredLoc, @Nonnull IWritableMount mount, @Nonnull String driveName )
{
Objects.requireNonNull( desiredLoc, "desiredLocation cannot be null" );
Objects.requireNonNull( mount, "mount cannot be null" );
Objects.requireNonNull( driveName, "driveName cannot be null" );
// Mount the location
String location;
FileSystem fileSystem = m_environment.getFileSystem();
if( fileSystem == null )
{
throw new IllegalStateException( "File system has not been created" );
}
if( fileSystem == null ) throw new IllegalStateException( "File system has not been created" );
synchronized( fileSystem )
{
@@ -102,26 +98,19 @@ public abstract class ComputerAccess implements IComputerAccess, IComputerOwned
}
}
}
if( location != null )
{
m_mounts.add( location );
}
if( location != null ) m_mounts.add( location );
return location;
}
@Override
public void unmount( String location )
{
if( location != null )
{
if( !m_mounts.contains( location ) )
{
throw new RuntimeException( "You didn't mount this location" );
}
if( location == null ) return;
if( !m_mounts.contains( location ) ) throw new IllegalStateException( "You didn't mount this location" );
m_environment.getFileSystem().unmount( location );
m_mounts.remove( location );
}
m_environment.getFileSystem().unmount( location );
m_mounts.remove( location );
}
@Override
@@ -133,6 +122,7 @@ public abstract class ComputerAccess implements IComputerAccess, IComputerOwned
@Override
public void queueEvent( @Nonnull final String event, final Object[] arguments )
{
Preconditions.checkNotNull( event, "event cannot be null" );
m_environment.queueEvent( event, arguments );
}
@@ -148,13 +138,9 @@ public abstract class ComputerAccess implements IComputerAccess, IComputerOwned
try
{
FileSystem fileSystem = m_environment.getFileSystem();
if( !fileSystem.exists( desiredLoc ) )
{
return desiredLoc;
}
if( !fileSystem.exists( desiredLoc ) ) return desiredLoc;
// We used to check foo2,foo3,foo4,etc here
// but the disk drive does this itself now
// We used to check foo2, foo3, foo4, etc here but the disk drive does this itself now
return null;
}
catch( FileSystemException e )

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -33,13 +33,13 @@ 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()
{
@@ -49,13 +49,13 @@ public class FSAPI implements ILuaAPI
}
@Override
public void startup( )
public void startup()
{
m_fileSystem = m_env.getFileSystem();
}
@Override
public void shutdown( )
public void shutdown()
{
m_fileSystem = null;
}
@@ -94,11 +94,13 @@ public class FSAPI implements ILuaAPI
// list
String path = getString( args, 0 );
m_env.addTrackingChange( TrackingField.FS_OPS );
try {
try
{
String[] results = m_fileSystem.list( path );
Map<Object,Object> table = new HashMap<>();
for(int i=0; i<results.length; ++i ) {
table.put( i+1, results[i] );
Map<Object, Object> table = new HashMap<>();
for( int i = 0; i < results.length; i++ )
{
table.put( i + 1, results[i] );
}
return new Object[] { table };
}
@@ -118,7 +120,7 @@ public class FSAPI implements ILuaAPI
{
// getName
String path = getString( args, 0 );
return new Object[]{ FileSystem.getName( path ) };
return new Object[] { FileSystem.getName( path ) };
}
case 3:
{
@@ -126,7 +128,7 @@ public class FSAPI implements ILuaAPI
String path = getString( args, 0 );
try
{
return new Object[]{ m_fileSystem.getSize( path ) };
return new Object[] { m_fileSystem.getSize( path ) };
}
catch( FileSystemException e )
{
@@ -137,41 +139,53 @@ public class FSAPI implements ILuaAPI
{
// exists
String path = getString( args, 0 );
try {
return new Object[]{ m_fileSystem.exists( path ) };
} catch( FileSystemException e ) {
return new Object[]{ false };
try
{
return new Object[] { m_fileSystem.exists( path ) };
}
catch( FileSystemException e )
{
return new Object[] { false };
}
}
case 5:
{
// isDir
String path = getString( args, 0 );
try {
return new Object[]{ m_fileSystem.isDir( path ) };
} catch( FileSystemException e ) {
return new Object[]{ false };
try
{
return new Object[] { m_fileSystem.isDir( path ) };
}
catch( FileSystemException e )
{
return new Object[] { false };
}
}
case 6:
{
// isReadOnly
String path = getString( args, 0 );
try {
return new Object[]{ m_fileSystem.isReadOnly( path ) };
} catch( FileSystemException e ) {
return new Object[]{ false };
try
{
return new Object[] { m_fileSystem.isReadOnly( path ) };
}
catch( FileSystemException e )
{
return new Object[] { false };
}
}
case 7:
{
// makeDir
String path = getString( args, 0 );
try {
try
{
m_env.addTrackingChange( TrackingField.FS_OPS );
m_fileSystem.makeDir( path );
return null;
} catch( FileSystemException e ) {
}
catch( FileSystemException e )
{
throw new LuaException( e.getMessage() );
}
}
@@ -180,11 +194,14 @@ public class FSAPI implements ILuaAPI
// move
String path = getString( args, 0 );
String dest = getString( args, 1 );
try {
try
{
m_env.addTrackingChange( TrackingField.FS_OPS );
m_fileSystem.move( path, dest );
return null;
} catch( FileSystemException e ) {
}
catch( FileSystemException e )
{
throw new LuaException( e.getMessage() );
}
}
@@ -193,11 +210,14 @@ public class FSAPI implements ILuaAPI
// copy
String path = getString( args, 0 );
String dest = getString( args, 1 );
try {
try
{
m_env.addTrackingChange( TrackingField.FS_OPS );
m_fileSystem.copy( path, dest );
return null;
} catch( FileSystemException e ) {
}
catch( FileSystemException e )
{
throw new LuaException( e.getMessage() );
}
}
@@ -205,11 +225,14 @@ public class FSAPI implements ILuaAPI
{
// delete
String path = getString( args, 0 );
try {
try
{
m_env.addTrackingChange( TrackingField.FS_OPS );
m_fileSystem.delete( path );
return null;
} catch( FileSystemException e ) {
}
catch( FileSystemException e )
{
throw new LuaException( e.getMessage() );
}
}
@@ -219,7 +242,8 @@ public class FSAPI implements ILuaAPI
String path = getString( args, 0 );
String mode = getString( args, 1 );
m_env.addTrackingChange( TrackingField.FS_OPS );
try {
try
{
switch( mode )
{
case "r":
@@ -261,7 +285,9 @@ public class FSAPI implements ILuaAPI
default:
throw new LuaException( "Unsupported mode" );
}
} catch( FileSystemException e ) {
}
catch( FileSystemException e )
{
return new Object[] { null, e.getMessage() };
}
}
@@ -269,13 +295,16 @@ public class FSAPI implements ILuaAPI
{
// getDrive
String path = getString( args, 0 );
try {
try
{
if( !m_fileSystem.exists( path ) )
{
return null;
}
return new Object[]{ m_fileSystem.getMountLabel( path ) };
} catch( FileSystemException e ) {
return new Object[] { m_fileSystem.getMountLabel( path ) };
}
catch( FileSystemException e )
{
throw new LuaException( e.getMessage() );
}
}
@@ -283,14 +312,17 @@ public class FSAPI implements ILuaAPI
{
// getFreeSpace
String path = getString( args, 0 );
try {
try
{
long freeSpace = m_fileSystem.getFreeSpace( path );
if( freeSpace >= 0 )
{
return new Object[]{ freeSpace };
return new Object[] { freeSpace };
}
return new Object[]{ "unlimited" };
} catch( FileSystemException e ) {
return new Object[] { "unlimited" };
}
catch( FileSystemException e )
{
throw new LuaException( e.getMessage() );
}
}
@@ -298,15 +330,19 @@ public class FSAPI implements ILuaAPI
{
// find
String path = getString( args, 0 );
try {
try
{
m_env.addTrackingChange( TrackingField.FS_OPS );
String[] results = m_fileSystem.find( path );
Map<Object,Object> table = new HashMap<>();
for(int i=0; i<results.length; ++i ) {
table.put( i+1, results[i] );
Map<Object, Object> table = new HashMap<>();
for( int i = 0; i < results.length; i++ )
{
table.put( i + 1, results[i] );
}
return new Object[] { table };
} catch( FileSystemException e ) {
}
catch( FileSystemException e )
{
throw new LuaException( e.getMessage() );
}
}
@@ -314,11 +350,11 @@ public class FSAPI implements ILuaAPI
{
// getDir
String path = getString( args, 0 );
return new Object[]{ FileSystem.getDirectory( path ) };
return new Object[] { FileSystem.getDirectory( path ) };
}
default:
{
assert( false );
assert (false);
return null;
}
}

View File

@@ -1,101 +1,81 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.apis;
import com.google.common.collect.ImmutableSet;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.lua.ILuaAPI;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.core.apis.http.*;
import dan200.computercraft.core.apis.http.request.HttpRequest;
import dan200.computercraft.core.apis.http.websocket.Websocket;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import javax.annotation.Nonnull;
import java.io.Closeable;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Future;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import static dan200.computercraft.core.apis.ArgumentHelper.*;
import static dan200.computercraft.core.apis.TableHelper.*;
public class HTTPAPI implements ILuaAPI
{
private static final Set<String> HTTP_METHODS = ImmutableSet.of(
"GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE"
);
private final IAPIEnvironment m_apiEnvironment;
private final List<Future<?>> m_httpTasks;
private final Set<Closeable> m_closeables;
private final ResourceGroup<CheckUrl> checkUrls = new ResourceGroup<>();
private final ResourceGroup<HttpRequest> requests = new ResourceQueue<>( () -> ComputerCraft.httpMaxRequests );
private final ResourceGroup<Websocket> websockets = new ResourceGroup<>( () -> ComputerCraft.httpMaxWebsockets );
public HTTPAPI( IAPIEnvironment environment )
{
m_apiEnvironment = environment;
m_httpTasks = new ArrayList<>();
m_closeables = new HashSet<>();
}
@Override
public String[] getNames()
{
return new String[]{
return new String[] {
"http"
};
}
@Override
public void update()
public void startup()
{
// Wait for all of our http requests
synchronized( m_httpTasks )
{
Iterator<Future<?>> it = m_httpTasks.iterator();
while( it.hasNext() )
{
final Future<?> h = it.next();
if( h.isDone() ) it.remove();
}
}
checkUrls.startup();
requests.startup();
websockets.startup();
}
@Override
public void shutdown()
{
synchronized( m_httpTasks )
{
for( Future<?> r : m_httpTasks )
{
r.cancel( false );
}
m_httpTasks.clear();
}
synchronized( m_closeables )
{
for( Closeable x : m_closeables )
{
try
{
x.close();
}
catch( IOException ignored )
{
}
}
m_closeables.clear();
}
checkUrls.shutdown();
requests.shutdown();
websockets.shutdown();
}
@Override
public void update()
{
// It's rather ugly to run this here, but we need to clean up
// resources as often as possible to reduce blocking.
Resource.cleanup();
}
@Nonnull
@Override
public String[] getMethodNames()
{
return new String[]{
return new String[] {
"request",
"checkURL",
"websocket",
@@ -109,16 +89,16 @@ public class HTTPAPI implements ILuaAPI
{
case 0: // request
{
String urlString, postString, requestMethod;
String address, postString, requestMethod;
Map<Object, Object> headerTable;
boolean binary, redirect;
if( args.length >= 1 && args[0] instanceof Map )
{
Map<?, ?> options = (Map) args[0];
urlString = getStringField( options, "url" );
address = getStringField( options, "url" );
postString = optStringField( options, "body", null );
headerTable = optTableField( options, "headers", null );
headerTable = optTableField( options, "headers", Collections.emptyMap() );
binary = optBooleanField( options, "binary", false );
requestMethod = optStringField( options, "method", null );
redirect = optBooleanField( options, "redirect", true );
@@ -127,70 +107,68 @@ public class HTTPAPI implements ILuaAPI
else
{
// Get URL and post information
urlString = getString( args, 0 );
address = getString( args, 0 );
postString = optString( args, 1, null );
headerTable = optTable( args, 2, null );
headerTable = optTable( args, 2, Collections.emptyMap() );
binary = optBoolean( args, 3, false );
requestMethod = null;
redirect = true;
}
Map<String, String> headers = null;
if( headerTable != null )
HttpHeaders headers = getHeaders( headerTable );
HttpMethod httpMethod;
if( requestMethod == null )
{
headers = new HashMap<>( headerTable.size() );
for( Object key : headerTable.keySet() )
httpMethod = postString == null ? HttpMethod.GET : HttpMethod.POST;
}
else
{
httpMethod = HttpMethod.valueOf( requestMethod.toUpperCase( Locale.ROOT ) );
if( httpMethod == null || requestMethod.equalsIgnoreCase( "CONNECT" ) )
{
Object value = headerTable.get( key );
if( key instanceof String && value instanceof String )
{
headers.put( (String) key, (String) value );
}
throw new LuaException( "Unsupported HTTP method" );
}
}
if( requestMethod != null && !HTTP_METHODS.contains( requestMethod ) )
{
throw new LuaException( "Unsupported HTTP method" );
}
// Make the request
try
{
URL url = HTTPRequest.checkURL( urlString );
HTTPRequest request = new HTTPRequest( m_apiEnvironment, urlString, url, postString, headers, binary, requestMethod, redirect );
synchronized( m_httpTasks )
URI uri = HttpRequest.checkUri( address );
HttpRequest request = new HttpRequest( requests, m_apiEnvironment, address, postString, headers, binary, redirect );
long requestBody = request.body().readableBytes() + HttpRequest.getHeaderSize( headers );
if( ComputerCraft.httpMaxUpload != 0 && requestBody > ComputerCraft.httpMaxUpload )
{
m_httpTasks.add( HTTPExecutor.EXECUTOR.submit( request ) );
throw new HTTPRequestException( "Request body is too large" );
}
return new Object[]{ true };
// Make the request
request.queue( r -> r.request( uri, httpMethod ) );
return new Object[] { true };
}
catch( HTTPRequestException e )
{
return new Object[]{ false, e.getMessage() };
return new Object[] { false, e.getMessage() };
}
}
case 1:
case 1: // checkURL
{
// checkURL
// Get URL
String urlString = getString( args, 0 );
String address = getString( args, 0 );
// Check URL
try
{
URL url = HTTPRequest.checkURL( urlString );
HTTPCheck check = new HTTPCheck( m_apiEnvironment, urlString, url );
synchronized( m_httpTasks )
{
m_httpTasks.add( HTTPExecutor.EXECUTOR.submit( check ) );
}
return new Object[]{ true };
URI uri = HttpRequest.checkUri( address );
new CheckUrl( checkUrls, m_apiEnvironment, address, uri ).queue( CheckUrl::run );
return new Object[] { true };
}
catch( HTTPRequestException e )
{
return new Object[]{ false, e.getMessage() };
return new Object[] { false, e.getMessage() };
}
}
case 2: // websocket
@@ -198,36 +176,26 @@ public class HTTPAPI implements ILuaAPI
String address = getString( args, 0 );
Map<Object, Object> headerTbl = optTable( args, 1, Collections.emptyMap() );
HashMap<String, String> headers = new HashMap<String, String>( headerTbl.size() );
for( Object key : headerTbl.keySet() )
{
Object value = headerTbl.get( key );
if( key instanceof String && value instanceof String )
{
headers.put( (String) key, (String) value );
}
}
if( !ComputerCraft.http_websocket_enable )
{
throw new LuaException( "Websocket connections are disabled" );
}
HttpHeaders headers = getHeaders( headerTbl );
try
{
URI uri = WebsocketConnector.checkURI( address );
int port = WebsocketConnector.getPort( uri );
Future<?> connector = WebsocketConnector.createConnector( m_apiEnvironment, this, uri, address, port, headers );
synchronized( m_httpTasks )
URI uri = Websocket.checkUri( address );
if( !new Websocket( websockets, m_apiEnvironment, uri, address, headers ).queue( Websocket::connect ) )
{
m_httpTasks.add( connector );
throw new LuaException( "Too many websockets already open" );
}
return new Object[]{ true };
return new Object[] { true };
}
catch( HTTPRequestException e )
{
return new Object[]{ false, e.getMessage() };
return new Object[] { false, e.getMessage() };
}
}
default:
@@ -237,19 +205,25 @@ public class HTTPAPI implements ILuaAPI
}
}
public void addCloseable( Closeable closeable )
@Nonnull
private static HttpHeaders getHeaders( @Nonnull Map<?, ?> headerTable ) throws LuaException
{
synchronized( m_closeables )
HttpHeaders headers = new DefaultHttpHeaders();
for( Object key : headerTable.keySet() )
{
m_closeables.add( closeable );
}
}
public void removeCloseable( Closeable closeable )
{
synchronized( m_closeables )
{
m_closeables.remove( closeable );
Object value = headerTable.get( key );
if( key instanceof String && value instanceof String )
{
try
{
headers.add( (String) key, value );
}
catch( IllegalArgumentException e )
{
throw new LuaException( e.getMessage() );
}
}
}
return headers;
}
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -23,27 +23,39 @@ public interface IAPIEnvironment extends IComputerOwned
@Override
Computer getComputer();
int getComputerID();
IComputerEnvironment getComputerEnvironment();
Terminal getTerminal();
FileSystem getFileSystem();
void shutdown();
void reboot();
void queueEvent( String event, Object[] args );
void setOutput( int side, int output );
int getOutput( int side );
int getInput( int side );
void setBundledOutput( int side, int output );
int getBundledOutput( int side );
int getBundledInput( int side );
void setPeripheralChangeListener( IPeripheralChangeListener listener );
IPeripheral getPeripheral( int side );
String getLabel();
void setLabel( String label );
void addTrackingChange( TrackingField field, long change );

View File

@@ -1,3 +1,9 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.apis;
/**
@@ -5,6 +11,7 @@ package dan200.computercraft.core.apis;
*
* @see dan200.computercraft.api.lua.ILuaAPI
*/
@Deprecated
public interface ILuaAPI extends dan200.computercraft.api.lua.ILuaAPI
{
void advance( double v );

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -28,7 +28,7 @@ public class OSAPI implements ILuaAPI
private int m_nextTimerToken;
private int m_nextAlarmToken;
private static class Timer
{
public int m_ticksLeft;
@@ -38,7 +38,7 @@ public class OSAPI implements ILuaAPI
m_ticksLeft = ticksLeft;
}
}
private class Alarm implements Comparable<Alarm>
{
public final double m_time;
@@ -55,16 +55,10 @@ public class OSAPI implements ILuaAPI
{
double t = m_day * 24.0 + m_time;
double ot = m_day * 24.0 + m_time;
if( t < ot ) {
return -1;
} else if( t > ot ) {
return 1;
} else {
return 0;
}
return Double.compare( t, ot );
}
}
public OSAPI( IAPIEnvironment environment )
{
m_apiEnvironment = environment;
@@ -73,9 +67,9 @@ public class OSAPI implements ILuaAPI
m_timers = new HashMap<>();
m_alarms = new HashMap<>();
}
// ILuaAPI implementation
@Override
public String[] getNames()
{
@@ -83,7 +77,7 @@ public class OSAPI implements ILuaAPI
"os"
};
}
@Override
public void startup()
{
@@ -101,7 +95,7 @@ public class OSAPI implements ILuaAPI
m_alarms.clear();
}
}
@Override
public void update()
{
@@ -109,7 +103,7 @@ public class OSAPI implements ILuaAPI
{
// Update the clock
m_clock++;
// Countdown all of our active timers
Iterator<Map.Entry<Integer, Timer>> it = m_timers.entrySet().iterator();
while( it.hasNext() )
@@ -125,15 +119,15 @@ public class OSAPI implements ILuaAPI
}
}
}
// 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();
int day = m_apiEnvironment.getComputerEnvironment().getDay();
if( time > previousTime || day > previousDay )
{
double now = m_day * 24.0 + m_time;
@@ -145,7 +139,7 @@ public class OSAPI implements ILuaAPI
double t = alarm.m_day * 24.0 + alarm.m_time;
if( now >= t )
{
queueLuaEvent( "alarm", new Object[]{ entry.getKey() } );
queueLuaEvent( "alarm", new Object[] { entry.getKey() } );
it.remove();
}
}
@@ -155,15 +149,15 @@ public class OSAPI implements ILuaAPI
m_day = day;
}
}
@Override
public void shutdown( )
public void shutdown()
{
synchronized( m_timers )
{
m_timers.clear();
}
synchronized( m_alarms )
{
m_alarms.clear();
@@ -194,28 +188,28 @@ public class OSAPI implements ILuaAPI
};
}
private float getTimeForCalendar(Calendar c)
private float getTimeForCalendar( Calendar c )
{
float time = c.get(Calendar.HOUR_OF_DAY);
time += c.get(Calendar.MINUTE) / 60.0f;
time += c.get(Calendar.SECOND) / (60.0f * 60.0f);
float time = c.get( Calendar.HOUR_OF_DAY );
time += c.get( Calendar.MINUTE ) / 60.0f;
time += c.get( Calendar.SECOND ) / (60.0f * 60.0f);
return time;
}
private int getDayForCalendar(Calendar c)
private int getDayForCalendar( Calendar c )
{
GregorianCalendar g = (c instanceof GregorianCalendar) ? (GregorianCalendar)c : new GregorianCalendar();
int year = c.get(Calendar.YEAR);
GregorianCalendar g = (c instanceof GregorianCalendar) ? (GregorianCalendar) c : new GregorianCalendar();
int year = c.get( Calendar.YEAR );
int day = 0;
for( int y=1970; y<year; ++y )
for( int y = 1970; y < year; y++ )
{
day += g.isLeapYear(y) ? 366 : 365;
day += g.isLeapYear( y ) ? 366 : 365;
}
day += c.get(Calendar.DAY_OF_YEAR);
day += c.get( Calendar.DAY_OF_YEAR );
return day;
}
private long getEpochForCalendar(Calendar c)
private long getEpochForCalendar( Calendar c )
{
return c.getTime().getTime();
}
@@ -237,7 +231,7 @@ public class OSAPI implements ILuaAPI
double timer = getReal( args, 0 );
synchronized( m_timers )
{
m_timers.put( m_nextTimerToken, new Timer( (int)Math.round( timer / 0.05 ) ) );
m_timers.put( m_nextTimerToken, new Timer( (int) Math.round( timer / 0.05 ) ) );
return new Object[] { m_nextTimerToken++ };
}
}
@@ -248,7 +242,7 @@ public class OSAPI implements ILuaAPI
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);
@@ -425,12 +419,12 @@ public class OSAPI implements ILuaAPI
{
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();

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -40,19 +40,21 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
public PeripheralWrapper( IPeripheral peripheral, String side )
{
super(m_environment);
super( m_environment );
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 );
assert (m_type != null);
assert (m_methods != null);
m_methodMap = new HashMap<>();
for(int i=0; i<m_methods.length; ++i ) {
if( m_methods[i] != null ) {
for( int i = 0; i < m_methods.length; i++ )
{
if( m_methods[i] != null )
{
m_methodMap.put( m_methods[i], i );
}
}
@@ -235,7 +237,7 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
m_environment.setPeripheralChangeListener( this );
m_peripherals = new PeripheralWrapper[6];
for(int i=0; i<6; ++i)
for( int i = 0; i < 6; i++ )
{
m_peripherals[i] = null;
}
@@ -254,21 +256,26 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
{
// Queue a detachment
final PeripheralWrapper wrapper = m_peripherals[side];
ComputerThread.queueTask(new ITask() {
ComputerThread.queueTask( new ITask()
{
@Override
public Computer getOwner() {
public Computer getOwner()
{
return m_environment.getComputer();
}
@Override
public void execute() {
synchronized (m_peripherals) {
if (wrapper.isAttached()) {
public void execute()
{
synchronized( m_peripherals )
{
if( wrapper.isAttached() )
{
wrapper.detach();
}
}
}
}, null);
}, null );
// Queue a detachment event
m_environment.queueEvent( "peripheral_detach", new Object[] { Computer.s_sideNames[side] } );
@@ -288,14 +295,17 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
{
// Queue an attachment
final PeripheralWrapper wrapper = m_peripherals[side];
ComputerThread.queueTask( new ITask() {
ComputerThread.queueTask( new ITask()
{
@Override
public Computer getOwner() {
public Computer getOwner()
{
return m_environment.getComputer();
}
@Override
public void execute() {
public void execute()
{
synchronized( m_peripherals )
{
if( m_running && !wrapper.isAttached() )
@@ -323,12 +333,12 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
}
@Override
public void startup( )
public void startup()
{
synchronized( m_peripherals )
{
m_running = true;
for( int i=0; i<6; ++i )
for( int i = 0; i < 6; i++ )
{
PeripheralWrapper wrapper = m_peripherals[i];
if( wrapper != null && !wrapper.isAttached() )
@@ -340,12 +350,12 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
}
@Override
public void shutdown( )
public void shutdown()
{
synchronized( m_peripherals )
{
m_running = false;
for( int i=0; i<6; ++i )
for( int i = 0; i < 6; i++ )
{
PeripheralWrapper wrapper = m_peripherals[i];
if( wrapper != null && wrapper.isAttached() )
@@ -382,7 +392,7 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
{
synchronized( m_peripherals )
{
PeripheralWrapper p = m_peripherals[ side ];
PeripheralWrapper p = m_peripherals[side];
if( p != null )
{
present = true;
@@ -400,7 +410,7 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
{
synchronized( m_peripherals )
{
PeripheralWrapper p = m_peripherals[ side ];
PeripheralWrapper p = m_peripherals[side];
if( p != null )
{
type = p.getType();
@@ -422,7 +432,7 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
{
synchronized( m_peripherals )
{
PeripheralWrapper p = m_peripherals[ side ];
PeripheralWrapper p = m_peripherals[side];
if( p != null )
{
methods = p.getMethods();
@@ -431,9 +441,10 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
}
if( methods != null )
{
Map<Object,Object> table = new HashMap<>();
for(int i=0; i<methods.length; ++i ) {
table.put( i+1, methods[i] );
Map<Object, Object> table = new HashMap<>();
for( int i = 0; i < methods.length; i++ )
{
table.put( i + 1, methods[i] );
}
return new Object[] { table };
}
@@ -451,7 +462,7 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
PeripheralWrapper p;
synchronized( m_peripherals )
{
p = m_peripherals[ side ];
p = m_peripherals[side];
}
if( p != null )
{
@@ -472,7 +483,7 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
private int parseSide( Object[] args ) throws LuaException
{
String side = getString( args, 0 );
for( int n=0; n<Computer.s_sideNames.length; ++n )
for( int n = 0; n < Computer.s_sideNames.length; n++ )
{
if( side.equals( Computer.s_sideNames[n] ) )
{

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -25,7 +25,7 @@ public class RedstoneAPI implements ILuaAPI
{
m_environment = environment;
}
@Override
public String[] getNames()
{
@@ -64,10 +64,10 @@ public class RedstoneAPI implements ILuaAPI
case 0:
{
// getSides
Map<Object,Object> table = new HashMap<>();
for(int i=0; i< Computer.s_sideNames.length; ++i )
Map<Object, Object> table = new HashMap<>();
for( int i = 0; i < Computer.s_sideNames.length; i++ )
{
table.put( i+1, Computer.s_sideNames[i] );
table.put( i + 1, Computer.s_sideNames[i] );
}
return new Object[] { table };
}
@@ -152,11 +152,11 @@ public class RedstoneAPI implements ILuaAPI
}
}
}
private int parseSide( Object[] args ) throws LuaException
{
String side = getString( args, 0 );
for( int n=0; n<Computer.s_sideNames.length; ++n )
for( int n = 0; n < Computer.s_sideNames.length; n++ )
{
if( side.equals( Computer.s_sideNames[n] ) )
{

View File

@@ -1,3 +1,9 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.apis;
import dan200.computercraft.api.lua.LuaException;

View File

@@ -1,6 +1,6 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -28,7 +28,7 @@ public class TermAPI implements ILuaAPI
m_terminal = _environment.getTerminal();
m_environment = _environment.getComputerEnvironment();
}
@Override
public String[] getNames()
{
@@ -68,7 +68,7 @@ public class TermAPI implements ILuaAPI
"getCursorBlink",
};
}
public static int parseColour( Object[] args ) throws LuaException
{
int colour = getInt( args, 0 );
@@ -109,12 +109,15 @@ public class TermAPI implements ILuaAPI
{
// write
String text;
if( args.length > 0 && args[0] != null ) {
if( args.length > 0 && args[0] != null )
{
text = args[0].toString();
} else {
}
else
{
text = "";
}
synchronized( m_terminal )
{
m_terminal.write( text );
@@ -128,7 +131,7 @@ public class TermAPI implements ILuaAPI
int y = getInt( args, 0 );
synchronized( m_terminal )
{
m_terminal.scroll(y);
m_terminal.scroll( y );
}
return null;
}
@@ -172,7 +175,7 @@ public class TermAPI implements ILuaAPI
{
width = m_terminal.getWidth();
height = m_terminal.getHeight();
}
}
return new Object[] { width, height };
}
case 6:
@@ -260,7 +263,7 @@ public class TermAPI implements ILuaAPI
{
int hex = getInt( args, 1 );
double[] rgb = Palette.decodeRGB8( hex );
setColour( m_terminal, colour, rgb[ 0 ], rgb[ 1 ], rgb[ 2 ] );
setColour( m_terminal, colour, rgb[0], rgb[1], rgb[2] );
}
else
{
@@ -278,7 +281,7 @@ public class TermAPI implements ILuaAPI
int colour = 15 - parseColour( args );
synchronized( m_terminal )
{
if ( m_terminal.getPalette() != null )
if( m_terminal.getPalette() != null )
{
return ArrayUtils.toObject( m_terminal.getPalette().getColour( colour ) );
}
@@ -294,7 +297,7 @@ public class TermAPI implements ILuaAPI
}
}
}
private static int getHighestBit( int group )
{
int bit = 0;

View File

@@ -1,3 +1,9 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.apis.handles;
import com.google.common.base.Preconditions;

View File

@@ -1,3 +1,9 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.apis.handles;
import com.google.common.collect.ObjectArrays;
@@ -53,12 +59,11 @@ public class BinaryReadableHandle extends HandleGeneric
{
switch( method )
{
case 0:
// read
case 0: // read
checkOpen();
try
{
if( args.length > 0 && args[ 0 ] != null )
if( args.length > 0 && args[0] != null )
{
int count = getInt( args, 0 );
if( count < 0 )
@@ -73,38 +78,41 @@ public class BinaryReadableHandle extends HandleGeneric
if( count <= BUFFER_SIZE )
{
ByteBuffer buffer = ByteBuffer.allocate( count );
int read = m_reader.read( buffer );
if( read < 0 ) return null;
return new Object[] { read < count ? Arrays.copyOf( buffer.array(), read ) : buffer.array() };
}
else
{
// Read the initial set of characters, failing if none are read.
ByteBuffer buffer = ByteBuffer.allocate( BUFFER_SIZE );
int read = m_reader.read( buffer );
if( read < 0 ) return null;
int totalRead = read;
// If we failed to read "enough" here, let's just abort
if( totalRead >= count || read < BUFFER_SIZE )
if( read >= count || read < BUFFER_SIZE )
{
return new Object[] { Arrays.copyOf( buffer.array(), read ) };
}
// Build up an array of ByteBuffers. Hopefully this means we can perform less allocation
// Build up an array of ByteBuffers. Hopefully this means we can perform less allocation
// than doubling up the buffer each time.
int totalRead = read;
List<ByteBuffer> parts = new ArrayList<>( 4 );
parts.add( buffer );
while( totalRead < count && read >= BUFFER_SIZE )
while( read >= BUFFER_SIZE && totalRead < count )
{
buffer = ByteBuffer.allocate( BUFFER_SIZE );
totalRead += read = m_reader.read( buffer );
buffer = ByteBuffer.allocate( Math.min( BUFFER_SIZE, count - totalRead ) );
read = m_reader.read( buffer );
if( read < 0 ) break;
totalRead += read;
parts.add( buffer );
}
// Now just copy all the bytes across!
byte[] bytes = new byte[ totalRead ];
byte[] bytes = new byte[totalRead];
int pos = 0;
for( ByteBuffer part : parts )
{
@@ -125,8 +133,7 @@ public class BinaryReadableHandle extends HandleGeneric
{
return null;
}
case 1:
// readAll
case 1: // readAll
checkOpen();
try
{
@@ -154,9 +161,8 @@ public class BinaryReadableHandle extends HandleGeneric
{
return null;
}
case 2:
case 2: // readLine
{
// readLine
checkOpen();
boolean withTrailing = optBoolean( args, 0, false );
try
@@ -190,12 +196,10 @@ public class BinaryReadableHandle extends HandleGeneric
return null;
}
}
case 3:
//close
case 3: // close
close();
return null;
case 4:
// seek
case 4: // seek
checkOpen();
return handleSeek( m_seekable, args );
default:

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