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

Compare commits

...

62 Commits

Author SHA1 Message Date
SquidDev
d173787a94 Another backwards compat change
Plethora only implements getPos on older versions, so we need to stub
out both.
2019-01-21 17:36:25 +00:00
SquidDev
d5aea26f3a Bump version
It's pretty soon after the previous release (10 days!) but there's a
couple of important bug fixes and some nice improvements.
2019-01-21 11:02:29 +00:00
SquidDev
2681e578c4 Merge pull request #101 from SquidDev-CC/feature/no-ticking
Make several tile entities non-ticking, hopefully reducing
server load.
2019-01-21 08:29:42 +00:00
SquidDev
1f498dcc73 Backwards compat patch for Plethora
Ughghgghghr.
2019-01-20 16:16:02 +00:00
SquidDev
83b01d35eb Make monitors non-ticking
- Convert terminals from a polling-based system to a more event-driven
   one: they now accept an onChanged callback, which marks the parent as
   dirty.
 - Schedule ticks when monitors are marked as dirty.
 - Add several missing @Overrides. This has nothing to do with the rest
   of the changes, but I'm bad at good git practice.
2019-01-20 15:39:11 +00:00
SquidDev
8a7e651c99 Several miscellaneous changes
- Merge BlockPeripheralBase and BlockPeripheral, as no other classes
   extended the former.
 - Make BlockPeripheral use ITilePeripheral instead of
   TilePeripheralBase. This allows us to use other, non-ticking tiles
   instead.
 - Convert advanced and normal modems to extend from a generic
   TileWirelessModemBase class, and thus neither now tick.
2019-01-20 14:06:41 +00:00
SquidDev
80a5759bae Make advanced modems non-ticking
- Move getPeripheralType and getLabel from IPeripheralTile to
   TilePeripheralBase. These were mostly constant on all other tiles, so
   were rather redundant.
 - Make TileAdvancedModem extend TileGeneric, and be non-ticking (using
   similar logic to all other blocks).
2019-01-20 09:34:15 +00:00
SquidDev
e8a4fbb4e3 Make TileCable non-ticking
- Move updateTick onto BlockGeneric/TileGeneric instead of the full
   wired modem, as it is used by several tiles now.
 - Make *Cable extend from *Generic, and schedule ticks instead of
   running every tick.
2019-01-19 22:25:38 +00:00
SquidDev
0ce67afcc1 Be less strict in comparing upgrade crafting items
We currently generate the crafting item once when the upgrade is first
created, and cache it for the duration of the game. As the item never
changes throughout the game, and constructing a stack is a little
expensive (we need to fire an event, etc...), the caching is worth
having.

However, some mods may register capabilities after we've constructed our
ItemStack. This means the capability will be present on other items but
not ours, meaning they are not considered equivalent, and thus the item
cannot be equipped.

In order to avoid this, we use compare items using their share-tag, like
Forge's IngredientNBT. This means the items must still be "mostly" the
same (same enchantements, etc...), but allow differing capabilities.

See NillerMedDild/Enigmatica2Expert#655 for the original bug report -
in this case, Astral Sourcery was registering the capability in init,
but we construct upgrades just before then.
2019-01-19 21:57:21 +00:00
SquidDev
a8dad23fa3 Begin investigations into reducing ticking of TEs
- Move IDirectionalTile constraint from IPeripheralTile to
   TilePeripheralBase.
 - Make *WiredModemFull no longer inherit from *PeripheralBase. While
   there is still some shared logic (namely in the syncing of "anim"),
   it's largely fine as we don't store label or direction in NBT.
 - Add a TickScheduler. This is a thread-safe version of
   World.scheduleUpdate. We simply build a set of all TEs, and schedule
   them to be updated the next tick.
 - Make ModemState receive an "onChanged" listener, which is fired
   whenever the modem changes.
 - Make WiredModemFull no longer tick, instead scheduling updates when
   it is first loaded and whenever the modem changes.
2019-01-19 10:16:41 +00:00
SquidDev
443e0f8f76 Remove FileSystemMount and rewrite JarMount
FileSystemMount was originally added to allow using ReadableByteChannels
instead of InputStreams. However, as zip files do not allow seeking,
there is no benefit of using them over the original JarMount (which we
need to preserve for backwards compatibility).

Instead of maintaining two near-identical mounts, we remove the
FileSystemMount and rewrite the JarMount implementation with several
improvements:

 - Rewrite the jar scanning algorithm to be closer to 1.13+'s data pack
   mount. This means we no longer require the jar file to have
   directories before the file (though this was not a problem in
   practice).
 - Add all JarMounts to a ReferenceQueue, closing up the ZipFile when
   they have been garbage collected (fixes #100).
 - Cache the contents of all files for 60 seconds (with some constraints
   on size). This allows us to seek on ROM files too (assuming they are
   small), by reading the whole thing into memory.
   The cache is shared across all mounts, and has a 64MiB limit, and
   thus should not have an adverse impact on memory.
2019-01-16 17:25:46 +00:00
SquidDev
a838595e1e Derive upgrade adjectives from its ID
This is done in 1.13+ for items and blocks, so we might as well do it
for upgrades now. Note we can't do it for ender pocket modems, as the
upgrade ID is spelled incorrectly there.
2019-01-14 10:42:13 +00:00
SquidDev
61daab910e Simplify placement logic of various blocks
- For those where placement is stored in the metadata (computers),
   don't also set it in onBlockPlacedBy.
 - Remove .getDefaultState(int, EnumFacing) override, as this means we
   have more control over what is passed to us (namely, placer's
   direction too).
2019-01-14 10:27:19 +00:00
SquidDev
7fd19c43e9 Try to hide CommandCopy from most completions.
"/computercraf" auto-completes to "/computercraft_copy" instead of
"/computercraft", which is rather annoying, as the former is not meant
to be used normally.
2019-01-14 10:10:52 +00:00
SquidDev
ce0685c31f Move our message model to be closer to Forge's
It's rather embarassing that it's been restructured _again_, but I think
this is a nice middle-ground. The previous implementation was written
mostly for Fabric, which doesn't always map perfectly to Forge.

 - Move the message identifier into the registration phrase. It's not
   really a property of the message itself, rather a property of the
   registry, so better suited there.

 - Move message handling into the message itself. Honestly, it was just
   ending up being rather messy mixing the logic in two places.

   This also means we can drop some proxy methods, as it's easier to
   have conditionally loaded methods.

 - Move network registry into a dedicated class, as that's what we're
   doing for everything else.
2019-01-14 10:09:22 +00:00
SquidDev
e33f852baa Store references to the registered items
This means we can avoid several rather ugly instances of getItemBlock
and a cast. We also derive the ItemBlock's registered name from the
block's name, which makes the register a little less ugly.
2019-01-12 19:01:32 +00:00
SquidDev
227d5e9e69 Fix cables not rendering the breaking steps
The fact that it's taken this long for anyone to notice this didn't work
is rather embarassing.
2019-01-12 18:35:43 +00:00
SquidDev
1c648850ab Even more proxy pruning
- Move the "world directory" getter out of the proxy - we can just use
   Forge's code here.
 - Remove the server proxies, as both were empty. We don't tend to
   register any dedicated-server specific code, so I think we can leave
   them out.
2019-01-12 18:23:22 +00:00
SquidDev
63691707fc Move registration methods into a separate class
- All "named" entries (blocks, items, recipes, TEs and pocket/turtle
   upgrades) are registeredin one place.
 - Most client side models/textures are registered in ClientRegistry -
   we can't do item colours or TEs for now, as these aren't event based.
 - A little cleanup to how we handle ItemPocketComputer models.
2019-01-12 17:51:26 +00:00
SquidDev
5d97b9c8f3 Utilise @Mod.EventBusSubscriber a little more
This offers several advantages

 - Less registration code: the subscribers are reigstered automatically,
   and we don't need to worry about sided-proxies.
 - We no longer have so many .instance() calls.
2019-01-12 16:27:40 +00:00
SquidDev
77666d7399 Some more minor cleanups
- Move SpeakerPeripheral's TileSpeaker functionality to a sub-class.
 - Use Vec3d instead of BlockPos for speaker's positions.
 - Use WorldUtil.dropItemStack to spawn in items.
 - Remove redundant lock on ModemPeripheral.
2019-01-12 15:43:18 +00:00
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
424 changed files with 11360 additions and 11678 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.14"
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>

File diff suppressed because it is too large Load Diff

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,156 @@
/*
* 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.ComputerCraft;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import javax.annotation.Nonnull;
/**
* Registers textures and models for items.
*/
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
public class ClientRegistry
{
private static final String[] TURTLE_UPGRADES = {
"turtle_modem_off_left",
"turtle_modem_on_left",
"turtle_modem_off_right",
"turtle_modem_on_right",
"turtle_crafting_table_left",
"turtle_crafting_table_right",
"advanced_turtle_modem_off_left",
"advanced_turtle_modem_on_left",
"advanced_turtle_modem_off_right",
"advanced_turtle_modem_on_right",
"turtle_speaker_upgrade_left",
"turtle_speaker_upgrade_right",
};
@SubscribeEvent
public static void registerModels( ModelRegistryEvent event )
{
// Register item models
registerUniversalItemModel( ComputerCraft.Items.computer, "computer" );
registerItemModel( ComputerCraft.Items.commandComputer, 0, "command_computer" );
registerItemModel( ComputerCraft.Items.pocketComputer, 0, "pocket_computer" );
registerItemModel( ComputerCraft.Items.pocketComputer, 1, "advanced_pocket_computer" );
registerItemModel( ComputerCraft.Items.peripheral, 0, "peripheral" );
registerItemModel( ComputerCraft.Items.peripheral, 1, "wireless_modem" );
registerItemModel( ComputerCraft.Items.peripheral, 2, "monitor" );
registerItemModel( ComputerCraft.Items.peripheral, 3, "printer" );
registerItemModel( ComputerCraft.Items.peripheral, 4, "advanced_monitor" );
registerItemModel( ComputerCraft.Items.cable, 0, "cable" );
registerItemModel( ComputerCraft.Items.cable, 1, "wired_modem" );
registerItemModel( ComputerCraft.Items.advancedModem, 0, "advanced_modem" );
registerItemModel( ComputerCraft.Items.peripheral, 5, "speaker" );
registerItemModel( ComputerCraft.Items.wiredModemFull, 0, "wired_modem_full" );
registerUniversalItemModel( ComputerCraft.Items.disk, "disk" );
registerItemModel( ComputerCraft.Items.diskExpanded, 0, "disk_expanded" );
registerItemModel( ComputerCraft.Items.treasureDisk, 0, "treasure_disk" );
registerItemModel( ComputerCraft.Items.printout, 0, "printout" );
registerItemModel( ComputerCraft.Items.printout, 1, "pages" );
registerItemModel( ComputerCraft.Items.printout, 2, "book" );
String[] extraTurtleModels = new String[] { "turtle", "turtle_advanced", "turtle_white", "turtle_elf_overlay" };
registerUniversalItemModel( ComputerCraft.Items.turtle, "turtle_dynamic", extraTurtleModels );
registerUniversalItemModel( ComputerCraft.Items.turtleExpanded, "turtle_dynamic", extraTurtleModels );
registerUniversalItemModel( ComputerCraft.Items.turtleAdvanced, "turtle_dynamic", extraTurtleModels );
}
@SubscribeEvent
public static void onTextureStitchEvent( TextureStitchEvent.Pre event )
{
// Load all textures for upgrades
TextureMap map = event.getMap();
for( String upgrade : TURTLE_UPGRADES )
{
IModel model = ModelLoaderRegistry.getModelOrMissing( new ResourceLocation( "computercraft", "block/" + upgrade ) );
for( ResourceLocation texture : model.getTextures() )
{
map.registerSprite( texture );
}
}
}
@SubscribeEvent
public static void onModelBakeEvent( ModelBakeEvent event )
{
// Load all upgrade models
for( String upgrade : TURTLE_UPGRADES )
{
loadBlockModel( event, upgrade );
}
}
private static void registerItemModel( Item item, int damage, String name )
{
ResourceLocation location = new ResourceLocation( ComputerCraft.MOD_ID, name );
final ModelResourceLocation res = new ModelResourceLocation( location, "inventory" );
ModelBakery.registerItemVariants( item, location );
ModelLoader.setCustomModelResourceLocation( item, damage, res );
}
private static void registerUniversalItemModel( Item item, String mainModel, String... extraModels )
{
ResourceLocation mainLocation = new ResourceLocation( ComputerCraft.MOD_ID, mainModel );
ResourceLocation[] modelLocations = new ResourceLocation[extraModels.length + 1];
modelLocations[0] = mainLocation;
for( int i = 0; i < extraModels.length; i++ )
{
modelLocations[i + 1] = new ResourceLocation( ComputerCraft.MOD_ID, extraModels[i] );
}
ModelBakery.registerItemVariants( item, modelLocations );
final ModelResourceLocation mainModelLocation = new ModelResourceLocation( mainLocation, "inventory" );
ModelLoader.setCustomMeshDefinition( item, new ItemMeshDefinition()
{
@Nonnull
@Override
public ModelResourceLocation getModelLocation( @Nonnull ItemStack stack )
{
return mainModelLocation;
}
} );
}
private static void loadBlockModel( ModelBakeEvent event, String name )
{
IModel model = ModelLoaderRegistry.getModelOrMissing( new ResourceLocation( ComputerCraft.MOD_ID, "block/" + name ) );
IBakedModel bakedModel = model.bake(
model.getDefaultState(), DefaultVertexFormats.ITEM,
location -> Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite( location.toString() )
);
event.getModelRegistry().putObject( new ModelResourceLocation( ComputerCraft.MOD_ID + ":" + name, "inventory" ), bakedModel );
}
}

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,46 @@
/*
* 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.ComputerCraft;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.relauncher.Side;
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
public final class FrameInfo
{
private static int tick;
private static long renderFrame;
private FrameInfo()
{
}
public static boolean getGlobalCursorBlink()
{
return (tick / 8) % 2 == 0;
}
public static long getRenderFrame()
{
return renderFrame;
}
@SubscribeEvent
public static void onTick( TickEvent.ClientTickEvent event )
{
if( event.phase == TickEvent.Phase.START ) tick++;
}
@SubscribeEvent
public static void onRenderTick( TickEvent.RenderTickEvent event )
{
if( event.phase == TickEvent.Phase.START ) renderFrame++;
}
}

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.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,72 +11,23 @@ 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;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.IBakedModel;
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.renderer.texture.TextureMap;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.resources.IReloadableResourceManager;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.client.resources.SimpleReloadableResourceManager;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
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
registerForgeHandlers();
}
@SubscribeEvent
public void registerModels( ModelRegistryEvent event )
{
// Register item models
ItemMeshDefinition turtleMeshDefinition = new ItemMeshDefinition()
{
private ModelResourceLocation turtle_dynamic = new ModelResourceLocation( "computercraft:turtle_dynamic", "inventory" );
@Nonnull
@Override
public ModelResourceLocation getModelLocation( @Nonnull ItemStack stack )
{
return turtle_dynamic;
}
};
String[] turtleModelNames = new String[] {
"turtle_dynamic",
"turtle", "turtle_advanced",
"turtle_white",
"turtle_elf_overlay"
};
registerItemModel( ComputerCraft.Blocks.turtle, turtleMeshDefinition, turtleModelNames );
registerItemModel( ComputerCraft.Blocks.turtleExpanded, turtleMeshDefinition, turtleModelNames );
registerItemModel( ComputerCraft.Blocks.turtleAdvanced, turtleMeshDefinition, turtleModelNames );
super.preInit();
MinecraftForge.EVENT_BUS.register( new ForgeHandlers() );
}
@Override
@@ -85,133 +36,7 @@ public class CCTurtleProxyClient extends CCTurtleProxyCommon
super.init();
// Setup turtle colours
Minecraft.getMinecraft().getItemColors().registerItemColorHandler(
new TurtleItemColour(),
ComputerCraft.Blocks.turtle, ComputerCraft.Blocks.turtleExpanded, ComputerCraft.Blocks.turtleAdvanced
);
// Setup renderers
ClientRegistry.bindTileEntitySpecialRenderer( TileTurtle.class, new TileEntityTurtleRenderer() );
}
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<names.length; ++i )
{
resources[i] = new ResourceLocation( "computercraft:" + names[i] );
}
ModelBakery.registerItemVariants( item, resources );
ModelLoader.setCustomMeshDefinition( item, definition );
}
private void registerForgeHandlers()
{
ForgeHandlers handlers = new ForgeHandlers();
MinecraftForge.EVENT_BUS.register( handlers );
}
public static class ForgeHandlers
{
private static final String[] TURTLE_UPGRADES = {
"turtle_modem_off_left",
"turtle_modem_on_left",
"turtle_modem_off_right",
"turtle_modem_on_right",
"turtle_crafting_table_left",
"turtle_crafting_table_right",
"advanced_turtle_modem_off_left",
"advanced_turtle_modem_on_left",
"advanced_turtle_modem_off_right",
"advanced_turtle_modem_on_right",
"turtle_speaker_upgrade_left",
"turtle_speaker_upgrade_right",
};
private TurtleSmartItemModel m_turtleSmartItemModel;
public ForgeHandlers()
{
m_turtleSmartItemModel = new TurtleSmartItemModel();
IResourceManager resourceManager = Minecraft.getMinecraft().getResourceManager();
if( resourceManager instanceof SimpleReloadableResourceManager )
{
SimpleReloadableResourceManager reloadableResourceManager = (SimpleReloadableResourceManager)resourceManager;
reloadableResourceManager.registerReloadListener( m_turtleSmartItemModel );
}
}
@SubscribeEvent
public void onTick( TickEvent.ClientTickEvent event )
{
if( event.phase == TickEvent.Phase.END )
{
TurtleBrain.cleanupBrains();
}
}
@SubscribeEvent
public void onTextureStitchEvent( TextureStitchEvent.Pre event )
{
// Load all textures for upgrades
TextureMap map = event.getMap();
for( String upgrade : TURTLE_UPGRADES )
{
IModel model = ModelLoaderRegistry.getModelOrMissing( new ResourceLocation( "computercraft", "block/" + upgrade ) );
for( ResourceLocation texture : model.getTextures() )
{
map.registerSprite( texture );
}
}
}
@SubscribeEvent
public void onModelBakeEvent( ModelBakeEvent event )
{
// Load all upgrade models
for( String upgrade : TURTLE_UPGRADES )
{
loadModel( event, upgrade );
}
loadSmartModel( event, "turtle_dynamic", m_turtleSmartItemModel );
}
private void loadModel( ModelBakeEvent event, String name )
{
IModel model = ModelLoaderRegistry.getModelOrMissing(
new ResourceLocation( "computercraft", "block/" + name )
);
IBakedModel bakedModel = model.bake(
model.getDefaultState(),
DefaultVertexFormats.ITEM,
location -> Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite( location.toString() )
);
event.getModelRegistry().putObject(
new ModelResourceLocation( "computercraft:" + name, "inventory" ),
bakedModel
);
}
private void loadSmartModel( ModelBakeEvent event, String name, IBakedModel smartModel )
{
event.getModelRegistry().putObject(
new ModelResourceLocation( "computercraft:" + name, "inventory" ),
smartModel
);
}
}
private static class TurtleItemColour implements IItemColor
{
@Override
public int colorMultiplier( @Nonnull ItemStack stack, int tintIndex )
{
Minecraft.getMinecraft().getItemColors().registerItemColorHandler( ( stack, tintIndex ) -> {
if( tintIndex == 0 )
{
ItemTurtleBase turtle = (ItemTurtleBase) stack.getItem();
@@ -220,6 +45,30 @@ public class CCTurtleProxyClient extends CCTurtleProxyCommon
}
return 0xFFFFFF;
}, ComputerCraft.Blocks.turtle, ComputerCraft.Blocks.turtleExpanded, ComputerCraft.Blocks.turtleAdvanced );
// Setup renderers
ClientRegistry.bindTileEntitySpecialRenderer( TileTurtle.class, new TileEntityTurtleRenderer() );
}
public static class ForgeHandlers
{
private final TurtleSmartItemModel m_turtleSmartItemModel = new TurtleSmartItemModel();
ForgeHandlers()
{
IResourceManager resourceManager = Minecraft.getMinecraft().getResourceManager();
if( resourceManager instanceof IReloadableResourceManager )
{
((IReloadableResourceManager) resourceManager).registerReloadListener( m_turtleSmartItemModel );
}
}
@SubscribeEvent
public void onModelBakeEvent( ModelBakeEvent event )
{
event.getModelRegistry().putObject( new ModelResourceLocation( "computercraft:turtle_dynamic", "inventory" ), m_turtleSmartItemModel );
}
}
}

View File

@@ -1,219 +1,57 @@
/*
* 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.render.*;
import dan200.computercraft.client.render.TileEntityCableRenderer;
import dan200.computercraft.client.render.TileEntityMonitorRenderer;
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.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.Mod;
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();
// Register any client-specific commands
ClientCommandHandler.instance.registerCommand( CommandCopy.INSTANCE );
}
@SubscribeEvent
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.peripheral, 0, "peripheral" );
registerItemModel( ComputerCraft.Blocks.peripheral, 1, "wireless_modem" );
registerItemModel( ComputerCraft.Blocks.peripheral, 2, "monitor" );
registerItemModel( ComputerCraft.Blocks.peripheral, 3, "printer" );
registerItemModel( ComputerCraft.Blocks.peripheral, 4, "advanced_monitor" );
registerItemModel( ComputerCraft.Blocks.cable, 0, "cable" );
registerItemModel( ComputerCraft.Blocks.cable, 1, "wired_modem" );
registerItemModel( ComputerCraft.Blocks.commandComputer, "command_computer" );
registerItemModel( ComputerCraft.Blocks.advancedModem, "advanced_modem" );
registerItemModel( ComputerCraft.Blocks.peripheral, 5, "speaker" );
registerItemModel( ComputerCraft.Blocks.wiredModemFull, "wired_modem_full" );
registerItemModel( ComputerCraft.Items.disk, "disk" );
registerItemModel( ComputerCraft.Items.diskExpanded, "disk_expanded" );
registerItemModel( ComputerCraft.Items.treasureDisk, "treasure_disk" );
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",
} );
}
@Override
public void init()
{
super.init();
// Load textures
Minecraft mc = Minecraft.getMinecraft();
m_fixedWidthFontRenderer = new FixedWidthFontRenderer( mc.getTextureManager() );
// Setup
mc.getItemColors().registerItemColorHandler( new DiskColorHandler( ComputerCraft.Items.disk ), ComputerCraft.Items.disk );
mc.getItemColors().registerItemColorHandler( new DiskColorHandler( ComputerCraft.Items.diskExpanded ), ComputerCraft.Items.diskExpanded );
mc.getItemColors().registerItemColorHandler( ( stack, layer ) ->
{
mc.getItemColors().registerItemColorHandler( ( stack, layer ) -> {
switch( layer )
{
case 0:
@@ -239,356 +77,11 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
ClientRegistry.bindTileEntitySpecialRenderer( TileCable.class, new TileEntityCableRenderer() );
}
private void registerItemModel( Block block, int damage, String name )
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
public static class ForgeHandlers
{
registerItemModel( Item.getItemFromBlock( block ), damage, name );
}
private void registerItemModel( Item item, int damage, String name )
{
ModelResourceLocation res = new ModelResourceLocation( "computercraft:" + name, "inventory" );
ModelBakery.registerItemVariants( item, new ResourceLocation( "computercraft", name ) );
ModelLoader.setCustomModelResourceLocation( item, damage, res );
}
private void registerItemModel( Block block, String name )
{
registerItemModel( Item.getItemFromBlock( block ), name );
}
private void registerItemModel( Item item, String name )
{
final ModelResourceLocation res = new ModelResourceLocation( "computercraft:" + name, "inventory" );
ModelBakery.registerItemVariants( item, new ResourceLocation( "computercraft", name ) );
ModelLoader.setCustomMeshDefinition( item, new ItemMeshDefinition()
{
@Nonnull
@Override
public ModelResourceLocation getModelLocation( @Nonnull ItemStack stack )
{
return res;
}
} );
}
private void registerItemModel( Block block, ItemMeshDefinition definition, String[] names )
{
registerItemModel( Item.getItemFromBlock( block ), definition, names );
}
private void registerItemModel( Item item, ItemMeshDefinition definition, String[] names )
{
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 RenderOverlayCable() );
MinecraftForge.EVENT_BUS.register( new ItemPocketRenderer() );
MinecraftForge.EVENT_BUS.register( new ItemPrintoutRenderer() );
}
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 )
public static void onWorldUnload( WorldEvent.Unload event )
{
if( event.getWorld().isRemote )
{
@@ -597,7 +90,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,22 +16,17 @@ 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.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT;
@@ -34,48 +35,27 @@ import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_WIDTH;
/**
* Emulates map rendering for pocket computers
*/
@SideOnly(Side.CLIENT)
public class ItemPocketRenderer
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
public final class ItemPocketRenderer extends ItemMapLikeRenderer
{
private static final ItemPocketRenderer INSTANCE = new ItemPocketRenderer();
private ItemPocketRenderer()
{
}
@SubscribeEvent
public void renderItem( RenderSpecificHandEvent event )
public static void renderItem( RenderSpecificHandEvent event )
{
ItemStack stack = event.getItemStack();
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();
INSTANCE.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 +69,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 +133,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 +151,7 @@ public class ItemPocketRenderer
// And render the cursor;
int tx = terminal.getCursorX(), ty = terminal.getCursorY();
if( terminal.getCursorBlink() && ComputerCraft.getGlobalCursorBlink() &&
if( terminal.getCursorBlink() && FrameInfo.getGlobalCursorBlink() &&
tx >= 0 && ty >= 0 && tx < tw && ty < th )
{
TextBuffer cursorColour = new TextBuffer( "0123456789abcdef".charAt( terminal.getTextColour() ), 1 );
@@ -189,76 +169,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,18 +1,20 @@
/*
* 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.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT;
import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_WIDTH;
@@ -20,114 +22,31 @@ 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
/**
* Emulates map and item-frame rendering for prinouts
*/
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
public final class ItemPrintoutRenderer extends ItemMapLikeRenderer
{
private static final ItemPrintoutRenderer INSTANCE = new ItemPrintoutRenderer();
private ItemPrintoutRenderer()
{
}
@SubscribeEvent
public void onRenderInHand( RenderSpecificHandEvent event )
public static void onRenderInHand( RenderSpecificHandEvent event )
{
ItemStack stack = event.getItemStack();
if( stack.getItem() != ComputerCraft.Items.printout ) return;
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();
INSTANCE.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
@@ -144,7 +63,7 @@ public class ItemPrintoutRenderer
}
@SubscribeEvent
public void onRenderInFrame( RenderItemInFrameEvent event )
public static void onRenderInFrame( RenderItemInFrameEvent event )
{
ItemStack stack = event.getItem();
if( stack.getItem() != ComputerCraft.Items.printout ) return;
@@ -162,6 +81,7 @@ public class ItemPrintoutRenderer
drawPrintout( stack );
GlStateManager.enableLighting();
GlStateManager.disableBlend();
}
private static void drawPrintout( ItemStack stack )

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,23 +18,29 @@ 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;
import net.minecraft.world.World;
import net.minecraftforge.client.event.DrawBlockHighlightEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import org.lwjgl.opengl.GL11;
public class RenderOverlayCable
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
public final 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;
private RenderOverlayCable()
{
}
@SubscribeEvent
public void drawHighlight( DrawBlockHighlightEvent event )
public static void drawHighlight( DrawBlockHighlightEvent event )
{
if( event.getTarget().typeOfHit != RayTraceResult.Type.BLOCK ) return;
@@ -38,13 +50,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 +72,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.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.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,10 +11,12 @@ 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 );
@Override
default void update()
{
advance( 0.05 );

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;

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