1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2025-10-15 22:17:39 +00:00

Compare commits

...

715 Commits

Author SHA1 Message Date
SquidDev
51e787f631 Bump version and update feature list 2018-10-24 12:49:35 +01:00
SquidDev
8080699030 Couple of minor improvements to the alternative mount implementation
- Rename openStreamFor* methods to more accurate openChannelFor*
 - Fix ArrayByteChannel having an incorrect .position() implementation

Cherry-picked from the PR against dan200/ComputerCraft
2018-10-24 12:39:22 +01:00
SquidDev
e555f9f7f0 Merge pull request #575 from SquidDev-CC/ComputerCraft/feature/file-seeking
Rewrite file systems to use ByteChannels
2018-10-24 12:20:53 +01:00
SquidDev
822db6e9b5 Add support for binary websockets
- Add an argument to send which controls whether it's a binary message
   or not. This is a little ugly, but it's probably more effective than
   anything else.
 - Fix binary frames not correctly queueing the correct data in the
   message event.

Closes #69
2018-10-23 12:15:40 +01:00
SquidDev
ac1f30ef43 Clamp the volume for all sounds, rather than just notes
This restores the previous behaviour.
2018-10-12 12:05:31 +01:00
SquidDev
0fc1b8c46b Merge pull request #578 from SquidDev-CC/ComputerCraft/feature/speaker-sound
Change speakers to use the SPacketCustomSound packet instead
2018-10-10 16:57:34 +01:00
SquidDev
e7c19bcf55 Change speakers to use the SPacketCustomSound packet instead
The method to register new SoundEvents is private, which means that few
(if any) mods actually register them. Consequently, one could not use
the speaker to play any modded sound, as they weren't registered on the
server side.

Using SPacketCustomSound does mean we can no longer determine if a sound
exists or not, but I think a price I'm willing to pay in order to allow
playing modded sounds.
2018-10-10 08:46:30 +01:00
SquidDev
63ca8aca4c Merge pull request #68 from Vexatos/patch-1
Create de_de.lang
2018-10-02 16:47:42 +01:00
Vexatos
2caa9c57fc Create de_de.lang 2018-10-02 15:43:43 +02:00
SquidDev
33fad2da15 Merge pull request #577 from SquidDev-CC/ComputerCraft/feature/get-blink
Add .getCursorBlink to monitors and terminals
2018-09-28 16:23:00 +01:00
SquidDev
518eefbe10 Rewrite file systems to use ByteChannels
This replaces the existing IMount openFor* method with openChannelFor*
ones, which return an appropriate byte channel instead.

As channels are not correctly closed when GCed, we introduce a
FileSystemWrapper. We store a weak reference to this, and when it is
GCed or the file closed, we will remove it from our "open file" set and
ensure any underlying buffers are closed.

While this change may seem a little odd, it does introduce some
benefits:

 - We can replace JarMount with a more general FileSystemMount. This
   does assume a read-only file system, but could technically be used
   for other sources.

 - Add support for seekable (binary) handles. We can now look for
   instances of SeekableByteChannel and dynamically add it. This works
   for all binary filesystem and HTTP streams.

 - Rewrite the io library to more accurately emulate PUC Lua's
   implementation. We do not correctly implement some elements (most
   noticably "*n", but it's a definite improvement.
2018-09-26 10:00:17 +01:00
SquidDev
1ba73454c1 Add .getCursorBlink to monitors and terminals
Closes #576
2018-09-23 09:34:28 +01:00
SquidDev
ee4735c17c Merge pull request #573 from osmarks/ComputerCraft/patch-1
Fix a crash in rednet `repeat`
2018-09-09 17:49:24 +01:00
Oliver Marks
b008edae90 Fix a crash in rednet repeat
This crash can be triggered remotely by specially constructed rednet messages, making this a bit of a problem, as any repeaters can be remotely crashed.
2018-09-08 21:55:36 +01:00
SquidDev
c6bd88f3ad Attempt to cut out a lot of synchronized calls
A lot of these don't actually have any effect as they'll only be called
on the main thread or they are getters where the state is guaranteed to
be consistent whenever it is accessed.

Hopefully this'll reduce the chance of world updates being blocked by
waiting for peripheral locks to be released.
2018-08-25 21:17:48 +01:00
SquidDev
efa57521c7 Bump version to 1.8pr1.8
While there haven't been a lot of changes, there's been a couple of bug
fixes and nice improvements.
2018-08-25 10:58:54 +01:00
SquidDev
4700f8831b Add a pull request template
Again, not entirely a fan of these, but there's been several PRs
which would have been better off targeting the original repo.
2018-08-24 17:37:20 +01:00
SquidDev
9428bee316 Merge pull request #65 from apemanzilla/fix/drop-consumer-overflow
Prevent stack overflows when using turtle.place() with a full inventory
2018-08-23 08:04:07 +01:00
apemanzilla
89c7183a1d Prevent stack overflows when using turtle.place() with a full inventory 2018-08-23 07:56:50 +01:00
SquidDev
d2a9e7e458 Reset a few more flags when rendering printouts
Closes #63
2018-08-13 22:25:58 +01:00
SquidDev
1774f1a079 Merge pull request #566 from SquidDev-CC/ComputerCraft/feature/tiny-lua-wins
A couple of small improvements to CraftOS
2018-08-12 15:49:19 +01:00
SquidDev
de1307913b A couple of small improvements to CraftOS
- Make window.reposition's argument validation a little more strict.
   Previously it would accept `window.reposition(x, y, width)` (no
   height argument), just not act upon it.
 - Use select instead of table.unpack within `pastebin run`.
 - Use `parallel.waitForAny` instead of `waitForAll` within the dance
   program.
 - Pipe the entire help file into `textutils.pagedPrint`, rather than
   doing it line by line.
 - Remove bytecode loading disabling from bios.lua. This never worked
   correctly, and serves little purpose as LuaJ is not vulnerable to
   such exploits.
2018-08-12 08:23:17 +01:00
SquidDev
093132533d Add charset bundled cable integration
- Bump MinecraftForge version so we don't crash on load. Oh boy, all
   the deprecation warnings.
 - Inject IBundledEmitter and IBundledReceiver capabilities onto all
   TileGenerics.
 - Register a IBundledRedstoneProvider instance for IBundledEmitter.
2018-08-11 10:49:21 +01:00
SquidDev
0685be6bfa Add issue templates
I'm not entirely a fan of massive templates, but there's 
been a couple of lacklustre issues recently, so it's probably
good to formalise my guidelines.
2018-08-04 10:52:26 +01:00
SquidDev
f40733e9a6 Error when missing computers after executing the command
This allows you to automate running various commands and still have them
"work" if some computers are not loaded.

Closes #47
2018-08-04 10:39:44 +01:00
SquidDev
a3d1cff298 Bump Cobalt version
This should allow us to do SquidDev-CC/mbs#18 due to the debug
improvements.
2018-08-03 20:58:20 +01:00
SquidDev
b8957cab5c Update to the latest mappings
This is a preliminary for updating to 1.13, as many of the name changes
apply to both. This will make it harder to remain consistent with
actual CC, though that will be less of a consideration when 1.13 hits.
2018-07-24 09:27:05 +01:00
SquidDev
3ac8dde779 Bump version 2018-07-09 21:02:20 +01:00
SquidDev
17dace979a Merge pull request #562 from SquidDev-CC/ComputerCraft/hotfix/turtle-sign-place
Be a little smarter about our detection of the placed sign
2018-07-09 20:57:42 +01:00
SquidDev
d405316a4b Be a little smarter about our detection of the placed sign
When placing a sign against a tile entity (such as a turtle or chest),
we would consider that block the "placed" one instead, meaning the text
was never set. This solution isn't entirely ideal either, but short of
capturing block snapshots I'm not sure of a better solution.

Fixes #552
2018-07-09 20:53:49 +01:00
SquidDev
7e18f2cead Clear the turtle's inventory on load 2018-07-09 18:22:42 +01:00
SquidDev
000786a1a7 Merge pull request #560 from SquidDev-CC/ComputerCraft/hotfix/turtle-destroy
Rewrite turtle block destroying
2018-07-08 23:01:13 +01:00
SquidDev
0bf13562b9 Provide a more direct way to get the related computer
Effectively shift extracting the computer away from Plethora into CC:T.
Ideally we wouldn't need this at all, but Plethora does some funky
things with tick timings.

See SquidDev-CC/plethora#125
2018-07-08 22:48:50 +01:00
SquidDev
45a189e834 Cache a turtle's fake player
Player construction can get a little expensive, and this is exacerbated
by Sponge. We now cache a turtle's fake player (updating the position
every time it is requested) in order to reduce this overhead.
2018-07-08 15:21:42 +01:00
SquidDev
0ce6f34a09 Rewrite printout rendering
- The current page is always centred when rendering in a GUI, with
   the turned pages moving from the sides.
 - Pages are no longer evenly distributed from the centre - they follow
   an exponential decay curve, so ones further out are closer together
   (a bit like an open book).
 - Render pages and books in item frames/in-hand (rather than just
   single pages).

This currently does some very dirty things with z values in order to
prevent z-fighting. It would be nice to avoid that, though turning off
writing to the z buffer causes issues with the bounding box.
2018-07-07 19:59:20 +01:00
SquidDev
4d984dc5ee Rewrite turtle block destroying
- Try to make drop capturing a little more generic. This now allows for
   capturing a block's drop at a given position, as well as any drop
   within a bounding box (for things which don't play nicely).

 - Use as much of Minecraft's block breaking logic as possible,
   hopefully simplifying things and making it more consistent with other
   mods.
2018-07-06 18:49:15 +01:00
SquidDev
984d358930 Provide .getNameLocal on modems
This provides the local modem's name on the remote network. Let's be
honest, I'll probably end up renaming this soon.
2018-06-29 20:29:04 +01:00
SquidDev
a95893b823 Send the terminal state to the pocket computer's player
As we only send the terminal to players using the GUI, the map interface
was never updated. We now will also send the terminal state to whoever
has the computer in their inventory.

This also marks the terminal as dirty when a new player picks the pocket
computer up, hopefully preventing any desync issues which might occur
then.

Fixes #42.
2018-06-24 19:18:30 +01:00
SquidDev
81aaead032 Improve using /computercraft as a non-player
- Fix text table only showing the first row (fixes #40)
 - Do not emit alignment characters in monospace environments
 - Reduce padding in monospace environments

Also make the output of dump consistent with that of the profiler: we
provide tp and view shortcuts for each computer.
2018-06-22 08:28:36 +01:00
SquidDev
a2083bcff1 Merge pull request #554 from SquidDev-CC/ComputerCraft/hotfix/gui-blemishes
Fix a couple of minor blemishes in the GUI textures
2018-06-19 22:24:32 +01:00
SquidDev
052f2a16dc Fix a couple of minor blemishes in the GUI textures
- Slight airbrush effect for normal turtles. While this is only really
   visible when upping the contrast, it's probably nice to fix.
 - A few off-colour pixels for advanced turtles
2018-06-19 22:18:48 +01:00
SquidDev
fd10ed6f62 Merge pull request #553 from SquidDev-CC/ComputerCraft/feature/fancy-printout
Fancy rendering of printouts
2018-06-19 19:44:51 +01:00
SquidDev
c0bdd4ff1d Add basic support for fancy rendering of printouts
- When held in first-person, single pages are displayed like a map.
 - When placed in an item frame, the page is drawn instead of the actual
   item.
2018-06-18 22:09:24 +01:00
SquidDev
5f0addbc3e Fix variable being declared too late 2018-06-18 19:01:36 +01:00
SquidDev
c9589ad0e7 Allow using any kind of skull for crafting heads
It's possible to acquire any mob head in vanilla, so it's probably best
if we allow any head to be used.
2018-06-02 11:12:29 +01:00
SquidDev
b21c495815 Update the README to be a bit more detailed
- Include a list of features, pretty similar to that on the forum
   thread or CurseForge page.
 - Replace CC: Tweaked with CC:T. After all, who wants to type all of
   that?
2018-05-15 12:27:04 +01:00
SquidDev
18429c50f9 Bump version 2018-05-15 11:59:21 +01:00
SquidDev
7ec8ddcf7d Delete previous chat messages of the same type
This uses a custom ComputerCraft packet to send chat messages to the
client. When received, we delete all messages of the same category
before sending the new ones.

This avoids cluttering the chat with near-identical messages, and helps
make working with the "individual dump" command easier, as the previous
computer's dump output is deleted.

Also change the max height of the TextTable to 18, so it fits within
Minecraft's default chat limit.
2018-05-15 11:44:23 +01:00
SquidDev
5bf9f9e3c5 Allow multiple HTTP request methods
This implements an argument format similar to LuaReqeust, as described
in dan200/ComputerCraft#515. The Lua argument checking code is a little
verbose and repetitive, but I'm not sure how to avoid that - we should
look into improving it in the future.

Closes #21
2018-05-15 10:11:08 +01:00
hugeblank
e4164ee9a1 amend additional typo in keys.lua
- fixed circumflex typo: you can now cîrcûmflêx on all your friends
- added comment making it clearer that the following lines are intended for backwards compatibility.
2018-05-14 15:54:06 +01:00
SquidDev
b522af3075 Add some basic tracking for HTTP requests and websockets
This should allow for easier identification of misbehaving computers,
which are consuming a large amount of bandwidth.
2018-05-14 15:52:16 +01:00
SquidDev
8775052dee Merge pull request #543 from hugeblank/ComputerCraft/patch-1
amend typo in keys.lua
2018-05-08 09:46:14 +01:00
hugeblank
c0c5d57e10 amend typo in keys.lua
The most important commit that CC has ever seen.
2018-05-08 01:10:45 -07:00
SquidDev
4c2e97b1af Enable compression extension for websockets 2018-05-05 08:34:35 +01:00
SquidDev
f17df15117 Always create extended disks
Whilst the legacy ones are important for backwards compatibility, they
cannot have an ID of 0, which introduces issues when they are the first
disk created in the world.
2018-04-27 09:51:28 +01:00
SquidDev
bfbb18bdfc Add support for tracking server-thread tasks too
This allows us to track how much work various peripherals are doing.
This will not work with all systems, such as Plethora, as that has its
own execution system.
2018-04-24 12:26:26 +01:00
SquidDev
cac65ef755 Print a useful debug log if we cannot safely terminate a task 2018-04-24 11:07:33 +01:00
SquidDev
a42793024b Merge pull request #541 from SquidDev-CC/ComputerCraft/feature/unlimited-reads
Remove upper bound on how many bytes/characters can be read
2018-04-23 16:42:28 +01:00
SquidDev
7dbc4e6455 Remove upper bound on how many bytes/characters can be read
The limit was added to prevent people creating arbitrarily large buffers
(for instance, handle.read(2^31) would create a 2GB char array). For
"large" counts, we now read in blocks of size 8192, adding to an
extendable buffer.
2018-04-23 16:41:00 +01:00
SquidDev
a0d71cb3ad A couple of fixes for maven and CCEmuX
- Add additional maven metadata and strip dependencies
 - Shift ICommand registration into the proxy, to avoid class loading
   issues. This is probably rather temperamental, but classloading
   always is.
2018-04-20 19:39:53 +01:00
SquidDev
83546d0acb Add support for Maven uploading 2018-04-19 22:36:00 +01:00
SquidDev
e2f9ddd534 Add support for arbitrary trackers
This is used by cc-prometheus to monitor statistics. It isn't currently
exposed as an API, as I'm making no guarantees on the stability of this.
2018-04-19 21:59:35 +01:00
SquidDev
911e404bfa Add support for tracking fs, turtle and peripheral operations
See #25
2018-04-17 09:22:26 +01:00
SquidDev
bfeafe163f Various improvements to the tracking system
- Trackers are created per-user, meaning multiple people can run
   /computercraft track at once.
 - Allow sorting the tracking information by arbitrary fields.
 - Add support for tracking arbitrary fields (though none are currently
   implemented).
2018-04-16 21:06:16 +01:00
SquidDev
6cf32f1f74 Various improvements to peripheral invalidation
- Abstract peripheral ID and type checking into separate class
 - Update peripherals directly rather than marking as invalid then
   fetching from the network.
 - Update peripherals when adjacent tiles change

This does result in a slightly more ugly interface, but reduces the
amount of work needed to perform partial updates of peripherals, such as
those done by neighbouring tile updates.
2018-04-16 18:22:28 +01:00
SquidDev
04f162ef25 Rename node → m_node
It's a bit of an ugly naming convention, but it's consistent.
2018-04-16 17:10:08 +01:00
SquidDev
b2aa390ae1 Split up modem and connection invalidation 2018-04-16 17:02:20 +01:00
SquidDev
6ca61f000f Minor performance improvements to WiredNetworkChange
This should improve the performance of the common case, where one
peripheral set is empty.
2018-04-16 15:31:37 +01:00
SquidDev
20a47a7f88 Merge pull request #540 from SquidDev-CC/ComputerCraft/hotfix/fakeplayer-stubs
Add additional method stubs to the TurtlePlayer
2018-04-16 09:39:15 +01:00
SquidDev
e2e6946c92 Add additional method stubs to the TurtlePlayer
Forge's default fake player implementation doesn't override all methods
which use the connection. As it is not set, we get an NPE and thus crash
the server. We simply stub those methods out ourselves to prevent such
an issue.
2018-04-16 09:34:44 +01:00
SquidDev
abe917cd54 Fix peripherals showing up when they shouldn't on world load
When initially attaching a modem, the adjacent computer would not show
up on its own peripheral list (like in vanilla CC). However, it would
show up when the chunk was reloaded as peripherals were added through a
different method.

This prevents such behaviour, always hiding the remote peripheral from
the object which provides it.

Closes #20
2018-04-07 10:23:11 +01:00
SquidDev
a1d77ab8e7 Merge pull request #536 from Luca0208/ComputerCraft/master
Make wget automatically determine the file name.
2018-04-06 21:08:54 +01:00
SquidDev
c8db671409 Override monitors' lightmap coordinates
Shaders appear to ignore all the other subtle (and not-so-subtle) hints
we drop that monitors shouldn't be rendered with shadows. This solution
isn't optimal, as monitors may still be tinted due to sunlight, but
there is nothing we can do about that.

Many thanks to ferreusveritas for their help in diagnosing, fixing and
testing this issue.
2018-03-30 12:57:27 +01:00
SquidDev
52641b7bea Allow rendering a monitor tile multiple times in a tick
Shader mods may perform multiple passes when rendering a tile, so
monitors will be drawn transparently on later passes. In order to
prevent this we allow drawing the a single tile multiple times in a
tick.
2018-03-29 12:31:20 +01:00
SquidDev
3e751ee94a Use Unicode escape code instead of literal
It doesn't compile under Gradle on my system. Goodness knows why not.
2018-03-29 11:47:45 +01:00
SquidDev
2b28cc3558 Merge remote-tracking branch 'SquidDev-CC-ComputerCraft/hotfix/disk-drive-stop' 2018-03-29 11:41:00 +01:00
SquidDev
f9761388b1 Fix .isDiskPresent() always reporting true
We were still determining if the stack was null, but post-1.11 this will
never be the case.
2018-03-29 11:36:59 +01:00
SquidDev
d28694eb57 Rewrite the command system's text padder
This uses narrow near-invisible unicode characters instead of attempting
to toggle between bold and non-bold spaces.
2018-03-25 21:31:31 +01:00
SquidDev
d758895578 Bump to Forge 1.12.2
Nobody is still using 1.12, so we might as well update to the latest -
it makes it easier to test mod compatibility at least.
2018-03-24 12:20:51 +00:00
SquidDev
043d5f00ca Convert wired elements to capabilities
See #18
2018-03-24 11:57:36 +00:00
SquidDev
36878e75b7 Merge remote-tracking branch 'origin/master' 2018-03-15 17:53:21 +00:00
SquidDev
ebb50cba48 Bump version 2018-03-15 17:43:23 +00:00
SquidDev
7c218361d9 Merge pull request #528 from SquidDev-CC/ComputerCraft/feature/computer-upgrade
Add recipes to upgrade computers
2018-03-15 17:39:17 +00:00
SquidDev
bb2eab0bed Use the ore dictionary for upgrade recipes
See #517 for motivation
2018-03-15 17:34:58 +00:00
SquidDev
e8c0cf3857 Convert TurtleRecipe to use ComputerConvertRecipe
The two recipes are pretty similar, so this allows us to substantially
simplify the code. This now introduces the additional requirement that
computers must be used to create turtles, rather than pocket computers
or another turtle.
2018-03-13 14:21:39 +00:00
SquidDev
db825a7aab Add recipes to convert computer items into their upgraded counterparts
This adds IComputerItem.withFamily(ItemStack, ComputerFamily) as well as
a ComputerFamilyRecipe class. Each type of computer (normal, turtle,
pocket) defines a recipe using this class, as they require a different
number of gold ingots to upgrade.
2018-03-13 14:14:36 +00:00
SquidDev
dbcae810f0 Fix monitor.getTextScale() being doubled
Closes #16. The original method divided by 2 in the getter, but that
was removed in our monitor rewrite.
2018-03-10 22:16:15 +00:00
Daniel Ratcliffe
914df8b0c7 Merge pull request #521 from SquidDev-CC/hotfix/modem-full-block
Fix wireless modems suffocating entities
2018-03-05 14:07:57 +00:00
SquidDev
f753513289 Wrap ComputerCraft fake player with brackets
Hopefully this'll make GriefPrevention play a little nicer
2018-03-01 15:58:09 +00:00
SquidDev
7bb8efed1d Dispose of monitor display lists when unloading worlds
This means all display lists are correctly deleted when changing
dimensions/exiting to main menu.
2018-02-24 20:37:14 +00:00
SquidDev
0cec4aee8c Merge pull request #15 from Lignum/maybe-fix-monitors
Maybe fix monitors
2018-02-24 16:59:21 +00:00
Lignum
e0c9dc24e7 Generate individual display lists instead of relying on their names being contiguous 2018-02-24 17:21:12 +01:00
SquidDev
244907a39a Various cherry picks from world thread safety
- Ensure monitor draw lists are not reused after deleting them.
 - Make terminal methods synchronized, avoding NPEs and IOOBEs when
   resizing.
2018-02-22 21:20:08 +00:00
SquidDev
9be61abd6b Merge pull request #5 from SquidDev-CC/feature/network-api
Well, how badly can this go?
2018-02-21 15:47:15 +00:00
SquidDev
922f424a78 Add full block wired modems
These act similarly to conventional wired modems, but with the advantage
that they are a full block. This means they can be attached to
peripherals which are not solid (such as chests). Further more, as they
do not have a direction, they allow wrapping peripherals on all 6 sides.

It's worth noting that wired modems do not require a cable - they will
automatically form connections to adjacent network elements when placed.
2018-02-21 15:40:08 +00:00
SquidDev
5c7828dd79 Convert TileCable to use the wired network API
There are several important things to note here:

 - The network element is associated with the cable, whilst the
   peripheral (and so packet sender/receiver) is associated with the
   modem. This allows us to have the main element be in the centre of
   the cable block, whilst the modem is in the centre of the adjacent
   computer.

 - Cables will connect to any adjacent network element, not just
   other cables.

 - Rednet messages are now sent on the computer thread, rather than the
   cable tick.
2018-02-21 15:35:38 +00:00
SquidDev
74f5093d2a Add the default implementation of wired networks 2018-02-21 15:29:34 +00:00
SquidDev
4651e362c9 Add an API for wired networks
The API is composed of three primary classes:

- IWiredElement: Represents some physical entity in the network. This
   will generally be a block (such as a cable or modem), but it is not
   required to be.

   Each element can provide a series of peripherals, which will be
   exposed to other elements on the network.

- IWiredNode: Every wired element has a unique wired node. This acts
   as a thread-safe proxy for communicating with the rest of the
   network (such as sending packets). Each node is also its own packet
   network.

- IWiredNetwork: This is responsible for keeping track of nodes and
   peripherals in the network. It provides methods for forming and
   breaking connections, correctly joining and splitting networks where
   needed.

Tiles which wish to be part of a wired network should implement
IWiredElementTile or register a custom IWiredProvider. When loaded into
the world, it should connect to adjacent nodes. Similarly, when removed
(either due to being broken or chunk unloads), it should break those
connections.

There is no method to query the layout of the network, as that offers
greater flexibility in changing or extending the implementation later
on.
2018-02-21 15:26:13 +00:00
SquidDev
a2e2a5cb37 Add the concept of "available peripherals" to IComputerAccess
This provides a mechanism for peripherals to see what else a computer is
connected to - and then interact with those peripherals.

We also add the ability to query what block or tile a peripheral
targets. This allows one to interact with the original block of adjacent
peripherals instead.
2018-02-21 15:25:20 +00:00
SquidDev
15a3882016 Fix monitor clear state being cleared without a redraw 2018-02-21 14:32:53 +00:00
SquidDev
d3ecd5214b Merge remote-tracking branch 'SquidDev-CC-ComputerCraft/feature/turtle-event' 2018-02-16 10:48:43 +00:00
SquidDev
0a8a8a742e Add config options to disable various turtle actions
Mostly intended for those people who don't like .inspect() or
.getItemDetail(), but could allow modpacks to block equipping upgrades,
placing blocks, etc...
2018-02-16 10:37:47 +00:00
SquidDev
ecff23d027 Add turtle events
The main aim of this is to allow for greater extensibility for other
mods. For instance, you can now prevent turtles placing dirt blocks, or
turning when on gravel.
2018-02-16 10:33:32 +00:00
SquidDev
20dcb32bae Add command to reload config from disk
Also bump version number, as we're relatively close to a release and
it's frustrating having to bump it when putting out previews.
2018-02-16 09:33:40 +00:00
SquidDev
678462d2db Minor fixes to the monitor rewrite 2018-02-15 20:49:34 +00:00
SquidDev
61fdfec09b Further overrides for wireless modem blockiness 2018-02-15 18:17:38 +00:00
SquidDev
5eadf5533d Fix wireless modems suffocating entities
As of #458, BlockPeripheral will act as a full/opaque block for some
peripherals and a transparent one for others. However, some Block
methods use the default state rather than the current one. This means
modems report being a full block when they are not, leading to
suffocating entities and lighting glitches.
2018-02-15 18:17:02 +00:00
SquidDev
2d3cd5dc80 Merge pull request #521 from SquidDev-CC/ComputerCraft/hotfix/modem-full-block
Fix wireless modems suffocating entities
2018-02-15 18:00:58 +00:00
SquidDev
5208ad0b98 Fix wireless modems suffocating entities
As of #458, BlockPeripheral will act as a full/opaque block for some
peripherals and a transparent one for others. However, some Block
methods use the default state rather than the current one. This means
modems report being a full block when they are not, leading to
suffocating entities and lighting glitches.
2018-02-15 17:56:08 +00:00
SquidDev
662fb96beb Overhaul monitor's terminal code
This restructures monitor in order to make it thread-safe: namely
removing any world interaction from the computer thread.

Instead of each monitor having their own terminal, resize flag, etc...
we use a monitor "multiblock" object. This is constructed on the origin
monitor and propagated to other monitors when required.

We attempt to construct the multiblock object (and so the corresponding
terminal) as lazily as posible. Consequently, we only create the
terminal when fetching the peripheral (not when attaching, as that is
done on the computer thread).

If a monitor is resized (say due to placing/breaking a monitor) then we
will invalidate all references to the multiblock object, construct a new
one if required, and propagate it to all component monitors.

This commit also fixes several instances of glLists not being deleted
after use. It is not a comprehensive fix, but that is outside the scope
of this commit.
2018-02-14 21:30:07 +00:00
SquidDev
4c14431a3d Various improvements to command system
- Ensure usage is consistent
 - Allow computer selectors to return multiple values
 - Fix commands being marked as usable when it isn't
 - Add /computercraft turn-on, a counter to /computercraft shutdown
2018-02-13 11:45:13 +00:00
SquidDev
5ae38a3f18 Merge pull request #520 from SquidDev-CC/ComputerCraft/hotfix/turtle-world-border
Prevent turtles moving beyond the world border
2018-02-13 11:21:55 +00:00
SquidDev
94e10d1f67 Prevent turtles moving beyond the world border
As tiles outside the world border are not ticked, turtles are rendered
entirely useless. Furthermore, the turtle animation will never progress
resulting in visual glitches.

In order to avoid this, we ensure the target position is within the
world border when moving to it.
2018-02-12 17:50:46 +00:00
SquidDev
0a50676884 Fix turtle owner not being persisted 2018-02-10 16:10:16 +00:00
SquidDev
41cce78fcb Merge pull request #518 from SquidDev-CC/ComputerCraft/feature/owner-tracking
Track which player "owns" a turtle
2018-02-05 11:07:06 +00:00
SquidDev
4c0fa1fabe Track which player "owns" a turtle
When a player places a turtle, they are marked as its owner. Any actions
they perform (such as breaking blocks, moving, etc...) are performed
using this player's game profile.

This allows turtles to work correctly with various permissions mods.
Previously you would have to whitelist all turtles in order for them to
function within a claim.
2018-02-04 21:35:21 +00:00
SquidDev
54e1dafa3f Merge pull request #517 from SquidDev-CC/ComputerCraft/feature/ore-dict
Add ore dictionary support to all recipes
2018-02-04 20:06:34 +00:00
SquidDev
3ac76bc05b Add ore dictionary support to all recipes 2018-02-04 20:02:12 +00:00
SquidDev
83030df3ee Add computer performance monitor 2018-02-02 13:34:27 +00:00
SquidDev
07d15caf6f Bump Cobalt version 2018-02-02 12:26:21 +00:00
SquidDev
3298efe652 Prevent computer dump command sending too much information 2018-01-20 11:07:09 +00:00
SquidDev
01d9919a3e Merge pull request #508 from SquidDev-CC/ComputerCraft/hotfix/turtle-speaker-model
Fix turtle speaker upgrade's missing texture
2018-01-19 13:10:20 +00:00
SquidDev
80b1170b63 Extract required textures from models instead
This ensures we will not get missing texture errors in the future, and
allows resource pack artists to use additional textures.
2018-01-19 13:04:50 +00:00
SquidDev
2e7302e654 Fix turtle speaker upgrade's missing texture
The sprite was not registered into the atlas, meaning it rendered the
missing texture instead.
2018-01-19 12:42:32 +00:00
SquidDev
ca7fb8a0b4 Cache turtle family within the tile
This means one can call .getFamily() in a thread-safe manner, ensuring
turtle.getFuelLimit() does not cause issues. As we use a specialist
TE class for each family this does not require any specialist caching.
2018-01-18 13:06:34 +00:00
SquidDev
c9b0894f26 Cache direction of modems within the tile
This ensures the world is not accessed from another thread.

Closes #410
2018-01-18 13:06:11 +00:00
SquidDev
c3454a195d Merge branch 'master' of https://github.com/dan200/ComputerCraft 2018-01-15 17:18:48 +00:00
Daniel Ratcliffe
3b3dd8071b Merge pull request #506 from Wojbie/Advanced-Monitor-Count-Fix
Fix advanced monitor recipe.
2018-01-15 12:59:35 +00:00
Wojbie
0d28c67534 Fix advanced monitor recipe.
Fix recipe to create 4 monitors.
2018-01-14 23:03:14 +01:00
SquidDev
d0af85754a Merge branch 'master' of https://github.com/dan200/ComputerCraft 2018-01-13 10:49:07 +00:00
Daniel Ratcliffe
3e265c27ff Merge pull request #455 from Wilma456/fileread
Add read() to Filehandle
2018-01-13 00:58:19 +00:00
Daniel Ratcliffe
8d356f50c4 Merge pull request #440 from Wilma456/iomulti
Make io.write() accept multiple args
2018-01-13 00:48:07 +00:00
Daniel Ratcliffe
f30c4f16c0 Merge pull request #411 from Wilma456/copyfixup
Fix Bug in copy.lua, mkdir.lua and rename.lua (updated)
2018-01-13 00:32:55 +00:00
Daniel Ratcliffe
8bb8caa315 Merge pull request #448 from Wilma456/writecheck
Fix check of write()
2018-01-13 00:28:08 +00:00
SquidDev
0f17a3d72e Merge branch 'master' of https://github.com/dan200/ComputerCraft 2018-01-12 14:15:22 +00:00
Daniel Ratcliffe
7647369e2d Merge pull request #446 from Wilma456/moduledir
Add folder /rom/modules
2018-01-12 14:10:50 +00:00
Daniel Ratcliffe
4b4208e724 Merge pull request #476 from SquidDev-CC/hotfix/printer-clear
Fix the printer overwriting the current page
2018-01-12 13:59:51 +00:00
Daniel Ratcliffe
2a16a1df85 Merge pull request #486 from Wilma456/extensionfix
Fix Bug in Paint and Edit
2018-01-12 13:59:15 +00:00
Daniel Ratcliffe
25f7c58400 Merge pull request #494 from SquidDev-CC/hotfix/collision-aabb
Fix getCollisionBoundingBox not using all AABBs
2018-01-12 13:57:50 +00:00
Daniel Ratcliffe
c3db91f11f Merge pull request #485 from Luca0208/patch-1
Removed the "the" that was too much(In /rom/help/cd.txt)
2018-01-12 13:56:48 +00:00
Daniel Ratcliffe
8c66ce03d4 Merge pull request #475 from Wilma456/ioline
Fix io.lines()
2018-01-12 13:56:21 +00:00
Daniel Ratcliffe
2be2a0625e Merge pull request #502 from SquidDev-CC/hotfix/missing-overlay
Fix turtle overlay not being rendered in items
2018-01-12 13:54:59 +00:00
Daniel Ratcliffe
c904d5041b Merge pull request #499 from SquidDev-CC/hotfix/null-network
Fix ComputerCraftAPI.getWirelessNetwork() failing
2018-01-12 13:54:33 +00:00
SquidDev
632762768e Add workaround for incorrect overload of getDrops being overridden
Closes #2
2017-12-30 19:03:32 +00:00
SquidDev
c69ba205f8 Merge pull request #502 from SquidDev-CC/ComputerCraft/hotfix/missing-overlay
Fix turtle overlay not being rendered in items
2017-12-24 21:49:01 +00:00
SquidDev
019f4dbea9 Fix turtle overlay not being rendered in items 2017-12-24 21:44:55 +00:00
SquidDev
259ea41ce3 Merge pull request #499 from SquidDev-CC/ComputerCraft/hotfix/null-network
Fix ComputerCraftAPI.getWirelessNetwork() failing
2017-12-10 15:39:59 +00:00
SquidDev
11290f7204 Fix ComputerCraftAPI.getWirelessNetwork() failing
I've got to admit, it is super embarrassing that a) I didn't notice this
when testing and b) no one else has noticed until now.
2017-12-10 15:37:40 +00:00
SquidDev
abd06133fb More binary compatibility stubs for ILuaAPI 2017-12-07 09:24:44 +00:00
SquidDev
29a3a0c48f Bump version 2017-12-07 09:08:15 +00:00
SquidDev
2728c63512 Add back ILuaAPI
This ensures binary compatibility with all those evil mods (Plethora)
which CC internals.
2017-12-07 09:06:47 +00:00
SquidDev
f3b11bc1c2 Copy over CCTweaks's command system
This adds several commands which may be useful for server owners. It'd
be nice to integrate this into ComputerCraft itself, but the associated
command framework is quite large so we'd have to think about it.
2017-12-06 15:51:51 +00:00
SquidDev
04590befb3 Add support for viewing arbitrary computers in a GUI
Important terminal (such as terminal size) is packed into the the
coordinate fields.
2017-12-06 15:43:25 +00:00
SquidDev
4e9034f910 Make http.websocket call synchronous in bios.lua
I thought I'd done this already, but it's possible it got lost during a
rebase.
2017-12-06 09:28:38 +00:00
SquidDev
ba9cfa3764 Bump version
Also add CurseGradle support
2017-12-01 20:05:26 +00:00
SquidDev
341e3e2f89 Merge pull request #497 from SquidDev-CC/ComputerCraft/feature/pocket-map
Add map-like rendering for pocket computers
2017-12-01 19:41:07 +00:00
SquidDev
3f70ca5192 Merge pull request #492 from SquidDev-CC/ComputerCraft/feature/fun-turtle-rendering
Improve vertex transformation system
2017-12-01 19:39:33 +00:00
SquidDev
f11bfc53ee Use IComputer instead of ServerComputer on the client 2017-12-01 19:32:15 +00:00
SquidDev
61e3967b8e Merge pull request #494 from SquidDev-CC/ComputerCraft/hotfix/collision-aabb
Fix getCollisionBoundingBox not using all AABBs
2017-12-01 19:19:17 +00:00
SquidDev
add86ea100 Merge pull request #491 from SquidDev-CC/ComputerCraft/feature/api-api
Provide an API for registering custom APIs
2017-12-01 19:18:40 +00:00
SquidDev
dd51c89278 Add map-like rendering for pocket computers 2017-12-01 11:28:15 +00:00
SquidDev
788d783745 Fix getCollisionBoundingBox not using all AABBs
Closes #493
2017-11-22 10:52:28 +00:00
SquidDev
35da60543e Improve turtles by 200%
Every other mod has some fun feature, so should we. And yes, this was
worth the 400 lines it took to implement.
2017-11-21 00:34:35 +00:00
SquidDev
ce7923d248 Improve vertex transformation system
This migrates TurtleMultiModel's current vertex transformation system
into something more powerful and "correct". Namely, it has the following
improvements:

 - Handles all position formats (float, byte, etc...)
 - Correctly translates normals of quads
 - Reorders faces if the winding order is reversed
2017-11-21 00:18:03 +00:00
SquidDev
55847460c5 Provide an API for registering custom APIs
ILuaAPI has been moved to dan200.computercraft.api.lua. One creates
a new API by registering an instance of ILuaAPIFactory. This takes an
instance of IComputerSystem and returns such an API.

IComputerSystem is an extension of IComputerAccess, with methods to
access additional information about the the computer, such as its label
and filesystem.
2017-11-19 18:23:38 +00:00
SquidDev
893524b0a8 Mark computers as changed when changing on state
Previously they were not marked as such, meaning computer state was not
broadcast to the client until blinking state changed.
2017-11-19 15:23:12 +00:00
SquidDev
8fb3ae405f Ensure we don't strip any whitespace 2017-11-19 15:04:21 +00:00
SquidDev
aa447ec101 Fix term.getTextScale() not using the main monitor 2017-11-19 14:03:48 +00:00
SquidDev
56b1cb4521 Fixup README a little 2017-11-19 13:48:17 +00:00
SquidDev
90cc24614c Add a subjectively fancy logo 2017-11-15 18:20:22 +00:00
SquidDev
d7301ff15e Merge pull request #412 from Wilma456/ComputerCraft-1/textfix
Add Check to textutils.tabulate/pagedTabulate
2017-11-15 16:58:13 +00:00
SquidDev
1cf10c5c47 Merge pull request #490 from zardyh/ComputerCraft/master
Propagate errors arising from API loading
2017-11-15 16:51:26 +00:00
SquidDev
6691ec8e3a Merge pull request #390 from Wilma456/ComputerCraft-1/errormsg
Show fs error in paint and edit
2017-11-15 16:39:37 +00:00
SquidDev
a9f77221ff Merge pull request #469 from Wilma456/ComputerCraft-1/newrecipe
Add more Recipes to Recipebook
2017-11-15 16:35:27 +00:00
SquidDev
dd3b69a633 Rebranding!
I feel kinda guilty about this, but it's probably a good idea to make it
clear that this isn't "actual, proper, stable" ComputerCraft.
2017-11-15 16:25:10 +00:00
hydraz
d766f8b34e Propagate errors arising from API loading 2017-11-15 14:22:36 -02:00
SquidDev
2ae6fb47e7 Move CommandComputer into a child package
Means we can be a little more organised where we put the additional
commands.
2017-11-15 15:57:10 +00:00
SquidDev
dd5698241b Add support for running multiple computers at the same time
- ComputerThread constructs multiple threads instead of just one,
   depending on a config options.
 - The synchronized blocks of PeripheralAPI.PeripheralWrapper have been
   shifted a little to ensure no deadlocks occur.
2017-11-15 13:30:40 +00:00
SquidDev
ed8e9d7817 Add support for enabling Lua's debug library
Whilst I'm pretty sure this is safe for general use, I'm disabling this
by default for now. I may consider enabling it in the future if no
issues are found.
2017-11-15 12:18:10 +00:00
SquidDev
6c29b44c3c Merge pull request #440 from Wilma456/ComputerCraft-1/iomulti
Make io.write() accept multiple args
2017-11-15 11:47:33 +00:00
SquidDev
0caa133089 Merge pull request #454 from SquidDev-CC/ComputerCraft/hotfix/lazy-computer-peripheral
[WIP] Only instantiate ServerComputer on tile ticks
2017-11-15 11:42:54 +00:00
SquidDev
a8b08bd971 Remove apis.HTTPRequest
I evidently duplicated this during some rebase, more fool me.
2017-11-15 11:39:48 +00:00
SquidDev
c9181a121f Merge pull request #395 from SquidDev-CC/ComputerCraft/feature/websocket
Websocket support
2017-11-15 11:39:02 +00:00
SquidDev
30f4e0829f Add websocket support to HTTP API
This uses Netty's websocket functionality, meaning we do not have to
depend on another library.

As websockets do not fit neatly into the standard polling socket model,
the API is significantly more event based than CCTweaks's. One uses
http.websocket to connect, which will wait until a connection is
established and then returns the connection object (an async variant is
available).

Once you have a websocket object, you can use .send(msg) to transmit a
message. Incoming messages will fire a "websocket_message" event, with
the URL and content as arguments. A convenience method (.receive())
exists to aid waiting for valid messages.
2017-11-15 11:32:17 +00:00
SquidDev
2155fce036 Merge pull request #486 from Wilma456/ComputerCraft-1/extensionfix
Fix Bug in Paint and Edit
2017-11-14 23:55:14 +00:00
SquidDev
27602ec8fc Merge pull request #485 from Luca0208/ComputerCraft/patch-1
Removed the "the" that was too much(In /rom/help/cd.txt)
2017-11-14 23:54:54 +00:00
SquidDev
66f683d9c9 Merge pull request #475 from Wilma456/ComputerCraft-1/ioline
Fix io.lines()
2017-11-14 23:53:50 +00:00
SquidDev
ac08a52323 Merge pull request #480 from Wilma456/ComputerCraft-1/monitorscale
Add getTextScale() to Monitor
2017-11-14 23:53:04 +00:00
SquidDev
fe0f998c27 Merge pull request #448 from Wilma456/ComputerCraft-1/writecheck
Fix check of write()
2017-11-14 23:50:12 +00:00
Wilma456
bcf79165f9 Merge pull request #455 from Wilma456/ComputerCraft-1/fileread
Add read() to Filehandle
2017-11-14 23:48:38 +00:00
Steven Dirth
9b2a50cdfc Merge pull request #362 from KingofGamesYami/ComputerCraft/featurecommand-event
Command Event
2017-11-14 23:27:11 +00:00
Wilma456
c5d99db654 Merge pull request #411 from Wilma456/ComputerCraft-1/copyfixup
Fix Bug in copy.lua, mkdir.lua and rename.lua (updated)
2017-11-14 23:24:11 +00:00
SquidDev
5253ab3e58 Merge pull request #463 from josephcsible/ComputerCraft/notnull
Remove some unnecessary null checks
2017-11-14 22:58:36 +00:00
SquidDev
11d8253d9c Merge pull request #464 from josephcsible/ComputerCraft/unnecessary
Remove unnecessary code
2017-11-14 22:57:36 +00:00
SquidDev
bc2b481918 Merge pull request #289 from Wojbie/ComputerCraft/Speaker-pocket-computer-light
Add pocket computer light support to Speaker.
2017-11-14 22:46:01 +00:00
SquidDev
b26564ccb9 Update README to explain what this project is
Also add a .editorconfig file to ensure some level of consistent
formatting.
2017-11-14 22:42:07 +00:00
SquidDev
28e3ffe978 Update Gradle and build system
- Bundle Javadoc and APIs using gradle instead of deploy.sh
 - Bump Gradle to 4.3, significantly improving compile times.
2017-11-14 22:42:03 +00:00
SquidDev
540e2e25aa Merge pull request #163 from SquidDev-CC/ComputerCraft/feature/cobalt
Replace LuaJ with Cobalt
2017-11-14 21:48:47 +00:00
SquidDev
845118e9e2 Merge pull request #218 from SquidDev-CC/ComputerCraft/feature/new-computer-thread
Rewrite the computer thread system
2017-11-14 21:33:20 +00:00
SquidDev
b2b8753ee7 Merge pull request #227 from SquidDev-CC/ComputerCraft/feature/improved-cable
Improving cable/wired modem interactions
2017-11-14 21:32:53 +00:00
SquidDev
060fb21bdb Merge pull request #298 from SquidDev-CC/ComputerCraft/feature/luaj-bit32
Replace BitAPI with a LuaJ implementation of bit32
2017-11-14 21:32:19 +00:00
SquidDev
ef008709c7 Merge pull request #402 from SquidDev-CC/ComputerCraft/feature/shell-resolution
Tweak shell program resolution slightly
2017-11-14 21:31:10 +00:00
SquidDev
09da119f27 Merge pull request #451 from SquidDev-CC/ComputerCraft/hotfix/disk-drive-stop
Use custom packet to play records, instead of using block events
2017-11-14 21:30:52 +00:00
SquidDev
f8487d1e1c Merge pull request #453 from SquidDev-CC/ComputerCraft/hotfix/eager-remove-te
Remove tile before calling destroy
2017-11-14 21:15:47 +00:00
SquidDev
b6f773ffce Merge pull request #457 from SquidDev-CC/ComputerCraft/hotfix/computer-reload
Turn on ServerComputer instances if they have timed out
2017-11-14 21:14:49 +00:00
SquidDev
c8673473ef Merge pull request #476 from SquidDev-CC/ComputerCraft/hotfix/printer-clear
Fix the printer overwriting the current page
2017-11-14 21:14:10 +00:00
SquidDev
3829815756 Merge pull request #479 from SquidDev-CC/ComputerCraft/feature/network-optimisations
Only send terminal state to interacting players
2017-11-14 21:13:17 +00:00
SquidDev
7eac8faf0d Merge pull request #482 from SquidDev-CC/ComputerCraft/feature/jei-integration
Add simple JEI integration
2017-11-14 21:06:02 +00:00
SquidDev
0bd0f4d313 Prefix all loaded strings with "="
Whilst this is not consistent with normal Lua, this is required in order
to remain compatible with LuaJ.
2017-11-14 18:41:01 +00:00
SquidDev
73873eb8cb Change timeout system to occur on instructions instead of API calls
This means loops which do not touch CC specific methods will still
produce an error, rather than terminating the computer.
2017-11-14 18:41:00 +00:00
SquidDev
0420b6c831 Remove string metatable protection
The string metatable and environment are no longer shared, so this
sandboxing is no longer required.
2017-11-14 18:41:00 +00:00
SquidDev
bb741975b7 Migrate LuaJLuaMachine to use Cobalt 2017-11-14 18:41:00 +00:00
SquidDev
8bffec6964 Add dependency on Cobalt 2017-11-14 18:40:57 +00:00
Wilma456
9e19dd7070 Fix Bug in Paint and Edit 2017-11-02 20:14:34 +01:00
Luca S
aba0e3d2d4 Removed the "the" that was too much 2017-10-29 19:06:34 +01:00
SquidDev
d9d025e33b Add simple JEI integration
- Ensure pocket computers and turtles are distinguished by upgrades and
   computer family.
 - Ensure disks are distinguished by colour.
 - Hide treasure disks from the list
2017-10-25 13:40:35 +01:00
Wilma456 (Jakob0815)
1fe29ab098 Add getTextScale() to Monitor 2017-10-13 12:37:55 +02:00
SquidDev
53f16782ab Only send terminal state to interacting players
This splits the computer state (blinking, label, etc...) and terminal
state into two separate packets. When a computer changes, the computer
state is sent to all players and the terminal state is sent to players
who are curerntly using the computer.

This reduces network usage by a substantial amount.
2017-10-12 10:45:38 +01:00
SquidDev
bfb4f88304 Fix the printer clearing the previous page
When printing on top of an already printed page, the previous contents
should be preserved. However, this did not occur as the stack had been
shrunk and so the item was no longer considered a printout.

Closes SquidDev-CC/ComputerCraft#2
2017-10-06 12:04:49 +01:00
SquidDev
fb6d65ec23 Invalidate the network when the peripheral is removed
Fixes #83
2017-10-04 21:49:41 +01:00
SquidDev
6b364052c7 Only render breaking animation on the part being hit 2017-10-04 21:49:40 +01:00
SquidDev
7169abcd7b Ensure the modem's peripheral is incorrectly invalidated when changed 2017-10-04 21:49:40 +01:00
SquidDev
75ccfbdb3d Migrate cable core block state to an enum
This allows us to render the cable "core", as was done pre-1.8.
2017-10-04 21:49:40 +01:00
SquidDev
728644c104 Initial attempt at improving cable/wired modem interactions
- Cable and modem can be broken individually
 - Ray tracing will go through "holes" in the cable.
 - Pick block will determine which part you are looking at.
 - Selection box will only highlight the region you are looking at:
   modem or cable.
2017-10-04 21:49:37 +01:00
Wilma456 (Jakob0815)
999351e667 Fix io.lines() 2017-10-04 18:51:48 +02:00
Wilma456
11e879db41 Removce Bow Upgrade Recipe 2017-09-29 18:56:52 +02:00
Wilma456
a4a774fcdf Add more Recipes to Recipebook 2017-09-27 20:08:48 +02:00
Wilma456
4fb0240a36 Changes suggested by SquidDev and update help file 2017-09-24 17:36:20 +02:00
Joseph C. Sible
80ec54eaf6 Remove unnecessary code
- Remove unnecessary casts
- Use the diamond operator where possible
- Remove "throws" declarations that aren't actually thrown
- Remove unused local variables
- Remove unused imports
- Remove redundant superinterfaces
2017-09-24 01:23:29 -04:00
Joseph C. Sible
9e4ae3a494 Remove some unnecessary null checks
We know turtle can't be null in any of these places, since in preceding code,
we called methods on it, so we would have gotten a NullPointerException then
and never gotten here if it were null.
2017-09-24 01:00:55 -04:00
Daniel Ratcliffe
19e4c03d3a Merge pull request #456 from Wilma456/ioerror
Set errorlevel for "Unsupported format" to 2
2017-09-22 13:20:34 +01:00
Daniel Ratcliffe
c6b8cb1fab Merge pull request #458 from SquidDev-CC/hotfix/block-shapes
Fix BlockFaceShape not being overridden for turtles and peripherals
2017-09-22 13:20:08 +01:00
Wilma456 (Jakob0815)
f20a7afa7f Better Code 2017-09-18 15:22:44 +02:00
SquidDev
01f5d006fc Fix BlockFaceShape not being overridden for turtles and peripherals
This meant one could perform various illogical actions to
non-full-blocks, such as connecting fences and placing paitings.

We also modify the behaviour of isOpaqueCube and isFullCube for
peripherals, only returning false for the case of modems and cables.
2017-09-18 08:33:40 +01:00
SquidDev
cd6b076efe Turn on ServerComputer instances if they have timed out 2017-09-16 20:09:51 +01:00
Wilma456 (Jakob0815)
f8193a4d23 Set errorlevel for "Unsupported format" to 2 2017-09-16 16:11:36 +02:00
Wilma456
5be2202b2e Add read() to Filehandle 2017-09-16 16:06:27 +02:00
SquidDev
fbbfe33e21 Do not instantiate ServerComputer instances in the peripheral provider
Instead we create a ComputerProxy, which delegates methods to the
ServerComputer or TileComputerBase, depending on which one exists.
2017-09-15 18:58:13 +01:00
SquidDev
7a916ed8c2 Do not instantiate a ServerComputer for pocket computers's mount 2017-09-15 18:48:57 +01:00
SquidDev
60305cd106 Remove tile before calling destroy
This ensures that the tile will updating neighbouring blocks, and so
the destroyed tile will not be wrapped as a peripheral.
2017-09-15 17:40:53 +01:00
Wilma456 (Jakob0815)
b8630f739a Add Check requested by dan200 2017-09-13 19:21:17 +02:00
Daniel Ratcliffe
1c8480a329 Merge pull request #441 from SquidDev-CC/hotfix/paintutils-read
Fix a non-existent method being used in paintutils
2017-09-13 17:10:07 +01:00
Daniel Ratcliffe
5219648128 Merge pull request #445 from SquidDev-CC/hotfix/container-backgrounds
Fix background and tooltips not rendering within containers
2017-09-13 00:43:10 +01:00
SquidDev
1ef7c8e8db Only send the packet to people within 64 blocks
This is equivalent to what vanilla Minecraft does
2017-09-12 22:44:49 +01:00
Wilma456
1415dd0dae Changes requested by dan200 2017-09-12 20:43:07 +02:00
Wilma456 (Jakob0815)
282aa804f8 Changes sugested by dan200 2017-09-12 19:42:08 +02:00
Daniel Ratcliffe
e959051239 Merge pull request #447 from BombBloke/patch-1
Correct minor typo in rednet.receive
2017-09-12 18:14:34 +01:00
Wilma456 (Jakob0815)
373b7ba293 Fix check of write()
if you call write(nil), you will get the error "bios.lua:229: bad argument: string expected, got nil", so nil is not a valid argument for write() and should be removed.
2017-09-12 17:17:58 +02:00
Bomb Bloke
70c6f3498b Correct minor typo in rednet.receive
Caused attempts to set a time-out value to throw "expected number, got number".
2017-09-13 01:06:59 +10:00
SquidDev
afec3743f3 Use custom packet to play records, instead of using block events
Breaking a disk drive was not stopping the record being played as the
block event never reached the client. Instead, we send a custom packet
which starts/stops music at a given location.

We also remove all the plumbing for eventReceived/sendBlockEvent from
the generic block/tile classes, as they are no longer used.

Closes #443
2017-09-12 15:46:46 +01:00
Wilma456
5989d021c7 Add folder /rom/modules 2017-09-12 16:44:22 +02:00
SquidDev
baa8993999 Fix background and tooltips not rendering within containers
The methods to draw these now have to be explicitly called, hence not
showing up.
2017-09-12 15:05:32 +01:00
Wilma456 (Jakob0815)
92f5860de6 Use select() 2017-09-12 15:27:09 +02:00
SquidDev
12abd4292e Fixes a non-existent method being used in paintutils 2017-09-12 09:52:21 +01:00
Daniel Ratcliffe
fa498e74fb 1.80pr1 2017-09-12 00:11:19 +01:00
Daniel Ratcliffe
bd90d7d3b0 Ignore .DS_Store files 2017-09-12 00:05:26 +01:00
SquidDev
4bd5b0d236 Remove HTTPTask, queueing the event when it has finished executing
This means we don't have to have lots of shared state between the run
and whenFinished method, and allows for easier chaining of futures later
on.
2017-09-11 22:13:00 +01:00
Wilma456 (Jakob0815)
0115bc8dca Make io.write() accept multiple args
This is just to bring the io API from CC close the the io API from normal lua, which accept multiple args for io.write().
2017-09-11 15:47:30 +02:00
Daniel Ratcliffe
1fdfcdb5f2 Merge pull request #378 from MineRobber9000/patch-3
Add ability to load raw data from a string [paintutils]
2017-09-11 13:28:27 +01:00
Daniel Ratcliffe
6c32d8a57e Merge pull request #394 from Wojbie/bugfix/Filesystem-dots-#35
Modify logic behind ... and more in file path.
2017-09-11 13:27:13 +01:00
SquidDev
5f323a85a7 Rethrow/retrigger interrupted status where appropriate 2017-09-10 22:08:08 +01:00
SquidDev
85c556d324 Rewrite the computer thread system
This makes a couple of significant changes to the original system, to
reduce the number of threads created and allow for multiple threads in
the future. There are several notable changes from the original
implementation:

 - A blocking queue is used for the main task queue queue. This removes
   the need for the "monitor" variable and allows for multiple threads
   polling this queue in the future.
 - The thread used to execute tasks is "cached" between tasks,
   significantly reducing the number of threads which need to be
   created. If a task needs to be stopped then the thread is then
   terminated and a new one constructed, though this rarely happens.
2017-09-10 22:08:08 +01:00
Daniel Ratcliffe
61ff91f237 Merge pull request #316 from SquidDev-CC/feature/minecraft-1.12.2
Update to 1.12. Bam!
2017-09-10 20:52:26 +01:00
SquidDev
3b2de38227 Build against Oracle JDK 8 instead 2017-09-10 20:45:24 +01:00
Daniel Ratcliffe
bde9ac9747 Merge pull request #400 from SquidDev-CC/hotfix/redstone-propagation
Fix redstone not being propagated through solid blocks
2017-09-10 18:05:51 +01:00
Wojbie
6aa4a385a3 Requested changes to logic behind ... in file path. 2017-09-10 17:51:29 +02:00
SquidDev
a2da6d9601 Pass the original block in redstone propagation
notifyBlockOfStateChange and notifyNeighborsOfStateExcept expect the
block which caused the redstone update, rather than the neighbor block.

Fixes #393
2017-09-10 09:32:02 +01:00
Daniel Ratcliffe
88b1124204 Merge pull request #399 from SquidDev-CC/hotfix/http-encoding
Fix setting an invalid content-encoding header
2017-09-10 00:28:39 +01:00
Daniel Ratcliffe
51644e32ed Merge pull request #415 from Wilma456/palletecheck
Add valid check to term.setPaletteColor/getPaletteColor
2017-09-10 00:12:46 +01:00
Daniel Ratcliffe
cf5216aefb Merge pull request #401 from SquidDev-CC/hotfix/peripheral-errors
Fix logPeripheralErrors not being set
2017-09-10 00:06:15 +01:00
Daniel Ratcliffe
c7e5386e80 Merge pull request #414 from Wilma456/listfix
Fix Bug in list.lua
2017-09-10 00:04:08 +01:00
Daniel Ratcliffe
707f0899da Merge pull request #429 from Wilma456/iofix
Fix io API
2017-09-09 23:59:57 +01:00
Daniel Ratcliffe
3095a6bbad Merge pull request #241 from SquidDev-CC/feature/minecraft-1.11.2
Update to 1.11.2
2017-09-09 23:54:42 +01:00
Wilma456 (Jakob0815)
a5bbed528d Make mode from io.open() accept nil 2017-09-06 18:53:44 +02:00
Wilma456
0c1114edbc Update to new Style 2017-08-30 17:29:06 +02:00
Wilma456 (Jakob0815)
369be7c32c Fix io API
While adding checks to the io API in #424, I had forgot that the io API has his own type() function who overwrite the default one. This PR fix this. Sorry for that.
2017-08-27 17:08:40 +02:00
Daniel Ratcliffe
fd8837c631 Merge pull request #377 from Wilma456/fserror
Better Errors for fs API
2017-08-27 13:51:36 +01:00
Daniel Ratcliffe
2f829a1413 Fixed load() not accepting function arguments 2017-08-27 13:34:33 +01:00
Daniel Ratcliffe
0de3a42808 Merge pull request #424 from Wilma456/newcheck
Add more Checks
2017-08-27 12:26:58 +01:00
Daniel Ratcliffe
2fb6a9dc62 Merge pull request #389 from Wilma456/ioerr
Make io.open() return Error
2017-08-27 12:22:54 +01:00
Daniel Ratcliffe
87b771b7c8 Merge pull request #421 from Wilma456/sleephelp
Remove sleep.txt
2017-08-27 12:17:53 +01:00
Wilma456
79697e37b0 Add Check to load() 2017-08-24 20:18:21 +02:00
Wilma456
4f9de6b02c Update Checks 2017-08-24 20:17:31 +02:00
Wilma456
e9cea7d0f5 Add more Checks 2017-08-21 15:20:32 +02:00
Wilma456 (Jakob0815)
90626748e4 Remove sleep.txt
sleep was removed from CC, so It's time to remove the help file
2017-08-18 15:45:57 +02:00
Wilma456 (Jakob0815)
30b55d966b Add valid check to term.setPaletteColor/getPaletteColor 2017-08-11 15:38:02 +02:00
Wilma456 (Jakob0815)
3371345fad Fix Bug in list.lua
list.lua check now, if sDir is a Directory
2017-08-11 13:42:20 +02:00
Wilma456 (Jakob0815)
2c264728d9 Add Check to textutils.tabulate/pagedTabulate 2017-08-10 13:40:35 +02:00
Wilma456
90c4ebd208 Fix Bug in copy.lua, mkdir.lua and rename.lua 2017-08-09 19:32:29 +02:00
SquidDev
5df97e5133 Tweak shell program resolution slightly
- Path containing '/' or '\' are resolved relative to the current
   directory, rather than using the path. Paths starting with '/' still
   resolve relative to the root directory.
 - Shell completion will also include sub-directories of the current
   directory.

Closes #219
2017-08-03 07:24:21 +01:00
SquidDev
8f6feff4fd Fix logPeripheralErrors not being set 2017-08-01 21:25:23 +01:00
SquidDev
26bca2e109 Fix setting an invalid content-encoding header 2017-07-31 07:50:23 +01:00
Wojbie
0d5397db34 Modify logic behind ... and more in file path.
Changes all equal or longer then 3 multidots setups to be treated as .
This removes other potentialy dangerus situations and brings it closer to windows in how it treats said dots.
2017-07-30 14:11:25 +02:00
Wojbie
acb5f65e16 Functional change Lignum suggested 2017-07-29 01:14:36 +02:00
Wilma456
c9e7b45509 Show fs error in paint and edit 2017-07-28 15:36:33 +02:00
Wilma456
226ae3648f Forget string 2017-07-28 15:21:15 +02:00
Wilma456 (Jakob0815)
83f34b430d Make io.open() return Error
If fs.open() failed, it will return nil and a a error message like "No such file"  or "Out of space". This PR make, that io.open() returned this error too.
2017-07-28 15:18:14 +02:00
Wilma456
0a5155c0ff New style 2017-07-27 16:40:00 +02:00
Daniel Ratcliffe
579f7443a8 Merge pull request #360 from Wojbie/Mixed-lua-side-improvements.-Part-2
Mixed-Lua-side-improvements.-Part-2
2017-07-25 23:15:10 +01:00
Daniel Ratcliffe
df1c8e22b8 Merge pull request #376 from CrazedProgrammer/fix-argument-checks
Fix argument checks made in PR #304 and #338
2017-07-25 23:13:34 +01:00
CrazedProgrammer
96288164c5 Fix textutils.serializeJSON argument check 2017-07-25 22:36:54 +02:00
SquidDev
263bade338 Add some basic recipe advancements
This doesn't provide the ability to unlock the upgrade impostor recipes,
but I'm not sure that is currently feasible.
2017-07-25 21:10:49 +01:00
SquidDev
d29ffed383 Java 8. Java 8. Does whatever Java 8 can.
Default methods, everywhere.
Arrow types, switch on strings.
Lambdas!
Here comes Java 8.
2017-07-25 21:10:48 +01:00
SquidDev
08099f08f2 Initial update to 1.12
- Convert most recipes to JSON
 - Add JSON factories for impostor and turtle recipes.
 - Several mappings changes
 - Migrate to Forge's new registry system
2017-07-25 21:10:47 +01:00
SquidDev
bee41e7f97 Avoid deprecated warnings on ItemCable 2017-07-25 21:08:52 +01:00
SquidDev
35425f0f61 Update to 1.11.2 2017-07-25 21:08:51 +01:00
Daniel Ratcliffe
f480965e67 Merge pull request #372 from Wilma456/apispro
Update alias.lua
2017-07-25 20:32:30 +01:00
Daniel Ratcliffe
6701403370 Merge pull request #364 from KingofGamesYami/feature/computer-get-label
Add .getLabel
2017-07-25 20:06:22 +01:00
Daniel Ratcliffe
ff2c26c4a1 Merge pull request #367 from SquidDev-CC/feature/texture-spacing
Fix texture artifacts when rendering monitors
2017-07-25 20:05:31 +01:00
Wojbie
4c89364964 Requested changes 2017-07-25 21:01:04 +02:00
Daniel Ratcliffe
94613d28a6 Merge pull request #381 from Wilma456/colerror
Better Error for "Invalid color"
2017-07-25 19:56:59 +01:00
Daniel Ratcliffe
f6ea561270 Merge pull request #374 from Wilma456/packapis
Add package to apis.lua
2017-07-25 19:05:11 +01:00
Daniel Ratcliffe
b4fb7bb20f Merge pull request #354 from Wilma456/multifix
Fix multishell.launch
2017-07-25 19:04:39 +01:00
Daniel Ratcliffe
35d29e1d88 Merge pull request #348 from Wilma456/termcheck
Update term.redirect check to new style
2017-07-25 19:03:55 +01:00
Daniel Ratcliffe
f14a14f4c3 Merge pull request #355 from MineRobber9000/patch-2
Make pastebin.lua use HTTPS
2017-07-25 19:03:15 +01:00
Daniel Ratcliffe
77cadf52fe Merge pull request #351 from Wojbie/Fix-to-349-Monitors-causing-miscolouration-of-tile-entities
Fix to #349 - Monitors causing miscolouration of tile entities.
2017-07-25 19:02:43 +01:00
Daniel Ratcliffe
e97a32cd69 Merge pull request #375 from SquidDev-CC/feature/resourcepack-bios
Adds the ability to load custom bios.lua files from resource packs
2017-07-25 19:02:05 +01:00
Daniel Ratcliffe
44a5284dd6 Merge pull request #379 from SquidDev-CC/hotfix/nil-errors
Fix incorrect null check in HTTP API
2017-07-25 19:00:25 +01:00
Wilma456 (Jakob0815)
43a5fc9fe7 Better Error for "Invalid color"
the "Invalid color" error now contain the wrong color.
2017-07-18 16:12:19 +02:00
SquidDev
505ccf97cf Fix incorrect null check
This was causing NPEs when no headers were specified and one was
attempting to POST data.
2017-07-17 22:46:48 +01:00
MineRobber___T
2c91c7962f Remove unused tImage table and slightly clean code 2017-07-17 01:49:14 -04:00
MineRobber___T
f785b0a488 Update paintutils.lua 2017-07-17 01:16:36 -04:00
MineRobber___T
af847818d2 Remove some context from comment
I agree with SquidDev, I went a bit too far with the whole context thing.
2017-07-16 02:10:42 -04:00
MineRobber___T
ee20d7bed2 Fix line split
Also fixes a typo.
2017-07-16 02:08:54 -04:00
MineRobber___T
11060596b1 Remove legacy bHandleRawData check and fix file loading
While the check (most likely) wouldn't break anything, it's better to fix it and not worry then to not fix it and find out it breaks image loading. Also fixes how files are loaded.
2017-07-15 18:31:42 -04:00
MineRobber___T
71d024a76c Move raw data parsing to paintutils.drawImage 2017-07-15 18:27:52 -04:00
MineRobber___T
260bb2e4e1 Add ability to load raw data from a string 2017-07-15 17:50:05 -04:00
Wilma456
f28a1ba517 Fix Bugs 2017-07-15 16:41:40 +02:00
Wilma456
239a2f0d25 Better Errors for fs API 2017-07-15 16:09:29 +02:00
CrazedProgrammer
1850dcdf38 Fix indentation of previous commits (tabs -> spaces) 2017-07-15 13:01:08 +02:00
CrazedProgrammer
af0549946b Fix window API argument check made in PR #304
- Fix window.reposition so the new width and height arguments are
optional
2017-07-15 00:17:34 +02:00
CrazedProgrammer
7e5a9b3a5a Fix some textutils API argument checks made in PR #338
- textutils.serializeJSON now takes a table/string/number/boolean instead of just a string as the t argument, and checks for nil in the tNBTStyle argument, so the parameter becomes optional again, as described in the wiki.
- textutils.slowWrite and textutils.slowPrint now checks if the rate
parameter is a number, if not nil.
2017-07-15 00:00:01 +02:00
SquidDev
c0294e1534 Adds the ability to load custom bios.lua files from resource packs
Computer now delegates to IComputerEnvironment which, by default, looks
in the following locations:

 - Resouce pack files
 - The "debug" folder
 - The original ComputerCraft jar
2017-07-14 21:58:58 +01:00
Wilma456 (Jakob0815)
bb6d423710 Add package to apis.lua 2017-07-14 12:50:59 +02:00
Wilma456 (Jakob0815)
0ab79fd466 Update alias.lua
The apis program show now, waht programs are behind the aliases
2017-07-13 16:04:55 +02:00
Bomb Bloke
756d297c85 Update worm.lua
Fix #368
2017-07-11 10:24:36 +10:00
SquidDev
1cf3d78eac Fix texture artifacts when rendering monitors
- Adds a 1px margin around every glyph. This is generally empty,
   with the exception of teletext characters where it continues their
   pattern.
 - Uses GL_CLAMP with the font texture.

Closes #300
2017-07-10 22:20:07 +01:00
Steven Dirth
f1bb56557d Update changelog and whatsnew 2017-07-09 12:45:08 -05:00
Steven Dirth
4b36ed6719 Add .getLabel to computer peripheral
Closes #359
2017-07-09 12:43:50 -05:00
KingofGamesYami
592c0c9341 Merge pull request #1 from dan200/master
update 7/8
2017-07-08 16:17:24 -05:00
SquidDev
e664eb26a9 Fix several global definitions
There were a couple of programs which were defining global variables, or
referencing undefined ones. This fixes all problems in the main rom files.
2017-07-08 11:31:30 +00:00
SquidDev
1ab5094b7f Only delete indent when at the beginning of a line
edit currently deletes the previous 4 spaces when pressing backspace,
wherever you are on the line. This can be frustrating when you are
trying to align text in comments or strings.

This changes edit to only delete 4 spaces if all preceding characters
are whitespace, otherwise it only deletes a single character.
2017-07-08 12:07:30 +01:00
Daniel Ratcliffe
94d701b1f7 Merge pull request #350 from Wilma456/argnil
Replaced "no value" with "nil" in ArgumentHelper
2017-07-07 20:58:09 +01:00
Daniel Ratcliffe
db2364dae6 Merge pull request #357 from SquidDev-CC/hotfix/credits-include
Various improvements to credits generation
2017-07-07 20:57:36 +01:00
Wojbie
87406bc00d Tweak to Colon syntax lua autocompletition.
Changes autocompletition to only complete function names (Or table names treated as functions via __call metamethod) after the colon symbol.
2017-07-07 02:30:57 +02:00
Wojbie
224e752a8f Tweak to Go and Turn autocompletition.
Adds spaces to simplyfy making chains of commands.  Also fix up turn not autocompleting after first argument.
2017-07-07 02:18:24 +02:00
SquidDev
48754659f8 Various improvements to credits generation
- Include author and comitter (so includes rebased commits)
 - Ignore case when sorting names

Fixes #356
2017-07-06 17:27:20 +01:00
MineRobber___T
f0559867d0 Fix pastebin.lua not using HTTPS
Attempting to use pastebin with plain HTTP results in a 301 redirect to the HTTPS version. This PR (and associated commit) makes the pastebin command work again.
2017-07-06 03:58:41 -04:00
Wilma456
02eb52da71 Fix multishell.launch 2017-07-05 10:17:44 +02:00
Wojbie
ef05eb7fe9 @SquidDev fix to #349.
This fixes problem reported in #349.
I was one of pepole that were having this bug so i was able to test it and confirm this fix.

Closes #349
2017-07-04 22:54:20 +02:00
Wilma456
6fdf38f55f Replaced "no value" with "nil" in ArgumentHelper 2017-07-04 12:44:20 +02:00
Wilma456
c46391555f Update term.redirect check to new style 2017-07-03 18:08:51 +02:00
Daniel Ratcliffe
1d63598d43 Merge pull request #338 from Wilma456/textcheck
Add Checks to Textutils API
2017-06-29 19:04:37 +01:00
Wilma456
5e244273c2 Allow Number and Table 2017-06-29 17:58:53 +02:00
Daniel Ratcliffe
b0a2dd5eb1 Merge pull request #344 from Wilma456/othercheck
Add Checks to disk,gps,help and keys
2017-06-29 16:09:46 +01:00
Wilma456
13f886be5a Add Checks to disk,gps,help and keys 2017-06-29 16:41:48 +02:00
Wilma456
845e1b633d Merge branch 'master' into textcheck 2017-06-29 16:24:30 +02:00
Wilma456
6a8c544914 Feedback from dan200 2017-06-29 16:18:13 +02:00
SquidDev
6fca136327 Move Bit32 library to LuaJ sources 2017-06-28 23:05:48 +01:00
Daniel Ratcliffe
123a0158af Merge pull request #313 from SquidDev-CC/feature/http-blacklist
HTTP blacklist and IP address support
2017-06-28 22:36:14 +01:00
SquidDev
b37b33f4f4 Migrate default whitelist/blacklist values to fields
This means we're not duplicating them between the initial field and
property creation.
2017-06-28 22:33:20 +01:00
Daniel Ratcliffe
00a1342883 Merge pull request #297 from SquidDev-CC/feature/fire-events
Fire Forge events where appropriate
2017-06-28 22:32:22 +01:00
Daniel Ratcliffe
14e4d037ad Merge pull request #317 from Wojbie/Mixed-lua-side-improvements
Multiple fixes and feature fixes for lua side of CC.
2017-06-28 22:25:18 +01:00
Daniel Ratcliffe
28a89a26ad Merge pull request #342 from SquidDev-CC/hotfix/turtle-suck
Replace direct equality with InventoryUtil.areItemsEqual
2017-06-28 22:12:30 +01:00
SquidDev
c9a3bcb68b Replace direct equality with InventoryUtil.areItemsEqual
Some IItemHandler.insertItem implementations clone the item, so we must
check whether the object is equal instead.

Fixes #340
2017-06-28 22:11:25 +01:00
Daniel Ratcliffe
025af6a0a0 Merge pull request #329 from Wilma456/pocketequip
Add equip and unequip for Pocket Computers
2017-06-28 22:06:35 +01:00
Wojbie
f247879d98 Re-add Colon syntax support to edit. 2017-06-28 23:06:06 +02:00
Wojbie
bf533dd00a Reverting requested changes. Take 1
Reverting rewrites to painutils, paint and edit - keept the paste logic change in edit.
Changed and removed misc parts as requested in PR.
2017-06-28 22:58:57 +02:00
Logan Davis
0fb8177721 Fixed possible Typo. (#337) 2017-06-28 21:39:54 +01:00
Daniel Ratcliffe
22066a96dd Merge pull request #335 from Wilma456/shellcheck
Add Checks to Shell and Multishell
2017-06-28 21:20:04 +01:00
Daniel Ratcliffe
836de416bc Merge pull request #334 from Wilma456/colorcheck
Add Checks to Colors API
2017-06-28 21:16:54 +01:00
Wilma456
6bbd1f3718 Add Checks to Textutils API 2017-06-26 15:21:52 +02:00
Wojbie
6255314ba8 Fir error in http.request _post error cheacking code and add package.config to shell require code to support standard better. 2017-06-24 14:33:29 +02:00
Wojbie
fc93ee474f Merge branch 'master' into Mixed-lua-side-improvements 2017-06-24 14:29:19 +02:00
Wilma456
13ed933c6b Add Checks to Shell and Multishell 2017-06-23 18:33:11 +02:00
Wilma456
fb5ba01e5a Add Checks to Colors API 2017-06-23 17:38:40 +02:00
Wojbie
7090f6b6a7 Make settings API getNames() function sort names.
Makes it easier for eye and keeps settings from same program next to eachother.
2017-06-23 01:07:18 +02:00
Wilma456
01c024d8b0 Add equip and unequip for Pocket Computers 2017-06-22 14:05:42 +02:00
Wojbie
52a2c6f7f9 Merge pull request #3 from BombBloke/patch-1
Update paintutils.lua
2017-06-21 16:51:09 +02:00
Bomb Bloke
d9190f95ec Update paintutils.lua
Couple of fixes, plus let's not use maxn when blitting images after all. Load method ensures it isn't needed.
2017-06-21 23:41:40 +10:00
Wojbie
6df22235ae Add forgotten settings.set in bios. 2017-06-20 02:09:28 +02:00
Daniel Ratcliffe
174b63d59a Merge pull request #309 from Wilma456/execcom
Add autocompletion to exec
2017-06-19 20:44:21 +01:00
Daniel Ratcliffe
f0257028ba Merge pull request #321 from Wilma456/bioscheck
Add Checks to Bios
2017-06-19 19:18:14 +01:00
Daniel Ratcliffe
4a9f1e013c Merge pull request #324 from BombBloke/patch-1
Fix Bug with peripheral.find()
2017-06-19 19:17:02 +01:00
Bomb Bloke
a7db108762 Update paintutils.lua 2017-06-19 13:46:13 +10:00
Bomb Bloke
be861a1c0d Fix Bug with peripheral.find()
Since #315 peripheral.find() doesn't work. This PR fix this.
2017-06-19 13:09:06 +10:00
Wojbie
1489da1f5f Adds support for colon operator in complete() function.
Includes changes to lua and edit programs to correctly support that too.
2017-06-19 01:15:26 +02:00
Wilma456
c70acbb05a Add Checks to Bios 2017-06-18 17:48:07 +02:00
Wojbie
7e08662b95 Assorted fixes to rednet, textutils, gps, chat.
As reported by @SquidDev.
2017-06-18 17:12:08 +02:00
Daniel Ratcliffe
93d1facbab Merge pull request #320 from Wilma456/perifix
Fix Bug with peripheral.find()
2017-06-18 15:07:18 +01:00
Wilma456
4580f10567 Fix Bug with peripheral.find() 2017-06-18 15:58:06 +02:00
Wojbie
06b2f3511f Update paintutils.lua
Make error messages consistent with new system.
Fix some type errors and fix problem noticed by @BombBloke.
2017-06-18 12:03:14 +02:00
SquidDev
084bbe8480 Replace BitAPI with a LuaJ implementation of bit32 2017-06-17 21:39:12 +01:00
Wojbie
3acbdb2f90 Merge branch 'master' into Mixed-lua-side-improvements 2017-06-17 22:21:25 +02:00
Wojbie
01a0ce3dd0 Implements suggested changes. 2017-06-17 22:14:04 +02:00
Daniel Ratcliffe
bfb682bef9 Merge pull request #315 from SquidDev-CC/feature/argument-validation
Rewrite argument validation
2017-06-17 19:25:20 +01:00
Daniel Ratcliffe
9b5aa43d95 Merge pull request #319 from Wilma456/defread
Add Default to read()
2017-06-17 19:18:27 +01:00
Wojbie
efb351e1b0 Modification of edit.lua to use blit in writeHighlighted
Reduces amount of string operations and write calls inside writeHighlighted function by switching it to blit and using the 3rd argument in string.match.
2017-06-16 23:13:53 +02:00
Wilma456
2445a5b5d5 Add Default to read() 2017-06-15 14:50:47 +02:00
Wojbie
c611b20db8 Merge pull request #2 from BombBloke/patch-1
Paint tweaks
2017-06-14 16:32:48 +02:00
Bomb Bloke
221143e767 Update paintutils.lua
Resolve a few potential bugs.
2017-06-15 00:23:40 +10:00
Bomb Bloke
34ac28066e Create paint.lua
General re-write for speed; much less likely to fail yield protection when attempting to draw the canvas.
2017-06-15 00:16:16 +10:00
Wojbie
9472d30dfc Update startup.lua
Removed code better implemented by @Wilma456
2017-06-14 03:11:47 +02:00
SquidDev
eb628e9b62 Make error messages more consistent 2017-06-13 19:33:42 +01:00
Wojbie
157bc01be5 Merge pull request #1 from BombBloke/patch-1
Better update paintutils.lua
2017-06-13 15:55:07 +02:00
Bomb Bloke
8e958d7a13 Update paintutils.lua
Remove drawPixelInternal / drawLineHorizontal. At runtime they're both just excess calls.
Localise high-use term functions.
Arg-related function errors reflect that "colour" parameter is optional.
Add saveImage(tImage, sPath).
Use term.blit for images.
2017-06-13 23:44:07 +10:00
Wojbie
76a3562d58 Multiple fixes and feature fixes for lua side of CC
In no particular order:
bios.lua - added missing test for ensure turtle folder exists.
paintutils.lua - added drawLineHorizontal() to reduce most (not all) cases of running multiple writes on same horizontal line that can be solved with one write.
textutils.lua - Added exception to complete function - will not complete if provided with LuaKeyword - solves do->dofile problem and removes other LuaKeyword related ones in advance.
edit.lua - Changed logic in handling the paste event - if paste event is received when menu is open it automatically closed said menu and lets it paste - resolves ctrl+ctrl+v annoyance. Added Jump to Menu functions - allows for fast jump to needed line - must for bigger files and a nice feature to have.
set.lua - Switched set to use pagedPrint - this will ensure that even if there are more settings than lines on screen the set command will show you all of them.
startup.lua - Added autocompletition for turtle programs go, turn, equip, unequip and command program exec.
lua.lua - Changed return function to print returned stuff correctly -
will print all returned variables even if there are any nils in there.
2017-06-13 11:00:07 +02:00
Wojbie
225ec594e7 Adds pocket computer light support to Speaker
This makes use of new pocket computer light access peripherals have and adds said functionality to speaker. If noisy pocket has made sound the pocket computer light will turn dark blue for a second.
2017-06-12 20:54:38 +02:00
SquidDev
585c769c2a Restructure the HTTP API
- Adds support for blacklisting domains
 - Adds support for blacklisting & whitelisting IP addresses and
   IP ranges.
 - Reuse threads for HTTP requests

AddressPredicate will parse a series of patterns and convert them into
regexes or CIDR ranges. When checking whether an address is accessible,
we first ensure the domain is whitelisted and isn't blacklisted.

If everything is OK, then we start create a new thread for the HTTP
request and resolve the IP, ensuring that is whitelisted & not
blacklisted. Then the normal HTTP request is continued.

However, http.checkURL also needs to resolve the IP address. In order to
avoid blocking the Lua thread, this method will return instantly and
create a new thread which will queue an event.

As both http.request and http.checkURL are now creating threads and
queuing events, some logic is abstracted into a separate HTTPTask class
- this allows us to share the thread creation, finishing and cancelling
logic.
2017-06-12 19:22:02 +01:00
SquidDev
fac625173a Use Lua style error messages in the rom files
This makes it mostly consistent with the Java APIs, and makes debugging
significantly easier.
2017-06-12 10:54:44 +01:00
SquidDev
bffc3c18cc Rewrite argument validation
This uses a new utility class ArgumentHelper, which provides convenience
methods for parsing arguments from an array of Objects.

The format of error messages has also changed. It now follows a format
similar to Lua's native error messages - including the invalid argument
index, the expected type and the type actually received.
2017-06-12 10:28:31 +01:00
Wilma456
9e9df37c40 Add autocompletion to exec 2017-06-07 16:51:23 +02:00
Daniel Ratcliffe
0f982e6199 Merge pull request #303 from Wojbie/Window-api-fix
Fix to setPaletteColour in rgb8 mode.
2017-06-04 13:58:40 +01:00
Daniel Ratcliffe
4f3be7963e Merge pull request #304 from Wilma456/windowcheck
Add checks to window API
2017-06-04 13:57:51 +01:00
Daniel Ratcliffe
2cd4daa9ad Merge pull request #305 from Wojbie/Redirection-fix
Fix to redirection game.
2017-06-04 13:57:06 +01:00
Wojbie
60e9ce1b68 Fix to redirection game.
Was not testing for correct file type. Game ended after first lvl cause it was looking from wrong name of file.
2017-06-04 14:51:49 +02:00
Wilma456
c9bf463419 Add checks to window API 2017-06-04 12:34:40 +02:00
Wojbie
a90e2a8bfd Fix to setPaletteColour in rgb8 mode.
Was not saving color if called using rgb8 mode.
2017-06-04 11:59:30 +02:00
Daniel Ratcliffe
3828750ade Merge pull request #302 from Wojbie/Wget-binary-mode
Switch wget to use binary mode.
2017-06-03 21:32:45 +01:00
Daniel Ratcliffe
5e3eb2c6a7 Merge pull request #299 from Wilma456/termbug
Fix Bug with term.setCursorPos
2017-06-03 21:31:56 +01:00
Wilma456
fd842be37f Remove second fix 2017-06-03 16:30:35 +02:00
Wojbie
0cc65adff9 Switch wget to use binary mode.
Allows wget to download all types of files not only text ones.
2017-06-03 13:19:57 +02:00
Wilma456
d6e4323f17 Fix Bug with term.setCursorPos
I fixed 2 Bugs:
1. If you call this function, without 2 numbers, you get a error in the window API and not in your Program
2. If you call, this function with 2 numbers lower then 1 (e.g. term.setCursorPos(0,0) ), CraftOS will hang forever and need to press Ctrl+R or rejoin the world.
2017-06-02 17:35:18 +02:00
SquidDev
255dc925fb Fire Forge events where appropriate
- BlockEvent.BreakEvent and BlockEvent.HarvestDropsEvent are fired when
   digging.
 - AttackEntityEvent is fired when attacking.
 - Various PlayerInteractEvent.* events are fired when placing.

Closes #103, closes #100
2017-05-31 12:41:31 +01:00
Daniel Ratcliffe
114c49e3f6 Merge pull request #291 from Wilma456/apis
Add multishell to apis program
2017-05-29 16:57:42 +01:00
Daniel Ratcliffe
26077cbced Merge pull request #293 from Lignum/fix-warning
Fix generic-related compiler warning
2017-05-29 16:56:30 +01:00
Lignum
44c67796b8 Fix generic-related compiler warning 2017-05-29 17:35:41 +02:00
Wilma456
9770f103ed Add multishell to apis program 2017-05-29 15:55:45 +02:00
Wilma456
07ae332c24 Add fileextension for Paint (#260)
* Add fileextension for Paint

* Change extension to .nfp

* Add setting
2017-05-29 14:05:19 +01:00
Wilma456
99b5534099 Add setting for .lua extension (#278)
* Add setting for .lua extension

* Feedback  from SquidDev

* Feedback from dan200

* All requested changes are done

* Better description

* Cleaner check
2017-05-29 13:21:27 +01:00
Daniel Ratcliffe
54d202cf6b Merge pull request #288 from Wojbie/getPaletteColour-fix
Fix to getPalletteColour
2017-05-28 13:40:56 +01:00
Wojbie
47f470910e Fix to getPalletteColour
Done as @dan200 specified in #287. Closes #287.
2017-05-28 14:08:15 +02:00
Daniel Ratcliffe
235131c3fb codesize.sh now only counts lua files 2017-05-28 12:18:12 +01:00
Daniel Ratcliffe
9f35d2a2b7 Merge pull request #282 from apemanzilla/contributors_task
Dynamically generate contributors list
2017-05-28 12:06:12 +01:00
Daniel Ratcliffe
934fd08506 Merge pull request #285 from MineRobber9000/patch-1
Add github repo url to credits.txt
2017-05-28 12:03:37 +01:00
Daniel Ratcliffe
7b182e32b8 Update credits.txt 2017-05-28 12:03:23 +01:00
MineRobber___T
3d9d54beef Update credits.txt
Add url of github repo to credits.
2017-05-25 10:15:01 -04:00
apemanzilla
51b9f3ca3b Use template instead of separate task 2017-05-24 13:20:46 -04:00
apemanzilla
3b6ed552e3 Fix incorrect forEach usage 2017-05-24 12:42:49 -04:00
apemanzilla
5ff3ae6434 Add Gradle task to generate contributor list 2017-05-24 12:35:41 -04:00
Daniel Ratcliffe
e66f0d7033 Merge pull request #268 from Wilma456/credits
Add Contributors to credits.txt
2017-05-24 13:21:52 +01:00
Daniel Ratcliffe
b34adde6f3 Merge pull request #279 from lupus590/feature/lua_extention_for_tresure_disks
.lua extentions for treasure disks
2017-05-24 13:17:54 +01:00
Nephi (AKA Lupus590)
5f2446009d mass file rename, left some files...
... as they are levels for nitrogenfingers goldrunner
2017-05-22 21:34:49 +01:00
Wilma456
19fc491532 Remove Ingamename and sort alphabetical 2017-05-22 17:18:11 +02:00
Daniel Ratcliffe
853e626756 Merge pull request #263 from Lignum/fix-speakers
Speaker-related cleanup
2017-05-20 12:27:12 +01:00
Lignum
0a2cb7442d Merge branch 'master' into fix-speakers 2017-05-20 13:23:12 +02:00
Daniel Ratcliffe
d86aa50bec Merge pull request #267 from SquidDev-CC/feature/tutle-tool-changes
Shovel upgrade converts grass to path blocks
2017-05-20 12:16:47 +01:00
Wilma456
df2fe7c445 Add Contributors to credits.txt 2017-05-20 13:13:08 +02:00
Daniel Ratcliffe
6c85ca071f Merge pull request #266 from Wilma456/leveldat
Add .dat extension to all redirection levels
2017-05-20 11:57:26 +01:00
Daniel Ratcliffe
aaa82dceab Merge pull request #265 from Wilma456/newhelp
Add .txt extension to all help files (update)
2017-05-20 11:56:04 +01:00
Wilma456
b31518cfb5 Add .dat extension to all redirection levels 2017-05-20 12:51:01 +02:00
Wilma456
e8ecf5dcd5 Add .txt extension to all help files 2017-05-20 12:20:27 +02:00
Lignum
163c1db6be Fix some if statements 2017-05-19 23:37:02 +02:00
Lignum
c8697d9158 nTicks -> nPitch in speaker help file
Not sure why this was called nTicks, but it had nothing to do with ticks.
2017-05-19 20:27:08 +02:00
Lignum
c2af482615 Format TileSpeaker and TurtleSpeaker 2017-05-19 20:25:08 +02:00
Lignum
a402fc9093 Format SpeakerPeripheral correctly 2017-05-19 20:20:51 +02:00
Daniel Ratcliffe
d822147704 Merge pull request #262 from Lignum/fix-spelling
Fix some minor spelling mistakes
2017-05-19 18:49:48 +01:00
Lignum
387fc13322 Pocket Computer upgrde -> Pocket Computer upgrade 2017-05-19 19:19:29 +02:00
Lignum
b30191638f Ensure the existence, not existance 2017-05-19 19:17:23 +02:00
Lignum
95991694e0 Load modules, not modiles 2017-05-19 19:16:50 +02:00
Daniel Ratcliffe
9b6d335c5d small fix 2017-05-19 14:13:08 +01:00
Daniel Ratcliffe
ffa075cd3d Merge pull request #259 from SquidDev-CC/hotfix/check-palette
Add some sanity checks to Palette.readFromNBT
2017-05-19 13:06:35 +01:00
SquidDev
971c719a9f Add some sanity checks to Palette.readFromNBT
Printers use a Terminal to store the page currently being printed.
Printers saved in an older version of ComputerCraft would be missing the
term_palette field, resulting in an NPE when loading the tile.
2017-05-19 11:47:27 +01:00
Daniel Ratcliffe
f3c291cb4d Merge pull request #205 from SquidDev-CC/feature/packet-network-api
Expose wireless network in the public API
2017-05-18 23:57:44 +01:00
SquidDev
d76ce22db7 Split transmit into two separate methods
This removes the interdimensional and range options from the packet
and ensures they are provides them from the transmit* methods instead.
2017-05-18 23:50:14 +01:00
Daniel Ratcliffe
6d590cee3b Merge pull request #258 from Wojbie/Speaker-volume-fix
Speaker max hearable range limit
2017-05-18 22:32:38 +01:00
Wojbie
af07a78f76 Speaker rage limit
Limit max volume of speaker to volume of normal noteblock.
2017-05-18 23:12:55 +02:00
Daniel Ratcliffe
757b1efd7e Merge pull request #255 from SquidDev-CC/feature/add-package-loaded
Include standard Lua libraries in package.loaded
2017-05-18 00:20:46 +01:00
SquidDev
d19bc53cb4 Include standard Lua libraries in package.loaded
PUC Lua includes all builtin libraries in the package.loaded table.
2017-05-18 00:15:21 +01:00
Daniel Ratcliffe
61b2ed36a9 Reworked how shell creates environments. Implemented require
"shell" now runs each program in a new lua environment, instead of
sharing that lua environment between all programs launched under a one
shell. Said environment now includes an implemenation of "require" and
the "package" API, so that programs can require modules into that
environment.

This means that programs can require in libraries without polluting the
global namespace, and without breaking the virtual computer model, as
each program has it's own set of requires, which are discarded when the
program ends.
2017-05-17 23:43:44 +01:00
Daniel Ratcliffe
4fb93853ce Running "edit foo" will now create "foo.lua" if "foo" does not exist 2017-05-17 22:47:39 +01:00
Daniel Ratcliffe
6e6b8e7eef Made os.loadAPI handle .lua files. Renamed all builtin APIs to .lua 2017-05-17 22:47:13 +01:00
Daniel Ratcliffe
50a4a961e5 Pressing tab in "edit" now inserts 4 spaces instead of 2, backspace now deletes them 2017-05-17 19:48:27 +01:00
Daniel Ratcliffe
f5edb32be9 Replaced tabs with spaces in all lua files 2017-05-17 19:48:27 +01:00
Daniel Ratcliffe
b86708aaf8 Merge pull request #253 from SquidDev-CC/hotfix/empty-files
Fix files not writing data when closed
2017-05-17 19:35:26 +01:00
SquidDev
5cf581e6c9 Fix files not writing data when closed
As the raw stream was being provided to the parent class, buffered data
was not written, resulting in empty files. This ensures the buffered
reader/writer is the one which is closed.
2017-05-17 19:25:13 +01:00
Daniel Ratcliffe
05e838ca5a Strip ".lua" from program names in multishell title bar 2017-05-17 19:05:45 +01:00
Daniel Ratcliffe
25a18ee33a Merge pull request #250 from Wilma456/luaex
Add .lua extension to all programs and startup (updated)
2017-05-17 18:13:56 +01:00
Wilma456
1d905963e9 Add .lua extension to all programs and startup 2017-05-17 16:28:43 +02:00
Daniel Ratcliffe
ebf8492198 Merge pull request #249 from SquidDev-CC/hotfix/speaker-server
Fixes speakers playing incorrect sounds on the server
2017-05-17 11:11:34 +01:00
SquidDev
12e61efd76 Fixes speakers playing incorrect sounds on the server
As a new SoundEvent was being created each time, the actual sound was
not in the registry, resulting in the sound -> id mapping yielding
incorrect values.
2017-05-17 08:00:14 +01:00
Daniel Ratcliffe
0a350077e9 Updated turtle speaker texture to match the style of the other turtle peripherals 2017-05-16 23:59:35 +01:00
Daniel Ratcliffe
19c8613dea Better shell.programs() fix
Prevents duplicate entries
2017-05-16 23:34:53 +01:00
Daniel Ratcliffe
fb00698557 Merge pull request #239 from Wilma456/shellprog
Make shell.programs filter .lua extension
2017-05-16 23:00:14 +01:00
Daniel Ratcliffe
3d1eb830c7 Saner extension check 2017-05-16 22:59:39 +01:00
Daniel Ratcliffe
2bc72a883f Merge pull request #228 from Lignum/startup-dir
Startup directories
2017-05-16 22:56:00 +01:00
Daniel Ratcliffe
c15fcd00ec Merge pull request #248 from Cruor/master
Added help file for speakers
2017-05-16 22:55:43 +01:00
Cruor
cd2a51f816 Updated text... again... 2017-05-16 23:39:48 +02:00
Cruor
8b7c769ff9 Update speakers 2017-05-16 23:33:09 +02:00
Cruor
4101cb2dfb Added help file for speakers
Added help file for speakers
2017-05-16 23:30:53 +02:00
Lignum
03794970ba Merge master into startup-dir 2017-05-16 23:25:54 +02:00
Lignum
9d0afe9e18 Mention startup directories in whatsnew and changelog
Also makes the line endings in these files consistent to be LF only.
2017-05-16 23:22:34 +02:00
Daniel Ratcliffe
f833450a68 Changed permissions on deploy.sh 2017-05-16 21:57:57 +01:00
Daniel Ratcliffe
d6bf2c5dbc Merge pull request #246 from SquidDev-CC/hotfix/at-stacked-block
Remove AT for Block.createStackedBlock
2017-05-16 21:38:49 +01:00
SquidDev
b5e75a86c8 Remove AT for Block.createStackedBlock
Access transformers do not propagate to sub classes, and so the access
transformer did not work here. Reverting to reflection fixes this issue.
2017-05-16 21:19:36 +01:00
Lignum
00943163c8 Replace type check with nil check 2017-05-16 21:53:50 +02:00
Lignum
eb9b7f3b8c Ignore dirs inside startup directories 2017-05-16 21:50:35 +02:00
Daniel Ratcliffe
ba4b1e21fe Merge pull request #238 from SquidDev-CC/feature/binary-handles
Refactor the filesystem and HTTP code
2017-05-16 20:02:34 +01:00
Daniel Ratcliffe
cd85a03429 Merge pull request #237 from Restioson/feature/speaker
[Peripheral] Speaker
2017-05-16 19:52:10 +01:00
Restioson
0113e7229f Added speaker to whatsnew 2017-05-16 20:44:34 +02:00
Restioson
7e556acebc Added Speaker to Changelog 2017-05-16 20:42:16 +02:00
Daniel Ratcliffe
aa8455e0b1 Merge pull request #245 from Wilma456/settings
Update Settings Help
2017-05-16 19:39:34 +01:00
Daniel Ratcliffe
2e22ca4ccf Merge pull request #217 from SquidDev-CC/feature/logging
Add a basic logging system
2017-05-16 19:38:03 +01:00
Wilma456
68f4611abc Add Default Settings 2017-05-16 20:35:46 +02:00
SquidDev
0e1135ed97 Disable peripheral logging by default 2017-05-16 19:35:07 +01:00
Daniel Ratcliffe
ebbdd29bd6 Merge pull request #243 from SquidDev-CC/feature/access-transformer
Replace reflection with access transformers
2017-05-16 19:25:10 +01:00
Daniel Ratcliffe
8c4331d15a Added checks to window.setTextColor and window.setBackgroundColor 2017-05-16 19:23:08 +01:00
Restioson
4df4b91d09 Converted (!x == y) to x != y 2017-05-16 20:02:59 +02:00
Restioson
b28c565665 (Hopefully) addressed @dan200's concerns
Push your fix to thread safety if this doesn't cut it
2017-05-16 19:48:38 +02:00
SquidDev
efb0065ebd Add config option to disable certain error messages 2017-05-16 15:59:09 +01:00
SquidDev
a0b6cbb671 Remove ILogger facade
Just use global Log4j logger on the ComputerCraft class.
2017-05-16 15:49:55 +01:00
SquidDev
44ba4069c1 Print stack traces/add logging messages in several places
This will hopefully make it easier to track down various issues which
might otherwise go unnoticed or provide little information.

The main areas modified are those that external APIs may provide values
for or interact with: various providers and ILuaObject/IPeripheral
implementations. However, we do also log in a couple of other places
which indicate a problem with this, or another, mod.
2017-05-16 15:49:55 +01:00
SquidDev
bdc438fc62 Add a basic logging system
This adds a common ILogger interface and two built-in loggers - one
which prints to stdout, the other using a Log4J logger. These are split
up as not to cause dependency issues for emulators.

The stdout logger is enabled by default, but the ComputerCraft mod class
will swap over to using FML's mod specific logger, which provides a more
consistent look with the rest of Minecraft.
2017-05-16 15:49:55 +01:00
Restioson
b3c49db761 Made Speaker threadsafe & fix warnings 2017-05-15 17:42:29 +02:00
Restioson
7ff4631a9f @gegy1000 strikes again 2017-05-15 17:42:29 +02:00
Restioson
aad81bead7 Fix style
@gegy1000 don't say *I* get distracted
2017-05-15 17:42:29 +02:00
Restioson
88b55934c7 Fix castException 2017-05-15 17:42:29 +02:00
Restioson
42962dcd48 Fix Noisy turtles not in creative - Thanks @SquidDev 2017-05-15 17:42:29 +02:00
Restioson
093d2ea89f Added PocketSpeaker & corrected blockmodel for turtle speaker 2017-05-15 17:42:29 +02:00
Restioson
97a6679510 Dammit, I hope my git history works now! 2017-05-15 17:38:50 +02:00
Restioson
a3b0e4e993 Added speaker as turtle peripheral 2017-05-15 17:38:50 +02:00
Restioson
3bf15a3798 Added speaker model - potentially glitched 2017-05-15 17:38:50 +02:00
Restioson
dc96f2121a Fix Speaker not playing sounds on break and replace for entire Lua session 2017-05-15 17:38:50 +02:00
Restioson
2899246dbc Fix speaker peripheral API 2017-05-15 17:38:50 +02:00
gegy1000
2444245b80 Speaker rendering and name 2017-05-15 17:38:50 +02:00
Restioson
a748d0167b Fixed Speaker being recognized as Disk Drive. Massive thanks to @SquidDev 2017-05-15 17:38:50 +02:00
Restioson
6cf1801f7e Changed method names to camelCaser 2017-05-15 17:38:50 +02:00
Restioson
61c08afc7f Implemented speaker. It's broken though - thinks it's a Disk Drive
~~Damn Tile Entities these days, always with their identity crises~~
2017-05-15 17:38:50 +02:00
Restioson
61dc61d356 Attempt to fix git history #2 2017-05-15 17:36:29 +02:00
Daniel Ratcliffe
7f365c5102 Merge pull request #232 from SquidDev-CC/feature/remove-duplicate-history
Do not insert empty or duplicate entries into shell history
2017-05-15 14:00:15 +01:00
Daniel Ratcliffe
42874073e9 Merge pull request #230 from SquidDev-CC/feature/dye-improvements
Dye improvements
2017-05-14 21:45:33 +01:00
SquidDev
63cdc7a72e Replace reflection with access transformers
This makes the code slightly neater and allows us to catch places where
the variable/function has been renamed between versions.
2017-05-14 17:01:14 +01:00
SquidDev
cf7308dbc8 Fix holes appearing in coloured turtles
There was a very small gap between the turtle frame and the top of the
turtle body. This increases the height of the body by one pixel, adding
a little bit of overlap and ensuring the frame renders on top fixes
this issue.
2017-05-14 16:02:15 +01:00
SquidDev
b37dbbd0af Allow dying pocket computers too
This splits up the pocket computer textures and models into the frame
(off, on, blinking), colour layer (normal, advanced, custom) and modem
light.
2017-05-14 15:02:56 +01:00
SquidDev
a6b870dfbb Expand IPocketAccess.getLight/setLight to use RGB colours
This allows us to restore the modem light to its original colour.
2017-05-14 14:22:20 +01:00
SquidDev
6426255bd4 Remove getColour and setColour methods from ITurtleAccess
This allows us to remove the m_Colour field from TurtleBrain
2017-05-14 14:17:55 +01:00
SquidDev
8c36eccfef Allow dying turtles arbitrary colours
- Makes ITurtleItem implement IColourableItem
 - Only cache one turtle item model for all colours, rather than one for
   each colour.
 - Allow ITurtleAccess to set an arbitrary colour.
2017-05-14 14:17:55 +01:00
SquidDev
88de097c1c Add more general item colouring system
This allows for other items, such as turtles, to be dyed in the future.
This also adds support for the ore dictionary, meaning you can use other
mod's dyes to colour items.
2017-05-14 14:17:54 +01:00
SquidDev
6ccffe9742 Refactor the filesystem and HTTP code
- Move the encoding/decoding from the Filesystem implementation to the
   individual handles.
 - Move each handle into an core.apis.handles package from the main fs
   API.
 - Move the HTTP response to inherit from these handles.
 - Allow binary handles' read function to accept a number, specifying
   how many characters to read - these will be returned as a Lua string.
 - Add readAll to binary handles
 - Allow binary handles' write function to accept a string which is
   decoded into the individual bytes.
 - Add "binary" argument to http.request and friends in order to return
   a binary handle.
 - Ensure file handles are open when reading from/writing to them.
 - Return the error message when opening a file fails.
2017-05-13 22:47:28 +01:00
Daniel Ratcliffe
2fd01b2adf Merge pull request #233 from SquidDev-CC/feature/file-handle-errors
Provide various error messages for file handles
2017-05-13 21:55:37 +01:00
Daniel Ratcliffe
ea0d688345 Merge pull request #234 from SquidDev-CC/feature/remap-ids
Remap all blocks and items to underscore_case
2017-05-13 21:44:10 +01:00
Daniel Ratcliffe
891666c8bf Merge pull request #220 from SquidDev-CC/feature/item-handler
Replace most inventory handling code with IItemHandlers
2017-05-13 21:31:58 +01:00
SquidDev
a328308f67 Switch from using INetwork to IPacketNetwork 2017-05-13 20:43:12 +01:00
SquidDev
e6ef1cfadd Add packet network API
This provides a publically accessible way of interacting with wireless
networks, hopefully extending to wired networks in the future.

Unlike the original INetwork/IReceiver system, networked devices listen
on all channels, filtering when they recieve the packet. This allows
other peripheral mods to be more flexible in their packet handling.
2017-05-13 20:43:10 +01:00
ObloxCC
7f754f33bb Updated (C) from 2016 to 2017 (#229)
* Updated (C)

* Fixed Whitespace

bugs, bugs, and more bugs

* Fixed Whitespaces 1/2

* Fixed Whitespaces 2/2

* Fixed Whitespaces 3/2
2017-05-13 19:20:39 +01:00
Wilma456
516bd8cf03 Make shell.programs filter .lua extension 2017-05-13 13:37:18 +02:00
SquidDev
add046cbda Remap all blocks and items to underscore_case
This makes block/model names a little mode consistent and should help
with porting to 1.11.2.

 - Prefix all tile entities with "computercraft:".
 - Change all "pascalCase" and "CC-*" items to use underscore_case
 - Listen to the missing mappings event and gracefully convert
   blocks/items.
2017-05-12 13:29:56 +01:00
SquidDev
9908f8c289 Do not insert empty or duplicate entries into shell history
If a string is empty or the same as the previous command then it will
not be inserted into history.
2017-05-11 21:01:23 +01:00
Lignum
259fe4b6b4 Remove unnecessary shell.resolveProgram call 2017-05-11 18:12:58 +02:00
SquidDev
b07f28c30c Replace most inventory handling code with IItemHandlers
- Make InventoryUtil deal with item handlers instead. This
   significantly simplifies the implementation, the interface now
   does most of the hard work.
 - Add InvWrapper item handlers to printers, disk drives and turtles
 - Add IItemHandlerModifiable accessor to ITurtleAccess
 - Migrate all other inventory code (mostly turtle commands) to use
   item handlers instead.
2017-05-11 00:00:10 +01:00
Lignum
8acf43256c Don't sort startup files
fs.list is already sorted, making this unnecessary.
2017-05-10 23:27:07 +02:00
Lignum
962e419098 Allow having a startup directory and a startup.lua file simultaneously 2017-05-10 23:21:04 +02:00
Lignum
2e7c9b163d Enable the use of startup directories 2017-05-10 23:02:08 +02:00
SquidDev
2c63a5f9a3 Provide various error messages for file handles
- fs.open will return an error message if the handle cannot be read
 - fs and http handles will error when reading from a closed file
2017-05-10 10:52:35 +01:00
Daniel Ratcliffe
25128dfb66 Merge pull request #224 from SquidDev-CC/feature/lowercase-models
Lower case most resource names
2017-05-09 20:31:24 +01:00
Daniel Ratcliffe
c049de6939 Merge pull request #221 from SquidDev-CC/feature/nullable-annotations
Fix several crashes caused by incorrect NonNull annotations.
2017-05-09 20:00:02 +01:00
SquidDev
82dbaece41 Lower case all resource names
- Lower case all model and texture names
 - Move model registration code into preInit - this ensures we don't
   get texture/model errors in the preInit stage.
2017-05-09 16:37:32 +01:00
Daniel Ratcliffe
8e3badf4f7 Merge pull request #222 from SquidDev-CC/feature/register-player
Register TurtlePlayer in the entity registry
2017-05-09 14:00:39 +01:00
SquidDev
93aea371a7 Shovel upgrade converts grass to path blocks
Using turtle.dig() with a shovel upgrade on a grass block will create a
path block.

Closes #127
2017-05-09 13:03:12 +01:00
SquidDev
dd63fac8af Register TurtlePlayer in the entity registry
Fixes #143
2017-05-09 12:16:32 +01:00
SquidDev
8b411387f1 Fix several craches caused by incorrect NonNull annotations.
Awfully sorry about this. It appears that Minecraft's annotations are
occasionally wrong. IntelliJ will automatically add "not-null" checks on
these annotations, resulting in crashes when they are actually null.
2017-05-09 00:54:15 +01:00
ObloxCC
922818dfa5 Add setPaletteColor and rgb8 to help files (#214)
* Added rgb8 help

* Update colours

* Added rgb8 help

* Added setPaletteColor help

* Added setPaletteColor help

* Added setColorPalette and rgb8 to change log

* Fixed formatting

* Fixed formatting

* Fixed formatting

* Fixed formatting

* Added changes to change log

* Added changes to whatsnew

* Fixed changelog

* Fixed whatsnew

* Added setPalatteColor

* Fixed Palette spelling

* Added space after 'b'

* Added getPaletteColor

* Ddded getPaletteColor

* Added getPaletteColor()

* Added getPaletteColor

* Update changelog

* Added getPaletteColor
2017-05-07 22:24:32 +01:00
Daniel Ratcliffe
0308ec555a Merge pull request #207 from SquidDev-CC/feature/cleanup
Fix a couple of warnings
2017-05-07 18:26:07 +01:00
Daniel Ratcliffe
008663c0e1 Lua fix 2017-05-07 17:42:39 +01:00
Daniel Ratcliffe
38e09920fa Lua fix 2017-05-07 17:40:23 +01:00
Daniel Ratcliffe
6fba381a4e Merge pull request #211 from Lignum/shell-run-lua
Make shell.resolveProgram pick up on *.lua files
2017-05-07 17:33:44 +01:00
Daniel Ratcliffe
e063f5a6b8 Merge pull request #197 from Lignum/colour-palettes
Modifiable terminal colour palette
2017-05-07 17:31:14 +01:00
Daniel Ratcliffe
0b8b39ced0 colours.rgb8(r,g,b) and colours.rgb8(c) are now the inverse of each other 2017-05-07 17:29:59 +01:00
Daniel Ratcliffe
5f22d8bac6 Enabled setTextColour/setBackgroundColour with all colours on greyscale monitors
It's fine, now that we have greyscale rendering
2017-05-07 17:24:45 +01:00
Daniel Ratcliffe
a5e1dad5fc Enabled term.setText/BackgroundColour with non grey colours on greyscale monitors
As rendering is greyscale now, this is fine.
2017-05-07 17:22:49 +01:00
Daniel Ratcliffe
ebb7d7a8d9 Enabled window.setText/BackgroundColour with no grey colours. Some small optimisations 2017-05-07 17:19:21 +01:00
Lignum
c6abf0b890 Make shell.resolveProgram pick up on *.lua files 2017-05-07 16:21:15 +02:00
Lignum
c10e1ba78c Get rid of setPaletteColour table overload 2017-05-07 15:04:09 +02:00
SquidDev
2e901a063d Remove accessibility modifiers from all enums and interfaces 2017-05-07 13:35:18 +01:00
SquidDev
5a60818c99 Make many fields final 2017-05-07 13:35:18 +01:00
SquidDev
a3400ecf26 Fix all the deprecated warnings 2017-05-07 13:35:05 +01:00
SquidDev
a2fd0b1f7f Use block comment instead of Javadoc for license 2017-05-07 13:30:10 +01:00
SquidDev
db9cd15fb3 Remove most raw types
This means we can remove even more casts and what not.
2017-05-07 13:30:05 +01:00
SquidDev
9af15d1e30 Remove some unnecessary constructs
- Replace for and while loops with for iterators
 - Remove unused casts
2017-05-07 13:29:52 +01:00
SquidDev
dc5517303f Add @Nullable and @NonNull annotations 2017-05-07 13:29:49 +01:00
Lignum
941d47908f Oh bother 2017-05-07 13:09:51 +02:00
Lignum
0164032a4a Allow greyscale palettes on basic computers 2017-05-07 13:04:54 +02:00
Lignum
70c2f50aa8 Un-break the non-table setPaletteColour overload 2017-05-07 12:55:16 +02:00
Lignum
54273fc6e5 Add Palette.DEFAULT 2017-05-07 12:51:06 +02:00
Lignum
4e55e03c8b Don't sync the whole palette in window.setPaletteColour 2017-05-07 12:46:23 +02:00
Lignum
156e74b69c setColour -> setPaletteColour 2017-05-07 12:40:31 +02:00
Daniel Ratcliffe
9d1872c948 Merge pull request #172 from SquidDev-CC/feature/pocket-upgrades
Pocket computer upgrades
2017-05-07 10:32:22 +01:00
SquidDev
8ba5edb6e4 Minor cleanup of pocket computer upgrades
- General improvements of the docs.
 - Move all ItemStack code to the ItemPocketComputer class
 - Make PocketAPI execute on the server thread, rather than the computer
   thread
2017-05-07 08:09:36 +01:00
SquidDev
5a4375f6ac Allow changing the colour of the modem light
This now uses an integer between 0 and 15 to represent a colour, rather
than a simple on/off flag.
2017-05-07 08:09:36 +01:00
SquidDev
6020cd55b1 Added documentation and updated changelog/whatsnew 2017-05-07 08:09:36 +01:00
SquidDev
7f8100ae0f Check the offhand inventory too when searching for upgrades 2017-05-07 08:08:09 +01:00
SquidDev
22631cfc63 Add .equip and .unequip methods to pocket API. 2017-05-07 08:08:09 +01:00
SquidDev
5faceac7ba Add registry for pocket computer upgrades 2017-05-07 08:08:09 +01:00
Daniel Ratcliffe
ff16868dd8 Merge pull request #206 from Lignum/update-craftos-version
Set CraftOS version to 1.8
2017-05-07 00:41:58 +01:00
Lignum
287c6f172c Allow passing RGB8 hex values to term.setColour 2017-05-07 01:16:48 +02:00
Daniel Ratcliffe
cad10fa2c7 Fixed incorrectness in os.day(). Added os.epoch() 2017-05-06 23:56:28 +01:00
Daniel Ratcliffe
58713caa73 Merge pull request #203 from SquidDev-CC/feature/turtle-models
Convert turtle rendering to use tinting
2017-05-06 23:56:13 +01:00
Daniel Ratcliffe
a6e3d4fd26 Merge pull request #195 from SquidDev-CC/hotfix/selection-boxes
Fix selection boxes not being shown
2017-05-06 23:55:45 +01:00
SquidDev
f34a319b79 Make cable collision boxes more accurate for cables
Each cable segment is added to the list, meaning you can get close and
snugly with the cables.
2017-05-06 23:45:15 +01:00
Lignum
1cc403191f Add colours.rgb8(r, g, b)/colours.rgb8(hex) 2017-05-07 00:13:36 +02:00
Lignum
2c7ee1d7e7 Bump CraftOS version to 1.8 2017-05-06 23:26:45 +02:00
Daniel Ratcliffe
3e3c1239b0 Merge pull request #183 from timia2109/master
Add real world time support
2017-05-06 22:26:14 +01:00
Daniel Ratcliffe
4b4e041f6f Merge branch 'master' into master 2017-05-06 22:25:46 +01:00
Daniel Ratcliffe
423d5af87f Merge pull request #191 from SquidDev-CC/feature/text-illumination
Make monitor text glow in the dark
2017-05-06 22:11:28 +01:00
Daniel Ratcliffe
5b6bbc3cbf Merge pull request #200 from Lignum/fs-weak-set
Replace WeakHashMap for open files with a weak set
2017-05-06 21:44:28 +01:00
Daniel Ratcliffe
f4dab801e4 Merge pull request #204 from SquidDev-CC/feature/some-deprecation
Use IBlockState instead of Block methods
2017-05-06 21:41:54 +01:00
Lignum
a9e7acbec5 Fix monitors fetching palette when there is no terminal 2017-05-06 20:23:44 +02:00
Lignum
ac2382a861 Add setColour overload with table parameter 2017-05-06 20:22:16 +02:00
SquidDev
2f93354981 Remove dye block state property
It doesn't make sense to have it now as the coloured models do not exist
any more, and so would just produce errors should we try to load them.
2017-05-06 17:41:49 +01:00
SquidDev
c7f5d039b2 Use IBlockState instead of Block methods
There was a crash in RedstoneUtil when redstone state was changing next
to a full block due to the incorrect state being passed. By using
IBlockState methods we ensure that this cannot happen again.

The old IBlockState methods were also deprecated, so this reduces the
warning count a little. I've also moved string translation into
StringUtils, to reduce the number of deprecation warnings from there.
2017-05-06 15:31:06 +01:00
SquidDev
d652bdb0b0 Convert turtle rendering to use tinting
This uses Minecraft's colour tinting system in order to change the
colour of turtle models. This removes the need to have 16 models and
textures for each colour, reducing texture atlas space and hopefully
memory consumption.

See #145
2017-05-06 15:06:02 +01:00
Tim Ittermann
f1c4634dfa os.time( ... ) now returns float 2017-05-06 14:52:02 +02:00
Tim Ittermann
f89bbeee54 Remove import 2017-05-06 14:30:19 +02:00
Tim Ittermann
e0e81a9b18 Put time functions into the OS API 2017-05-06 14:24:48 +02:00
Lignum
bfa5f6ec9c Make palettes work properly with the window API 2017-05-05 20:23:57 +02:00
Lignum
988e9f10db Fix compiler error 2017-05-05 19:13:52 +02:00
Lignum
b0ac48b9a3 Use some sweet tricks to have a weak set to store open files 2017-05-05 19:11:59 +02:00
Lignum
3de674dfb1 Simplify the palette payload to an int array 2017-05-05 18:47:43 +02:00
Lignum
39a56c8e55 Get rid of the PaletteColour class
It just took up a bunch of space. We're storing an array of float[3] now.
2017-05-05 18:22:48 +02:00
Daniel Ratcliffe
06b63980eb Merge pull request #196 from SquidDev-CC/feature/docs
Fix several documentation warnings
2017-05-05 17:19:26 +01:00
Daniel Ratcliffe
3eae944923 Merge pull request #198 from SquidDev-CC/hotfix/no-reset-redstone
Do not reset redstone inputs when adding peripherals
2017-05-05 17:17:15 +01:00
Lignum
6997471280 Add palette functions to monitor peripheral 2017-05-05 18:12:33 +02:00
SquidDev
4b95ed5d53 Do not reset redstone inputs when adding peripherals
As of 8abff95441, peripherals no longer
block redstone input. As this is no longer the case, redstone levels
should not be reset.
2017-05-05 17:00:44 +01:00
Lignum
088dab799e Network the colour palette
Which means it actually has a visible effect! 🎉
2017-05-05 17:21:53 +02:00
SquidDev
0cdd0ea21a Change license headers to block comments
This means they do not get picked up by Javadoc and friends
2017-05-05 16:16:09 +01:00
Daniel Ratcliffe
c413b9af04 Merge pull request #194 from SquidDev-CC/feature/docs
General improvements to the documentation
2017-05-05 16:08:45 +01:00
SquidDev
76e926c090 Document several undocumented arguments and exceptions 2017-05-05 16:07:18 +01:00
SquidDev
d87b0e9435 Fix selection boxes not being shown
getSelectedBoundingBox expects a bounding box relative to (0, 0, 0) but
we were returning one relative to the current block. Instead we allow
the default behaviour to continue, which will call getBoundingBox and
offset it.
2017-05-05 15:25:07 +01:00
Lignum
b0f0d8fd71 Add getColour/setColour to the window api 2017-05-05 16:14:13 +02:00
SquidDev
7b07921a73 General improvements to the documentation
- Add documentation for all undocumented methods and enums.
 - Use @code, @link and @see where appropriate.
 - Fix spelling in a couple of cases.
2017-05-05 14:59:11 +01:00
Lignum
56c9dec687 Add term.setColour/term.getColour 2017-05-05 15:52:21 +02:00
Lignum
936a531cd5 Add a palette class and use it for rendering 2017-05-05 15:24:29 +02:00
Daniel Ratcliffe
09215daa03 FileSystem uses a WeakHashMap to store it's open file handles
This means if lua code forgets to free a handle, the java GC will still
be able to collect the stream (andclose the file in the finaliser in the
process)
2017-05-05 00:54:24 +01:00
Daniel Ratcliffe
42f2235d45 Made the black colour on monitors, terminals, block and item graphics darker
0x111111 is now used throughout, previously there was quite a bit of
variance
2017-05-05 00:54:24 +01:00
Daniel Ratcliffe
2436d813e6 Treat a maximumFilesOpen values of 0 as unlimited 2017-05-05 00:54:23 +01:00
Daniel Ratcliffe
6271555c45 Merge pull request #192 from Lignum/render-improvements
Small terminal & monitor rendering improvements
2017-05-04 23:09:48 +01:00
Lignum
4b8493baab Terminal cursor bounds checking 2017-05-05 00:08:10 +02:00
Lignum
4e3def39e0 Render terminal cursor in a less awkward way
The previous way seemed weird enough to seem to have had a purpose, but I can't tell. Revert this if it turns out that there was.
2017-05-04 23:53:43 +02:00
Lignum
7e71045c7b Remove texture coordinates from text background part 2017-05-04 23:49:08 +02:00
Lignum
2d5d5e3a9e Use GL_TRIANGLES in FixedWidthFontRenderer 2017-05-04 23:43:05 +02:00
Lignum
c0b5b6af07 Add ".idea" to .gitignore 2017-05-04 23:39:12 +02:00
Lignum
c104eabcdd Use GlStateManager where necessary, replace GL_QUADS with GL_TRIANGLE_STRIP 2017-05-04 23:38:24 +02:00
SquidDev
933bdcc6b7 Make monitor text glow in the dark 2017-05-04 22:24:39 +01:00
Tim Ittermann
45803e4a49 Replace get...() functions with properties. NOT ALL TESTED YET! 2017-05-04 23:18:03 +02:00
Daniel Ratcliffe
8abff95441 Peripherals no longer break turtle<->redstone connectivity
I can't think of a good reason for this feature tbh
2017-05-04 22:13:14 +01:00
Daniel Ratcliffe
f99caed4f2 Merge pull request #169 from Lignum/fd-limit
Configurable file descriptor limit
2017-05-04 22:12:50 +01:00
Daniel Ratcliffe
4b0a976bd6 Merge pull request #182 from SquidDev-CC/feature/turtle-upgrade-both
Allow turtle upgrades to act as tools and peripherals
2017-05-04 22:02:09 +01:00
Lignum
30d191df0b Avoid casts with generic type args 2017-05-04 23:00:02 +02:00
Daniel Ratcliffe
17a3e120e8 Merge pull request #180 from boq/master
Handle tile entity changes
2017-05-04 21:42:34 +01:00
Daniel Ratcliffe
55b160e1bb Merge pull request #164 from SquidDev-CC/hotfix/turtle-connectivity
Fix redstone connectivity on turtles
2017-05-04 21:28:08 +01:00
Daniel Ratcliffe
a57eb14113 Added windows setup script 2017-05-04 21:14:28 +01:00
Daniel Ratcliffe
fa99305914 Merge pull request #168 from SquidDev-CC/hotfix/modem-model-rotation
Various model improvements
2017-05-04 21:08:51 +01:00
Daniel Ratcliffe
27ef182294 Merge pull request #158 from SquidDev-CC/feature/require-container
Require the player to be interacting with the computer when typing
2017-05-04 21:08:34 +01:00
Daniel Ratcliffe
82e76d9872 Merge pull request #184 from SquidDev-CC/hotfix/sort-list
Sort the result of FileSystem.list
2017-05-04 21:06:26 +01:00
Daniel Ratcliffe
2a0556fa4c Merge pull request #185 from SquidDev-CC/hotfix/unpack-length
Manually specify the number of values to unpack
2017-05-04 21:05:14 +01:00
Daniel Ratcliffe
22e36fc35d Merge pull request #178 from boq/patch-1
Fix compilation error
2017-05-04 21:04:14 +01:00
Daniel Ratcliffe
655a328b86 Merge pull request #174 from SquidDev-CC/hotfix/shutdown-abort
Send termination signals unless the computer is off
2017-05-04 21:03:40 +01:00
Daniel Ratcliffe
df1ef7133d Merge pull request #181 from SquidDev-CC/hotfix/gps-locate
Ensure GPS coordinates are numbers
2017-05-04 21:02:36 +01:00
SquidDev
bd14223ea8 Manually specify the number of values to unpack
table.unpack will often stop at the first nil value, meaning some event
arguments may be discarded. By storing the number of arguments through
table.pack, and then using that count when unpacking, we can ensure all
values are returned/resumed with.
2017-05-04 10:49:41 +01:00
SquidDev
72dfb0e7cc Sort the result of FileSystem.list
This ensures fs.list and fs.find always return the same result.

For some reason, the ComputerCraft jar was being packaged differently on
some platforms, causing files to appear in a different order. As
computers depend on the colors API being loaded before colours, we need
to ensure that they are loaded in a consistent order.
2017-05-03 22:29:57 +01:00
Tim Ittermann
b2cc6ec82a Add TimeAPI to Computers APIs 2017-05-03 23:12:48 +02:00
Tim Ittermann
c1d5ae2a09 Rename src/main/java/dan200.computercraft/core/apis/TimeAPI.java to src/main/java/dan200/computercraft/core/apis/TimeAPI.java 2017-05-03 23:11:52 +02:00
Tim Ittermann
627524dcb7 Create TimeAPI.java 2017-05-03 23:10:58 +02:00
SquidDev
6b6829e22b Use tonumber when validating message format 2017-05-03 18:39:32 +01:00
SquidDev
67eecd4b1c Use tonumber instead of checking type 2017-05-03 18:21:14 +01:00
SquidDev
a021a072b5 Allow turtle upgrades to act as tools and peripherals
This may be useful when you want your tool to also provide additional
methods. For instance, a pickaxe could provide methods to check whether
it can break the block in front.
2017-05-03 17:28:54 +01:00
SquidDev
7e5970673f Ensure GPS coordinates are numbers
Fixes #138
2017-05-03 16:35:45 +01:00
Bartek Bok
4eb4bb933f Different fix for shadow turtles 2017-05-03 16:03:47 +02:00
Bartek Bok
5284b145f8 Handle tile entity changes 2017-05-03 11:36:55 +02:00
Bartek Bok
bd8769f300 Fix compilation error 2017-05-02 23:40:31 +02:00
Lignum
994dcd9f58 Localise the maximumFilesOpen setting 2017-05-02 18:29:50 +02:00
Lignum
2bfb53227a Merge master into fd-limit 2017-05-02 18:26:45 +02:00
SquidDev
ba761a15b6 Send termination signals unless the computer is off
If a shutdown has been queued, then the abort message was not set. This
allowed for programs to run for a significantly longer period of time.
2017-05-02 14:04:48 +01:00
Daniel Ratcliffe
58e6e9ea46 Fixed a typo 2017-05-02 13:56:24 +01:00
Daniel Ratcliffe
4825aefccf Merge pull request #167 from SquidDev-CC/hotfix/limit-label
Impose additional limitations on disk and computer labels
2017-05-02 13:54:43 +01:00
Daniel Ratcliffe
3a360a50b0 Merge pull request #166 from SquidDev-CC/feature/config-gui
Add config GUI
2017-05-02 13:46:01 +01:00
SquidDev
65ef8a0937 Add config GUI description to changelog/whatsnew 2017-05-02 13:35:05 +01:00
SquidDev
14d3a182d9 Fix NPE when clearing disk label 2017-05-02 13:32:53 +01:00
Daniel Ratcliffe
800e448264 Improved the wording of some of the labels in the Config UI 2017-05-02 13:28:54 +01:00
SquidDev
2fef772f3d Use '?' for unprintable characters 2017-05-02 13:24:42 +01:00
Daniel Ratcliffe
463d6fdcbe Fixed some typos 2017-05-02 13:18:20 +01:00
Daniel Ratcliffe
b2c786c06c Merge pull request #171 from JLLeitschuh/fix/daemon_thread
Make threads daemon threads
2017-05-02 08:53:05 +01:00
SquidDev
c537c4fa78 Swap from builtin/generated to item/generated
This model has more sane defaults, meaning items are scaled to the
appropriate size.
2017-05-02 02:12:51 +01:00
Jonathan Leitschuh
2a01883177 Make threads daemon threads
Threads that aren't daemon threads can keep the JVM from shutting down.
I'm certain that this doesn't happen very often but if one of these
threads hangs it can cause the rest of the JVM to not shut down
when the main thread exits.
By making all threads daemon threads if the main thread terminates
the rest of these threads will shut down.
2017-05-01 20:34:28 -04:00
SquidDev
c190ec5147 Do not limit labels to the ASCII range.
This should accept all printable characters that ComputerCraft can
handle.
2017-05-02 00:20:46 +01:00
Lignum
6ff9db89cc Fix file handle leak 2017-05-02 00:44:33 +02:00
Lignum
2a1e110a65 Make the file descriptor limit configurable 2017-05-02 00:17:16 +02:00
SquidDev
d08b47db93 Preserve default values in configuration
Before we were setting the default as the previous value each time. Here
we store each property in a separate field, allowing us to access them
without setting a default.
2017-05-01 23:14:06 +01:00
Lignum
2d0690e625 Add file descriptor limit 2017-05-02 00:05:42 +02:00
SquidDev
876df68294 Rotate modem models 180 degrees
Or pi radians. Or tau/2 radians.

This ensures the main modem texture is facing towards the screen.
2017-05-01 22:39:18 +01:00
SquidDev
b1efbdad95 Impose additional limitations on disk and computer labels
Closes #147
2017-05-01 22:23:54 +01:00
SquidDev
230b578a98 Add config GUI
This allows you to modify various settings in-game.
2017-05-01 22:14:45 +01:00
SquidDev
02ce111d9e Invert side when checking connectivity
The side marks the direction relative to the wire, rather than the side
of the block it is attempting to connect to. Therefore needs to be
flipped.

Closes #149
2017-05-01 21:44:48 +01:00
Daniel Ratcliffe
1b562ae837 Merge pull request #159 from SquidDev-CC/feature/http-extensions
Various extensions to the HTTP API
2017-05-01 18:11:21 +01:00
SquidDev
ae04070915 Update documentation to include HTTP API changes 2017-05-01 18:05:04 +01:00
SquidDev
f2596a8547 Return string->string headers instead, joining fields with a comma. 2017-05-01 18:00:53 +01:00
Daniel Ratcliffe
6cd734a305 Merge pull request #160 from JLLeitschuh/patch-1
Add travis-ci build status badge to README
2017-05-01 17:54:27 +01:00
Jonathan Leitschuh
d4cb5f6f3f Add travis-ci build status badge to README 2017-05-01 12:50:15 -04:00
Daniel Ratcliffe
5775c77aa3 Merge pull request #157 from JLLeitschuh/feat/add-travis
Add travis.yml file to project
2017-05-01 17:38:47 +01:00
SquidDev
29952d5b4f Various extensions to the HTTP API
- A response is returned on the event of a HTTP error (such as 404).
 - Responses include the response headers.
2017-05-01 17:35:06 +01:00
SquidDev
b2542289f0 Require the player to be interacting with the computer when typing
Packets will be discarded if the sending player is not currently
interacting with the appropriate computer. This ensures players cannot
control other people's computers.

This is enforced by checking if the current container is a "computer
container", and this container holds the correct computer.
2017-05-01 17:07:32 +01:00
Jonathan Leitschuh
910ac37716 Add travis.yml file to project 2017-05-01 12:00:47 -04:00
Daniel Ratcliffe
ec7a251c09 Merge pull request #156 from SquidDev-CC/feature/fs-find-performance
Performance improvements to fs.find
2017-05-01 16:47:44 +01:00
Daniel Ratcliffe
92b319a05b Merge pull request #155 from JLLeitschuh/bug/make_gradlew_executable
Make gradlew executable by default
2017-05-01 16:46:37 +01:00
SquidDev
b3760f58e6 Performance improvements to fs.find
If the path includes no wildcards then it just checks it exists.
If it does, instead of scanning the entire tree, it works out the last
directory before the wildcard and starts scanning from there.

Closes #89
2017-05-01 16:45:41 +01:00
Jonathan Leitschuh
a74388c954 Make gradlew executable by default 2017-05-01 11:43:41 -04:00
Daniel Ratcliffe
5c6369b910 Merge pull request #154 from SquidDev-CC/hotfix/unborked-patches
Various fixes for 1.9.4
2017-05-01 16:31:14 +01:00
SquidDev
bbbbccf63d Fire all entity interaction events in TurtlePlaceCommand
This allows turtles to interact with entities correctly.
2017-05-01 16:14:05 +01:00
SquidDev
d050ca9849 Fix advanced computer's item model 2017-05-01 16:10:45 +01:00
SquidDev
77d225d1fe Listen to correct block update
We now listen to neighborChanged instead of onNeighborChange. This means
computers correctly detect redstone updates.

However, this leads to issues when moving turtles, so we defer the block
update until the turtle has finished moving.
2017-05-01 16:08:27 +01:00
SquidDev
9b5f4a877c Fix null bounding box being returned
Its usage is not always checked for null, so it is safer to return a
full block.
2017-05-01 16:04:42 +01:00
SquidDev
34cb75dfc3 Fix various tile entities not syncing correctly
This ensures the tile state is sent and received when it changes. This
fixes turtles facing the wrong direction and computers not turning on.
2017-05-01 16:04:36 +01:00
SquidDev
43d68db349 Add missing classes 2017-05-01 16:02:47 +01:00
Daniel Ratcliffe
b202b7b8a5 Converted tabs to spaces throughout 2017-05-01 15:48:44 +01:00
Daniel Ratcliffe
df01405583 codesize.sh now counts JSON too 2017-05-01 15:24:08 +01:00
978 changed files with 40316 additions and 22861 deletions

17
.editorconfig Normal file
View File

@@ -0,0 +1,17 @@
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
# Sadly too many files have whitespace errors, so we leave this as is for
# now and just make sure we don't introduce any more.
# trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.properties]
insert_final_newline = false

16
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,16 @@
---
name: Bug report
about: Report some misbehaviour in the mod
---
<!--
## Before reporting
- Search for the bug both here and [on the ComputerCraft issues page](https://github.com/dan200/ComputerCraft/issues?utf8=%E2%9C%93&q=is%3Aissue+)
- If possible, try to reproduce on vanilla ComputerCraft. If it still occurs, [report on the ComputerCraft repo](https://github.com/dan200/ComputerCraft/issues/new) instead.
-->
## Useful information to include:
- Minecraft version
- CC: Tweaked version
- Detailed reproduction steps!** Sometimes I can spot a bug pretty easily, but often it's much more obscure. Anything you can give which will help reproduce it means it'll get fixed quicker.

View File

@@ -0,0 +1,15 @@
---
name: Feature request
about: Suggest an idea or improvement
---
<!--
## Before reporting
- Search for the suggestion both here and [on the ComputerCraft issues page](https://github.com/dan200/ComputerCraft/issues?utf8=%E2%9C%93&q=is%3Aissue+). It's possible someone's suggested it before!
- Unless something is specific to CC:Tweaked, try to [suggest them on the ComputerCraft repo](https://github.com/dan200/ComputerCraft/issues/new). There's a lot more people watching it, so it allows the wider community to contribute.
-->
## Useful information to include:
- Explanation of how the feature/change chould work.
- Some rationale/use case for a feature. I'd like to keep CC:T as minimal

9
.github/pull_request_template.md vendored Normal file
View File

@@ -0,0 +1,9 @@
<!--
Unless this feature is specific to CC:Tweaked, try to [target the original ComputerCraft repo](https://github.com/dan200/ComputerCraft/) instead. There's a lot more people watching it, so it allows the wider community to contribute.
-->
## Useful information to include:
- Brief explanation of the changes you've made.
- Rationale of why this change has been made/reasoning behind it.
The more information you can provide, the easier it is to review something now _and_ to see why a change was made, when the code needs updating in the future.

2
.gitignore vendored
View File

@@ -5,6 +5,8 @@ deploy
*.ipr
*.iws
*.iml
.idea
.gradle
luaj-2.0.3/lib
luaj-2.0.3/*.jar
*.DS_Store

14
.travis.yml Normal file
View File

@@ -0,0 +1,14 @@
language: java
script: ./gradlew build --no-daemon
before_cache:
- rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
- rm -fr $HOME/.gradle/caches/*/plugin-resolution/
cache:
directories:
- $HOME/.gradle/caches/
- $HOME/.gradle/wrapper/s
jdk:
- oraclejdk8

View File

@@ -36,7 +36,7 @@ This mod is provided 'as is' with no warranties, implied or otherwise. The owner
of this mod takes no responsibility for any damages incurred from the use of
this mod. This mod alters fundamental parts of the Minecraft game, parts of
Minecraft may not work with this mod installed. All damages caused from the use
or misuse of this mad fall on the user.
or misuse of this mod fall on the user.
3. Play rights
--------------

View File

@@ -1,25 +1,49 @@
ComputerCraft
=============
# ![CC: Tweaked](logo.png)
[![Build Status](https://travis-ci.org/SquidDev-CC/CC-Tweaked.svg?branch=master)](https://travis-ci.org/SquidDev-CC/CC-Tweaked)
ComputerCraft is a Minecraft modification which adds programmable Robots and Computers to the world of Minecraft.
If you're not familiar with ComputerCraft, visit the [Website](http://www.computercraft.info/download) or the [Wiki](http://www.computercraft.info/wiki) to find out more.
CC: Tweaked is a fork of ComputerCraft which aims to provide earlier access to the more experimental and in-development
features of the mod. For a more stable experience, I recommend checking out the
[original mod](https://github.com/dan200/ComputerCraft).
About this Repository
=====================
## What?
CC: Tweaked (or CC:T for short) does not aim to create a competing fork of ComputerCraft, nor am I planning to take it
in in a vastly different direction to the original mod. In fact, CC:T aims to be a nurturing ground for various
features, with a pull request against the original mod being the end goal.
ComputerCraft was originally released in late 2011 by [Daniel Ratcliffe](https://twitter.com/DanTwoHundred). In early 2017, after working on the mod solo for five years, it was decided to release the source code publicly to allow Dan to devote time to other projects. This repository marks the first public release of this source code.
CC:T also includes many pull requests from the community which have not yet been merged, offering a large number
of additional bug fixes and features over the original mod.
The code in this repository will always represent the "bleeding edge" of the ComputerCraft codebase, but stable builds back to 1.79 will be marked on the [Releases](https://github.com/dan200/ComputerCraft/releases) page.
## Features
CC: Tweaked contains the all features of the latest alpha, as well as numerous fixes, performance improvements and
several additional features. I'd recommend checking out [the releases page](https://github.com/SquidDev-CC/CC-Tweaked/releases)
to see the full changes, but here's a couple of the more interesting changes:
Contributing
============
- Replace LuaJ with Cobalt.
- Allow running multiple computers at the same time.
- Websocket support in the HTTP library.
- Wired modems and cables act more like multiparts.
- Add map-like rendering for pocket computers and printed pages/books.
- Adds the `/computercraft` command, offering various diagnostic tools for server owners. This allows operators to
track which computers are hogging resources, turn on and shutdown multiple computers at once and interact with
computers remotely.
- Add full-block wired modems, allowing one to wrap non-solid peripherals (such as turtles, or chests if Plethora is
installed).
- Extended binary file handles. They support file seeking, and reading new lines, allowing full (and accurate)
emulation of the standard Lua `io` library.
While ComputerCraft will no longer be actively developed by Daniel Ratcliffe, you may still contribute pull requests which will be reviewed and incorporated into releases periodically. A pull requests is more likely to be accepted if it meets the following criteria:
## Relation to CCTweaks?
This mod has nothing to do with CCTweaks, though there is no denying the name is a throwback to it. That being said,
several features have been included, such as full block modems, the Cobalt runtime and map-like rendering for pocket
computers.
* It does not add any new dependencies for compiling, running or using the mod.
* It does not break compatibility with world saves or programs created with previous versions of the mod.
* It does not add unneccessary complexity for users of the mod, and maintains the accessibility for which the mod is known.
* It does not add unneccessary complexity or stylistic changes to the code, especially where functionality is not being changed.
* It does not create bugs!
## Contributing
Any contribution is welcome, be that using the mod, reporting bugs or contributing code. If you do wish to contribute
code, do consider submitting it to the ComputerCraft repository first.
The pull requests most likely to be accepted are those which fix bugs, simplify code, or make the mod compatible with newer versions of Minecraft.
That being said, in order to start helping develop CC:T, you'll need to follow these steps:
- **Clone the repository:** `git clone https://github.com/SquidDev-CC/CC-Tweaked.git && cd CC-Tweaked`
- **Setup Forge:** `./gradlew setupDecompWorkspace`
- **Test your changes:** `./gradlew runClient` (or run the `GradleStart` class from your IDE).
If you want to run CC:T in a normal Minecraft instance, run `./gradlew build` and copy the `.jar` from `build/libs`.

View File

@@ -9,77 +9,190 @@ buildscript {
}
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:2.2-SNAPSHOT'
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
classpath 'org.ajoberstar:gradle-git:1.6.0'
}
}
apply plugin: 'net.minecraftforge.gradle.forge'
/*
// for people who want stable - not yet functional for MC 1.8.8 - we require the forgegradle 2.1 snapshot
plugins {
id "net.minecraftforge.gradle.forge" version "2.0.2"
id 'com.matthewprenger.cursegradle' version '1.0.10'
}
*/
version = "1.80pr0"
group = "dan200.computercraft"
archivesBaseName = "ComputerCraft"
apply plugin: 'net.minecraftforge.gradle.forge'
apply plugin: 'org.ajoberstar.grgit'
apply plugin: 'maven-publish'
apply plugin: 'maven'
version = "1.80pr1.9"
group = "org.squiddev"
archivesBaseName = "cc-tweaked"
minecraft {
version = "1.9.4-12.17.0.1959"
version = "1.12.2-14.23.4.2749"
runDir = "run"
replace '${version}', project.version
// the mappings can be changed at any time, and must be in the following format.
// snapshot_YYYYMMDD snapshot are built nightly.
// stable_# stables are built at the discretion of the MCP team.
// Use non-default mappings at your own risk. they may not allways work.
// simply re-run your setup task after changing the mappings to update your workspace.
mappings = "snapshot_20160518"
mappings = "snapshot_20180724"
// makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable.
}
dependencies {
// you may put jars on which you depend on in ./libs
// or you may define them like so..
//compile "some.group:artifact:version:classifier"
//compile "some.group:artifact:version"
// real examples
//compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env
//compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env
// the 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime.
//provided 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// the deobf configurations: 'deobfCompile' and 'deobfProvided' are the same as the normal compile and provided,
// except that these dependencies get remapped to your current MCP mappings
//deobfCompile 'com.mod-buildcraft:buildcraft:6.0.8:dev'
//deobfProvided 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// for more info...
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
repositories {
maven {
name = "JEI"
url = "http://dvs1.progwml6.com/files/maven"
}
maven {
name = "squiddev"
url = "https://dl.bintray.com/squiddev/maven"
}
ivy { artifactPattern "https://asie.pl/files/mods/Charset/LibOnly/[module]-[revision](-[classifier]).[ext]" }
}
processResources
{
// this will ensure that this task is redone when the versions change.
configurations {
shade
compile.extendsFrom shade
deployerJars
}
dependencies {
deobfProvided "mezz.jei:jei_1.12.2:4.8.5.159:api"
deobfProvided "pl.asie:Charset-Lib:0.5.4.6"
runtime "mezz.jei:jei_1.12.2:4.8.5.159"
shade 'org.squiddev:Cobalt:0.3.2'
testCompile 'junit:junit:4.11'
deployerJars "org.apache.maven.wagon:wagon-ssh:3.0.0"
}
javadoc {
include "dan200/computercraft/api/**/*.java"
}
jar {
dependsOn javadoc
manifest {
attributes('FMLAT': 'computercraft_at.cfg')
}
into("docs", { from (javadoc.destinationDir) })
into("api", { from (sourceSets.main.allSource) {
include "dan200/computercraft/api/**/*.java"
}})
from configurations.shade.collect { it.isDirectory() ? it : zipTree(it) }
}
import org.ajoberstar.grgit.Grgit
processResources {
inputs.property "version", project.version
inputs.property "mcversion", project.minecraft.version
// replace stuff in mcmod.info, nothing else
def grgit = Grgit.open(dir: '.')
inputs.property "commithash", grgit.head().id
def blacklist = ['GitHub', 'dan200', 'Daniel Ratcliffe']
Set<String> contributors = []
grgit.log().each {
if (!blacklist.contains(it.author.name)) contributors.add(it.author.name)
if (!blacklist.contains(it.committer.name)) contributors.add(it.committer.name)
}
from(sourceSets.main.resources.srcDirs) {
include 'mcmod.info'
// replace version and mcversion
expand 'version':project.version, 'mcversion':project.minecraft.version
include 'assets/computercraft/lua/rom/help/credits.txt'
expand 'version':project.version,
'mcversion':project.minecraft.version,
'gitcontributors':contributors.sort(false, String.CASE_INSENSITIVE_ORDER).join('\n')
}
// copy everything else, thats not the mcmod.info
from(sourceSets.main.resources.srcDirs) {
exclude 'mcmod.info'
exclude 'assets/computercraft/lua/rom/help/credits.txt'
}
}
curseforge {
apiKey = project.hasProperty('curseForgeApiKey') ? project.curseForgeApiKey : ''
project {
id = '282001'
releaseType = 'beta'
changelog = "Release notes can be found on the GitHub repository (https://github.com/SquidDev-CC/CC-Tweaked/releases/tag/v${project.version})."
}
}
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
artifact sourceJar
}
}
}
uploadArchives {
repositories {
if(project.hasProperty('mavenUploadUrl')) {
mavenDeployer {
configuration = configurations.deployerJars
repository(url: project.property('mavenUploadUrl')) {
authentication(
userName: project.property('mavenUploadUser'),
privateKey: project.property('mavenUploadKey'))
}
pom.project {
name 'CC: Tweaked'
packaging 'jar'
description 'A fork of ComputerCraft which aims to provide earlier access to the more experimental and in-development features of the mod.'
url 'https://github.com/SquidDev-CC/CC-Tweaked'
scm {
url 'https://github.com/dan200/ComputerCraft.git'
}
issueManagement {
system 'github'
url 'https://github.com/dan200/ComputerCraft/issues'
}
licenses {
license {
name 'ComputerCraft Public License, Version 1.0'
url 'https://github.com/dan200/ComputerCraft/blob/master/LICENSE'
distribution 'repo'
}
}
}
pom.whenConfigured { pom ->
pom.dependencies.clear()
}
}
}
}
}
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint"
}
}
runClient.outputs.upToDateWhen { false }
runServer.outputs.upToDateWhen { false }

View File

@@ -3,4 +3,8 @@ echo "Java code:"
cat `find src | grep \\.java$` | wc
echo "Lua code:"
cat `find src/main/resources/assets/computercraft/lua` | wc
cat `find src/main/resources/assets/computercraft/lua | grep \\.lua$` | wc
echo "JSON:"
cat `find src/main/resources/assets/computercraft | grep \\.json$` | wc

25
deploy.sh Normal file → Executable file
View File

@@ -18,29 +18,4 @@ OUTPUTJAR=`ls -1 build/libs | grep -v sources | sed s/\-//g`
FRIENDLYNAME=`ls -1 build/libs | grep -v sources | sed s/\-/\ /g | sed s/\.jar//g`
cp build/libs/$INPUTJAR deploy/$OUTPUTJAR
echo "Creating API..."
mkdir -p deploy/api/src/dan200/computercraft
cp -r build/sources/main/java/dan200/computercraft/api deploy/api/src/dan200/computercraft/api
echo "Creating API Javadocs..."
mkdir -p deploy/api/doc
cd src/main/java/dan200/computercraft/api
find . -type f -name "*.java" | xargs javadoc -d ../../../../../../deploy/api/doc -windowtitle "$FRIENDLYNAME"
cd ../../../../../..
echo "Adding API and Javadocs to deployment..."
cd deploy
zip -r $OUTPUTJAR api/doc > /dev/null
zip -r $OUTPUTJAR api/src/dan200/computercraft > /dev/null
cd ..
rm -rf deploy/api
echo "Adding LuaJ to deployment..."
mkdir deploy/luaj
cd deploy/luaj
jar xf ../../libs/luaj-jse-2.0.3.jar
zip -r ../$OUTPUTJAR org > /dev/null
cd ../..
rm -rf deploy/luaj
echo "Done."

Binary file not shown.

View File

@@ -1,6 +1,5 @@
#Mon Sep 14 12:28:28 PDT 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.7-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.3-bin.zip

110
gradlew vendored Normal file → Executable file
View File

@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/usr/bin/env sh
##############################################################################
##
@@ -6,47 +6,6 @@
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS="-Xmx2048m"
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
@@ -61,9 +20,49 @@ while [ -h "$PRG" ] ; do
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@@ -90,7 +89,7 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
@@ -114,6 +113,7 @@ fi
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
@@ -154,11 +154,19 @@ if $cygwin ; then
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
APP_ARGS=$(save "$@")
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
gradlew.bat vendored Normal file
View File

@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

Binary file not shown.

BIN
logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

View File

@@ -0,0 +1,181 @@
/*******************************************************************************
* Copyright (c) 2012 Luaj.org. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.vm2.lib;
import org.luaj.vm2.LuaInteger;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
/**
* Subclass of LibFunction that implements the Lua standard {@code bit32} library.
*/
public class Bit32Lib extends ZeroArgFunction
{
public LuaValue call( )
{
LuaTable t = new LuaTable();
bind( t, Bit32LibV.class, new String[] {
"band", "bnot", "bor", "btest", "bxor", "extract", "replace"
} );
bind( t, Bit32Lib2.class, new String[] {
"arshift", "lrotate", "lshift", "rrotate", "rshift"
} );
env.set( "bit32", t );
return t;
}
public static final class Bit32LibV extends VarArgFunction
{
public Varargs invoke( Varargs args )
{
switch( opcode )
{
case 0: // band
{
int result = -1;
for( int i = 1; i <= args.narg(); i++ )
{
result &= args.checkint( i );
}
return bitsToValue( result );
}
case 1: // bnot
return bitsToValue( ~args.checkint( 1 ) );
case 2: // bot
{
int result = 0;
for( int i = 1; i <= args.narg(); i++ )
{
result |= args.checkint( i );
}
return bitsToValue( result );
}
case 3: // btest
{
int bits = -1;
for( int i = 1; i <= args.narg(); i++ )
{
bits &= args.checkint( i );
}
return valueOf( bits != 0 );
}
case 4: // bxor
{
int result = 0;
for( int i = 1; i <= args.narg(); i++ )
{
result ^= args.checkint( i );
}
return bitsToValue( result );
}
case 5: // extract
{
int field = args.checkint( 2 );
int width = args.optint( 3, 1 );
if( field < 0 ) argerror( 2, "field cannot be negative" );
if( width <= 0 ) argerror( 3, "width must be postive" );
if( field + width > 32 ) error( "trying to access non-existent bits" );
return bitsToValue( (args.checkint( 1 ) >>> field) & (-1 >>> (32 - width)) );
}
case 6: // replace
{
int n = args.checkint( 1 );
int v = args.checkint( 2 );
int field = args.checkint( 3 );
int width = args.optint( 4, 1 );
if( field < 0 ) argerror( 3, "field cannot be negative" );
if( width <= 0 ) argerror( 4, "width must be postive" );
if( field + width > 32 ) error( "trying to access non-existent bits" );
int mask = (-1 >>> (32 - width)) << field;
n = (n & ~mask) | ((v << field) & mask);
return bitsToValue( n );
}
}
return NIL;
}
}
public static final class Bit32Lib2 extends TwoArgFunction
{
public LuaValue call( LuaValue arg1, LuaValue arg2 )
{
switch( opcode )
{
case 0: // arshift
{
int x = arg1.checkint();
int disp = arg2.checkint();
return disp >= 0 ? bitsToValue( x >> disp ) : bitsToValue( x << -disp );
}
case 1: // lrotate
return rotate( arg1.checkint(), arg2.checkint() );
case 2: // lshift
return shift( arg1.checkint(), arg2.checkint() );
case 3: // rrotate
return rotate( arg1.checkint(), -arg2.checkint() );
case 4: // rshift
return shift( arg1.checkint(), -arg2.checkint() );
}
return NIL;
}
}
static LuaValue rotate( int x, int disp )
{
if( disp < 0 )
{
disp = -disp & 31;
return bitsToValue( (x >>> disp) | (x << (32 - disp)) );
}
else
{
disp = disp & 31;
return bitsToValue( (x << disp) | (x >>> (32 - disp)) );
}
}
static LuaValue shift( int x, int disp )
{
if( disp >= 32 || disp <= -32 )
{
return ZERO;
}
else if( disp >= 0 )
{
return bitsToValue( x << disp );
}
else
{
return bitsToValue( x >>> -disp );
}
}
private static LuaValue bitsToValue( int x )
{
return x < 0 ? LuaValue.valueOf( (long) x & 0xFFFFFFFFL ) : LuaInteger.valueOf( x );
}
}

1
settings.gradle Normal file
View File

@@ -0,0 +1 @@
rootProject.name = 'cc-tweaked'

7
setup.bat Normal file
View File

@@ -0,0 +1,7 @@
echo "Setting up IntelliJ development environment with gradle..."
rmdir /s /q .\build
call gradlew.bat --stacktrace setupDecompWorkspace --refresh-dependencies
call gradlew.bat --stacktrace cleanIdea idea
echo "Done."
pause

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-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. 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.
*/
@@ -8,15 +8,26 @@ package dan200.computercraft.api;
import dan200.computercraft.api.filesystem.IMount;
import dan200.computercraft.api.filesystem.IWritableMount;
import dan200.computercraft.api.lua.ILuaAPIFactory;
import dan200.computercraft.api.media.IMedia;
import dan200.computercraft.api.media.IMediaProvider;
import dan200.computercraft.api.network.IPacketNetwork;
import dan200.computercraft.api.network.wired.IWiredElement;
import dan200.computercraft.api.network.wired.IWiredNode;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.api.peripheral.IPeripheralProvider;
import dan200.computercraft.api.permissions.ITurtlePermissionProvider;
import dan200.computercraft.api.pocket.IPocketUpgrade;
import dan200.computercraft.api.redstone.IBundledRedstoneProvider;
import dan200.computercraft.api.turtle.ITurtleUpgrade;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.Method;
/**
@@ -32,6 +43,7 @@ public final class ComputerCraftAPI
return computerCraft != null;
}
@Nonnull
public static String getInstalledVersion()
{
findCC();
@@ -46,116 +58,134 @@ public final class ComputerCraftAPI
return "";
}
@Nonnull
public static String getAPIVersion()
{
return "${version}";
}
/**
* Creates a numbered directory in a subfolder of the save directory for a given world, and returns that number.<br>
* Use in conjuction with createSaveDirMount() to create a unique place for your peripherals or media items to store files.<br>
* @param world The world for which the save dir should be created. This should be the serverside world object.
* @param parentSubPath The folder path within the save directory where the new directory should be created. eg: "computercraft/disk"
* @return The numerical value of the name of the new folder, or -1 if the folder could not be created for some reason.<br>
* eg: if createUniqueNumberedSaveDir( world, "computer/disk" ) was called returns 42, then "computer/disk/42" is now available for writing.
* @see #createSaveDirMount(World, String, long)
*/
public static int createUniqueNumberedSaveDir( World world, String parentSubPath )
{
findCC();
if( computerCraft_createUniqueNumberedSaveDir != null )
{
try {
return (Integer)computerCraft_createUniqueNumberedSaveDir.invoke( null, world, parentSubPath );
} catch (Exception e) {
// It failed
}
}
return -1;
}
/**
* Creates a file system mount that maps to a subfolder of the save directory for a given world, and returns it.<br>
* Use in conjuction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a folder from the
* users save directory onto a computers file system.<br>
* @param world The world for which the save dir can be found. This should be the serverside world object.
* @param subPath The folder path within the save directory that the mount should map to. eg: "computer/disk/42".<br>
* Use createUniqueNumberedSaveDir() to create a new numbered folder to use.
* @param capacity The ammount of data that can be stored in the directory before it fills up, in bytes.
* @return The mount, or null if it could be created for some reason. Use IComputerAccess.mount() or IComputerAccess.mountWritable()
* to mount this on a Computers' file system.
* @see #createUniqueNumberedSaveDir(World, String)
* @see dan200.computercraft.api.peripheral.IComputerAccess#mount(String, dan200.computercraft.api.filesystem.IMount)
* @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, dan200.computercraft.api.filesystem.IWritableMount)
* @see dan200.computercraft.api.filesystem.IMount
* @see IWritableMount
*/
public static IWritableMount createSaveDirMount( World world, String subPath, long capacity )
{
findCC();
if( computerCraft_createSaveDirMount != null )
{
try {
return (IWritableMount)computerCraft_createSaveDirMount.invoke( null, world, subPath, capacity );
} catch (Exception e){
// It failed
}
}
return null;
}
/**
* Creates a file system mount to a resource folder, and returns it.<br>
* Use in conjuction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a resource folder onto a computers file system.<br>
* The files in this mount will be a combination of files in the specified mod jar, and resource packs that contain resources with the same domain and path.<br>
* @param modClass A class in whose jar to look first for the resources to mount. Using your main mod class is recommended. eg: MyMod.class
* @param domain The domain under which to look for resources. eg: "mymod"
* @param subPath The domain under which to look for resources. eg: "mymod/lua/myfiles"
* @return The mount, or null if it could be created for some reason. Use IComputerAccess.mount() or IComputerAccess.mountWritable()
* to mount this on a Computers' file system.
* @see dan200.computercraft.api.peripheral.IComputerAccess#mount(String, dan200.computercraft.api.filesystem.IMount)
* @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, IWritableMount)
* @see dan200.computercraft.api.filesystem.IMount
*/
public static IMount createResourceMount( Class modClass, String domain, String subPath )
{
findCC();
if( computerCraft_createResourceMount != null )
{
try {
return (IMount)computerCraft_createResourceMount.invoke( null, modClass, domain, subPath );
} catch (Exception e){
// It failed
}
}
return null;
}
/**
* Registers a peripheral handler to convert blocks into IPeripheral implementations.
* @see dan200.computercraft.api.peripheral.IPeripheral
* @see dan200.computercraft.api.peripheral.IPeripheralProvider
*/
public static void registerPeripheralProvider( IPeripheralProvider handler )
{
findCC();
if ( computerCraft_registerPeripheralProvider != null)
{
try {
computerCraft_registerPeripheralProvider.invoke( null, handler );
} catch (Exception e){
// It failed
}
}
}
/**
* Creates a numbered directory in a subfolder of the save directory for a given world, and returns that number.
*
* Use in conjunction with createSaveDirMount() to create a unique place for your peripherals or media items to store files.
*
* @param world The world for which the save dir should be created. This should be the server side world object.
* @param parentSubPath The folder path within the save directory where the new directory should be created. eg: "computercraft/disk"
* @return The numerical value of the name of the new folder, or -1 if the folder could not be created for some reason.
*
* eg: if createUniqueNumberedSaveDir( world, "computer/disk" ) was called returns 42, then "computer/disk/42" is now
* available for writing.
* @see #createSaveDirMount(World, String, long)
*/
public static int createUniqueNumberedSaveDir( @Nonnull World world, @Nonnull String parentSubPath )
{
findCC();
if( computerCraft_createUniqueNumberedSaveDir != null )
{
try {
return (Integer)computerCraft_createUniqueNumberedSaveDir.invoke( null, world, parentSubPath );
} catch (Exception e) {
// It failed
}
}
return -1;
}
/**
* Creates a file system mount that maps to a subfolder of the save directory for a given world, and returns it.
*
* Use in conjunction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a folder from the
* users save directory onto a computers file system.
*
* @param world The world for which the save dir can be found. This should be the server side world object.
* @param subPath The folder path within the save directory that the mount should map to. eg: "computer/disk/42".
* Use createUniqueNumberedSaveDir() to create a new numbered folder to use.
* @param capacity The amount of data that can be stored in the directory before it fills up, in bytes.
* @return The mount, or null if it could be created for some reason. Use IComputerAccess.mount() or IComputerAccess.mountWritable()
* to mount this on a Computers' file system.
* @see #createUniqueNumberedSaveDir(World, String)
* @see IComputerAccess#mount(String, IMount)
* @see IComputerAccess#mountWritable(String, IWritableMount)
* @see IMount
* @see IWritableMount
*/
@Nullable
public static IWritableMount createSaveDirMount( @Nonnull World world, @Nonnull String subPath, long capacity )
{
findCC();
if( computerCraft_createSaveDirMount != null )
{
try {
return (IWritableMount)computerCraft_createSaveDirMount.invoke( null, world, subPath, capacity );
} catch (Exception e){
// It failed
}
}
return null;
}
/**
* Creates a file system mount to a resource folder, and returns it.
*
* Use in conjunction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a resource folder
* onto a computer's file system.
*
* The files in this mount will be a combination of files in the specified mod jar, and resource packs that contain
* resources with the same domain and path.
*
* @param modClass A class in whose jar to look first for the resources to mount. Using your main mod class is recommended. eg: MyMod.class
* @param domain The domain under which to look for resources. eg: "mymod".
* @param subPath The domain under which to look for resources. eg: "mymod/lua/myfiles".
* @return The mount, or {@code null} if it could be created for some reason. Use IComputerAccess.mount() or
* IComputerAccess.mountWritable() to mount this on a Computers' file system.
* @see IComputerAccess#mount(String, IMount)
* @see IComputerAccess#mountWritable(String, IWritableMount)
* @see IMount
*/
@Nullable
public static IMount createResourceMount( @Nonnull Class<?> modClass, @Nonnull String domain, @Nonnull String subPath )
{
findCC();
if( computerCraft_createResourceMount != null )
{
try {
return (IMount)computerCraft_createResourceMount.invoke( null, modClass, domain, subPath );
} catch (Exception e){
// It failed
}
}
return null;
}
/**
* Registers a peripheral handler to convert blocks into {@link IPeripheral} implementations.
*
* @param handler The peripheral provider to register.
* @see dan200.computercraft.api.peripheral.IPeripheral
* @see dan200.computercraft.api.peripheral.IPeripheralProvider
*/
public static void registerPeripheralProvider( @Nonnull IPeripheralProvider handler )
{
findCC();
if ( computerCraft_registerPeripheralProvider != null)
{
try {
computerCraft_registerPeripheralProvider.invoke( null, handler );
} catch (Exception e){
// It failed
}
}
}
/**
* Registers a new turtle turtle for use in ComputerCraft. After calling this,
* users should be able to craft Turtles with your new turtle. It is recommended to call
* this during the load() method of your mod.
*
* @param upgrade The turtle upgrade to register.
* @see dan200.computercraft.api.turtle.ITurtleUpgrade
*/
public static void registerTurtleUpgrade( ITurtleUpgrade upgrade )
public static void registerTurtleUpgrade( @Nonnull ITurtleUpgrade upgrade )
{
if( upgrade != null )
{
@@ -172,10 +202,12 @@ public final class ComputerCraftAPI
}
/**
* Registers a bundled redstone handler to provide bundled redstone output for blocks
* Registers a bundled redstone handler to provide bundled redstone output for blocks.
*
* @param handler The bundled redstone provider to register.
* @see dan200.computercraft.api.redstone.IBundledRedstoneProvider
*/
public static void registerBundledRedstoneProvider( IBundledRedstoneProvider handler )
public static void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider handler )
{
findCC();
if( computerCraft_registerBundledRedstoneProvider != null )
@@ -190,11 +222,15 @@ public final class ComputerCraftAPI
/**
* If there is a Computer or Turtle at a certain position in the world, get it's bundled redstone output.
* @see dan200.computercraft.api.redstone.IBundledRedstoneProvider
*
* @param world The world this block is in.
* @param pos The position this block is at.
* @param side The side to extract the bundled redstone output from.
* @return If there is a block capable of emitting bundled redstone at the location, it's signal (0-65535) will be returned.
* If there is no block capable of emitting bundled redstone at the location, -1 will be returned.
* @see dan200.computercraft.api.redstone.IBundledRedstoneProvider
*/
public static int getBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side )
public static int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull EnumFacing side )
{
findCC();
if( computerCraft_getDefaultBundledRedstoneOutput != null )
@@ -209,10 +245,12 @@ public final class ComputerCraftAPI
}
/**
* Registers a media handler to provide IMedia implementations for Items
* Registers a media handler to provide {@link IMedia} implementations for Items
*
* @param handler The media provider to register.
* @see dan200.computercraft.api.media.IMediaProvider
*/
public static void registerMediaProvider( IMediaProvider handler )
public static void registerMediaProvider( @Nonnull IMediaProvider handler )
{
findCC();
if( computerCraft_registerMediaProvider != null )
@@ -226,10 +264,12 @@ public final class ComputerCraftAPI
}
/**
* Registers a permission handler to restrict where turtles can move or build
* Registers a permission handler to restrict where turtles can move or build.
*
* @param handler The turtle permission provider to register.
* @see dan200.computercraft.api.permissions.ITurtlePermissionProvider
*/
public static void registerPermissionProvider( ITurtlePermissionProvider handler )
public static void registerPermissionProvider( @Nonnull ITurtlePermissionProvider handler )
{
findCC();
if( computerCraft_registerPermissionProvider != null )
@@ -242,76 +282,199 @@ public final class ComputerCraftAPI
}
}
public static void registerPocketUpgrade( @Nonnull IPocketUpgrade upgrade )
{
findCC();
if(computerCraft_registerPocketUpgrade != null) {
try {
computerCraft_registerPocketUpgrade.invoke( null, upgrade );
} catch (Exception e) {
// It failed
}
}
}
/**
* Attempt to get the game-wide wireless network.
*
* @return The global wireless network, or {@code null} if it could not be fetched.
*/
public static IPacketNetwork getWirelessNetwork()
{
findCC();
if( computerCraft_getWirelessNetwork != null )
{
try
{
return (IPacketNetwork) computerCraft_getWirelessNetwork.invoke( null );
} catch (Exception e) {
// It failed;
}
}
return null;
}
public static void registerAPIFactory( @Nonnull ILuaAPIFactory upgrade )
{
findCC();
if( computerCraft_registerAPIFactory != null )
{
try
{
computerCraft_registerAPIFactory.invoke( null, upgrade );
}
catch( Exception e )
{
// It failed
}
}
}
/**
* Construct a new wired node for a given wired element
*
* @param element The element to construct it for
* @return The element's node
* @see IWiredElement#getNode()
*/
@Nonnull
public static IWiredNode createWiredNodeForElement( @Nonnull IWiredElement element )
{
findCC();
if( computerCraft_createWiredNodeForElement != null )
{
try
{
return (IWiredNode) computerCraft_createWiredNodeForElement.invoke( null, element );
}
catch( ReflectiveOperationException e )
{
throw new IllegalStateException( "Error creating wired node", e );
}
}
else
{
throw new IllegalStateException( "ComputerCraft cannot be found" );
}
}
/**
* Get the wired network element for a block in world
*
* @param world The world the block exists in
* @param pos The position the block exists in
* @param side The side to extract the network element from
* @return The element's node
* @see IWiredElement#getNode()
*/
@Nullable
public static IWiredElement getWiredElementAt( @Nonnull IBlockAccess world, @Nonnull BlockPos pos, @Nonnull EnumFacing side )
{
findCC();
if( computerCraft_getWiredElementAt != null )
{
try
{
return (IWiredElement) computerCraft_getWiredElementAt.invoke( null, world, pos, side );
}
catch( ReflectiveOperationException ignored )
{
}
}
return null;
}
// The functions below here are private, and are used to interface with the non-API ComputerCraft classes.
// Reflection is used here so you can develop your mod without decompiling ComputerCraft and including
// it in your solution, and so your mod won't crash if ComputerCraft is installed.
private static void findCC()
{
if( !ccSearched ) {
try {
computerCraft = Class.forName( "dan200.computercraft.ComputerCraft" );
computerCraft_getVersion = findCCMethod( "getVersion", new Class[]{
// Reflection is used here so you can develop your mod without decompiling ComputerCraft and including
// it in your solution, and so your mod won't crash if ComputerCraft is installed.
private static void findCC()
{
if( !ccSearched ) {
try {
computerCraft = Class.forName( "dan200.computercraft.ComputerCraft" );
computerCraft_getVersion = findCCMethod( "getVersion", new Class<?>[]{
} );
computerCraft_createUniqueNumberedSaveDir = findCCMethod( "createUniqueNumberedSaveDir", new Class[]{
computerCraft_createUniqueNumberedSaveDir = findCCMethod( "createUniqueNumberedSaveDir", new Class<?>[]{
World.class, String.class
} );
computerCraft_createSaveDirMount = findCCMethod( "createSaveDirMount", new Class[] {
World.class, String.class, Long.TYPE
} );
computerCraft_createResourceMount = findCCMethod( "createResourceMount", new Class[] {
Class.class, String.class, String.class
} );
computerCraft_registerPeripheralProvider = findCCMethod( "registerPeripheralProvider", new Class[] {
IPeripheralProvider.class
} );
computerCraft_registerTurtleUpgrade = findCCMethod( "registerTurtleUpgrade", new Class[] {
computerCraft_createSaveDirMount = findCCMethod( "createSaveDirMount", new Class<?>[] {
World.class, String.class, Long.TYPE
} );
computerCraft_createResourceMount = findCCMethod( "createResourceMount", new Class<?>[] {
Class.class, String.class, String.class
} );
computerCraft_registerPeripheralProvider = findCCMethod( "registerPeripheralProvider", new Class<?>[] {
IPeripheralProvider.class
} );
computerCraft_registerTurtleUpgrade = findCCMethod( "registerTurtleUpgrade", new Class<?>[] {
ITurtleUpgrade.class
} );
computerCraft_registerBundledRedstoneProvider = findCCMethod( "registerBundledRedstoneProvider", new Class[] {
computerCraft_registerBundledRedstoneProvider = findCCMethod( "registerBundledRedstoneProvider", new Class<?>[] {
IBundledRedstoneProvider.class
} );
computerCraft_getDefaultBundledRedstoneOutput = findCCMethod( "getDefaultBundledRedstoneOutput", new Class[] {
computerCraft_getDefaultBundledRedstoneOutput = findCCMethod( "getDefaultBundledRedstoneOutput", new Class<?>[] {
World.class, BlockPos.class, EnumFacing.class
} );
computerCraft_registerMediaProvider = findCCMethod( "registerMediaProvider", new Class[] {
computerCraft_registerMediaProvider = findCCMethod( "registerMediaProvider", new Class<?>[] {
IMediaProvider.class
} );
computerCraft_registerPermissionProvider = findCCMethod( "registerPermissionProvider", new Class[] {
computerCraft_registerPermissionProvider = findCCMethod( "registerPermissionProvider", new Class<?>[] {
ITurtlePermissionProvider.class
} );
} catch( Exception e ) {
System.out.println( "ComputerCraftAPI: ComputerCraft not found." );
} finally {
ccSearched = true;
}
}
}
computerCraft_registerPocketUpgrade = findCCMethod( "registerPocketUpgrade", new Class<?>[] {
IPocketUpgrade.class
} );
computerCraft_getWirelessNetwork = findCCMethod( "getWirelessNetwork", new Class<?>[] {
} );
computerCraft_registerAPIFactory = findCCMethod( "registerAPIFactory", new Class<?>[] {
ILuaAPIFactory.class
} );
computerCraft_createWiredNodeForElement = findCCMethod( "createWiredNodeForElement", new Class<?>[] {
IWiredElement.class
} );
computerCraft_getWiredElementAt = findCCMethod( "getWiredElementAt", new Class<?>[]{
IBlockAccess.class, BlockPos.class, EnumFacing.class
} );
} catch( Exception e ) {
System.out.println( "ComputerCraftAPI: ComputerCraft not found." );
} finally {
ccSearched = true;
}
}
}
private static Method findCCMethod( String name, Class[] args )
{
try {
private static Method findCCMethod( String name, Class<?>[] args )
{
try {
if( computerCraft != null )
{
return computerCraft.getMethod( name, args );
return computerCraft.getMethod( name, args );
}
return null;
} catch( NoSuchMethodException e ) {
System.out.println( "ComputerCraftAPI: ComputerCraft method " + name + " not found." );
return null;
}
}
private static boolean ccSearched = false;
private static Class computerCraft = null;
} catch( NoSuchMethodException e ) {
System.out.println( "ComputerCraftAPI: ComputerCraft method " + name + " not found." );
return null;
}
}
private static boolean ccSearched = false;
private static Class<?> computerCraft = null;
private static Method computerCraft_getVersion = null;
private static Method computerCraft_createUniqueNumberedSaveDir = null;
private static Method computerCraft_createSaveDirMount = null;
private static Method computerCraft_createResourceMount = null;
private static Method computerCraft_registerPeripheralProvider = null;
private static Method computerCraft_createUniqueNumberedSaveDir = null;
private static Method computerCraft_createSaveDirMount = null;
private static Method computerCraft_createResourceMount = null;
private static Method computerCraft_registerPeripheralProvider = null;
private static Method computerCraft_registerTurtleUpgrade = null;
private static Method computerCraft_registerBundledRedstoneProvider = null;
private static Method computerCraft_getDefaultBundledRedstoneOutput = null;
private static Method computerCraft_registerMediaProvider = null;
private static Method computerCraft_registerPermissionProvider = null;
private static Method computerCraft_registerPocketUpgrade = null;
private static Method computerCraft_getWirelessNetwork = null;
private static Method computerCraft_registerAPIFactory = null;
private static Method computerCraft_createWiredNodeForElement = null;
private static Method computerCraft_getWiredElementAt = null;
}

View File

@@ -0,0 +1,38 @@
package dan200.computercraft.api.filesystem;
import java.io.IOException;
/**
* Provides a mount of the entire computer's file system.
*
* This exists for use by various APIs - one should not attempt to mount it.
*/
public interface IFileSystem extends IWritableMount
{
/**
* Combine two paths together, reducing them into a normalised form.
*
* @param path The main path.
* @param child The path to append.
* @return The combined, normalised path.
*/
String combine( String path, String child );
/**
* Copy files from one location to another.
*
* @param from The location to copy from.
* @param to The location to copy to. This should not exist.
* @throws IOException If the copy failed.
*/
void copy( String from, String to ) throws IOException;
/**
* Move files from one location to another.
*
* @param from The location to move from.
* @param to The location to move to. This should not exist.
* @throws IOException If the move failed.
*/
void move( String from, String to ) throws IOException;
}

View File

@@ -1,57 +1,98 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.filesystem;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.api.peripheral.IComputerAccess;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.List;
/**
* Represents a read only part of a virtual filesystem that can be mounted onto a computercraft using IComputerAccess.mount().
* Ready made implementations of this interface can be created using ComputerCraftAPI.createSaveDirMount() or ComputerCraftAPI.createResourceMount(), or you're free to implement it yourselves!
* @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String)
* @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String)
* @see dan200.computercraft.api.peripheral.IComputerAccess#mount(String, IMount)
* Represents a read only part of a virtual filesystem that can be mounted onto a computer using
* {@link IComputerAccess#mount(String, IMount)}
*
* Ready made implementations of this interface can be created using
* {@link ComputerCraftAPI#createSaveDirMount(World, String, long)} or
* {@link ComputerCraftAPI#createResourceMount(Class, String, String)}, or you're free to implement it yourselves!
*
* @see ComputerCraftAPI#createSaveDirMount(World, String, long)
* @see ComputerCraftAPI#createResourceMount(Class, String, String)
* @see IComputerAccess#mount(String, IMount)
* @see IWritableMount
*/
public interface IMount
{
/**
* Returns whether a file with a given path exists or not.
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram"
* @return true if the file exists, false otherwise
*/
public boolean exists( String path ) throws IOException;
/**
* Returns whether a file with a given path exists or not.
*
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram"
* @return If the file exists.
* @throws IOException If an error occurs when checking the existence of the file.
*/
boolean exists( @Nonnull String path ) throws IOException;
/**
* Returns whether a file with a given path is a directory or not.
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms"
* @return true if the file exists and is a directory, false otherwise
*/
public boolean isDirectory( String path ) throws IOException;
/**
* Returns whether a file with a given path is a directory or not.
*
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms".
* @return If the file exists and is a directory
* @throws IOException If an error occurs when checking whether the file is a directory.
*/
boolean isDirectory( @Nonnull String path ) throws IOException;
/**
* Returns the file names of all the files in a directory.
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms"
* @param contents A list of strings. Add all the file names to this list
*/
public void list( String path, List<String> contents ) throws IOException;
/**
* Returns the file names of all the files in a directory.
*
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms".
* @param contents A list of strings. Add all the file names to this list.
* @throws IOException If the file was not a directory, or could not be listed.
*/
void list( @Nonnull String path, @Nonnull List<String> contents ) throws IOException;
/**
* Returns the size of a file with a given path, in bytes
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram"
* @return the size of the file, in bytes
*/
public long getSize( String path ) throws IOException;
/**
* Opens a file with a given path, and returns an inputstream representing it's contents.
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram"
* @return a stream representing the contents of the file
*/
public InputStream openForRead( String path ) throws IOException;
/**
* Returns the size of a file with a given path, in bytes
*
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram".
* @return The size of the file, in bytes.
* @throws IOException If the file does not exist, or its size could not be determined.
*/
long getSize( @Nonnull String path ) throws IOException;
/**
* Opens a file with a given path, and returns an {@link InputStream} representing its contents.
*
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram".
* @return A stream representing the contents of the file.
* @throws IOException If the file does not exist, or could not be opened.
* @deprecated Use {@link #openChannelForRead(String)} instead
*/
@Nonnull
@Deprecated
InputStream openForRead( @Nonnull String path ) throws IOException;
/**
* Opens a file with a given path, and returns an {@link ReadableByteChannel} representing its contents.
*
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram".
* @return A channel representing the contents of the file. If the channel implements
* {@link java.nio.channels.SeekableByteChannel}, one will be able to seek to arbitrary positions when using binary
* mode.
* @throws IOException If the file does not exist, or could not be opened.
*/
@Nonnull
@SuppressWarnings("deprecation")
default ReadableByteChannel openChannelForRead( @Nonnull String path ) throws IOException
{
return Channels.newChannel( openForRead( path ) );
}
}

View File

@@ -1,52 +1,111 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.filesystem;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.api.peripheral.IComputerAccess;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
/**
* Represents a part of a virtual filesystem that can be mounted onto a computercraft using IComputerAccess.mount() or IComputerAccess.mountWritable(), that can also be written to.
* Ready made implementations of this interface can be created using ComputerCraftAPI.createSaveDirMount(), or you're free to implement it yourselves!
* @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String)
* @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, dan200.computercraft.api.filesystem.IMount)
* @see dan200.computercraft.api.filesystem.IMount
* Represents a part of a virtual filesystem that can be mounted onto a computer using {@link IComputerAccess#mount(String, IMount)}
* or {@link IComputerAccess#mountWritable(String, IWritableMount)}, that can also be written to.
*
* Ready made implementations of this interface can be created using
* {@link ComputerCraftAPI#createSaveDirMount(World, String, long)}, or you're free to implement it yourselves!
*
* @see ComputerCraftAPI#createSaveDirMount(World, String, long)
* @see IComputerAccess#mount(String, IMount)
* @see IComputerAccess#mountWritable(String, IWritableMount)
* @see IMount
*/
public interface IWritableMount extends IMount
{
/**
* Creates a directory at a given path inside the virtual file system.
* @param path A file path in normalised format, relative to the mount location. ie: "programs/mynewprograms"
*/
public void makeDirectory( String path ) throws IOException;
/**
* Creates a directory at a given path inside the virtual file system.
*
* @param path A file path in normalised format, relative to the mount location. ie: "programs/mynewprograms".
* @throws IOException If the directory already exists or could not be created.
*/
void makeDirectory( @Nonnull String path ) throws IOException;
/**
* Deletes a directory at a given path inside the virtual file system.
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myoldprograms"
*/
public void delete( String path ) throws IOException;
/**
* Deletes a directory at a given path inside the virtual file system.
*
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myoldprograms".
* @throws IOException If the file does not exist or could not be deleted.
*/
void delete( @Nonnull String path ) throws IOException;
/**
* Opens a file with a given path, and returns an outputstream for writing to it.
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram"
* @return a stream for writing to
*/
public OutputStream openForWrite( String path ) throws IOException;
/**
* Opens a file with a given path, and returns an {@link OutputStream} for writing to it.
*
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram".
* @return A stream for writing to
* @throws IOException If the file could not be opened for writing.
* @deprecated Use {@link #openChannelForWrite(String)} instead.
*/
@Nonnull
@Deprecated
OutputStream openForWrite( @Nonnull String path ) throws IOException;
/**
* Opens a file with a given path, and returns an outputstream for appending to it.
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram"
* @return a stream for writing to
*/
public OutputStream openForAppend( String path ) throws IOException;
/**
* Opens a file with a given path, and returns an {@link OutputStream} for writing to it.
*
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram".
* @return A stream for writing to. If the channel implements {@link java.nio.channels.SeekableByteChannel}, one
* will be able to seek to arbitrary positions when using binary mode.
* @throws IOException If the file could not be opened for writing.
*/
@Nonnull
@SuppressWarnings("deprecation")
default WritableByteChannel openChannelForWrite( @Nonnull String path ) throws IOException
{
return Channels.newChannel( openForWrite( path ) );
}
/**
* Get the ammount of free space on the mount, in bytes. You should decrease this value as the user writes to the mount, and write operations should fail once it reaches zero.
* @return The ammount of free space, in bytes.
*/
public long getRemainingSpace() throws IOException;
/**
* Opens a file with a given path, and returns an {@link OutputStream} for appending to it.
*
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram".
* @return A stream for writing to.
* @throws IOException If the file could not be opened for writing.
* @deprecated Use {@link #openChannelForAppend(String)} instead.
*/
@Nonnull
@Deprecated
OutputStream openForAppend( @Nonnull String path ) throws IOException;
/**
* Opens a file with a given path, and returns an {@link OutputStream} for appending to it.
*
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram".
* @return A stream for writing to. If the channel implements {@link java.nio.channels.SeekableByteChannel}, one
* will be able to seek to arbitrary positions when using binary mode.
* @throws IOException If the file could not be opened for writing.
*/
@Nonnull
@SuppressWarnings("deprecation")
default WritableByteChannel openChannelForAppend( @Nonnull String path ) throws IOException
{
return Channels.newChannel( openForAppend( path ) );
}
/**
* Get the amount of free space on the mount, in bytes. You should decrease this value as the user writes to the
* mount, and write operations should fail once it reaches zero.
*
* @return The amount of free space, in bytes.
* @throws IOException If the remaining space could not be computed.
*/
long getRemainingSpace() throws IOException;
}

View File

@@ -1,10 +1,10 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
@API( owner="ComputerCraft", provides="ComputerCraft|API|FileSystem", apiVersion="${version}" )
package dan200.computercraft.api.filesystem;
import net.minecraftforge.fml.common.API;
import net.minecraftforge.fml.common.API;

View File

@@ -0,0 +1,29 @@
package dan200.computercraft.api.lua;
import dan200.computercraft.api.filesystem.IFileSystem;
import dan200.computercraft.api.peripheral.IComputerAccess;
import javax.annotation.Nullable;
/**
* An interface passed to {@link ILuaAPIFactory} in order to provide additional information
* about a computer.
*/
public interface IComputerSystem extends IComputerAccess
{
/**
* Get the file system for this computer.
*
* @return The computer's file system, or {@code null} if it is not initialised.
*/
@Nullable
IFileSystem getFileSystem();
/**
* Get the label for this computer
*
* @return This computer's label, or {@code null} if it is not set.
*/
@Nullable
String getLabel();
}

View File

@@ -0,0 +1,47 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.api.lua;
import dan200.computercraft.api.ComputerCraftAPI;
/**
* Represents a {@link ILuaObject} which is stored as a global variable on computer startup.
*
* Before implementing this interface, consider alternative methods of providing methods. It is generally preferred
* to use peripherals to provide functionality to users.
*
* @see ILuaAPIFactory
* @see ComputerCraftAPI#registerAPIFactory(ILuaAPIFactory)
*/
public interface ILuaAPI extends ILuaObject
{
/**
* Get the globals this API will be assigned to. This will override any other global, so you should
*
* @return A list of globals this API will be assigned to.
*/
String[] getNames();
/**
* Called when the computer is turned on.
*
* One should only interact with the file system.
*/
default void startup() { }
/**
* Called every time the computer is ticked. This can be used to process various.
*/
default void update() { }
/**
* Called when the computer is turned off or unloaded.
*
* This should reset the state of the object, disposing any remaining file handles, or other resources.
*/
default void shutdown() { }
}

View File

@@ -0,0 +1,24 @@
package dan200.computercraft.api.lua;
import dan200.computercraft.api.ComputerCraftAPI;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Construct an {@link ILuaAPI} for a specific computer.
*
* @see ILuaAPI
* @see ComputerCraftAPI#registerAPIFactory(ILuaAPIFactory)
*/
public interface ILuaAPIFactory
{
/**
* Create a new API instance for a given computer.
*
* @param computer The computer this API is for.
* @return The created API, or {@code null} if one should not be injected.
*/
@Nullable
ILuaAPI create( @Nonnull IComputerSystem computer );
}

View File

@@ -1,58 +1,97 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.lua;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* An interface passed to peripherals and ILuaObjects' by computers or turtles, providing methods
* that allow the peripheral call to wait for events before returning, just like in lua.
* This is very useful if you need to signal work to be performed on the main thread, and don't want to return
* until the work has been completed.
* An interface passed to peripherals and {@link ILuaObject}s by computers or turtles, providing methods
* that allow the peripheral call to wait for events before returning, just like in lua. This is very useful if you need
* to signal work to be performed on the main thread, and don't want to return until the work has been completed.
*/
public interface ILuaContext
{
/**
* Wait for an event to occur on the computercraft, suspending the thread until it arises. This method is exactly equivalent to os.pullEvent() in lua.
* @param filter A specific event to wait for, or null to wait for any event
* @return An object array containing the name of the event that occurred, and any event parameters
* @throws Exception If the user presses CTRL+T to terminate the current program while pullEvent() is waiting for an event, a "Terminated" exception will be thrown here.
* Do not attempt to common this exception, unless you wish to prevent termination, which is not recommended.
* @throws InterruptedException If the user shuts down or reboots the computercraft while pullEvent() is waiting for an event, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state.
*/
public Object[] pullEvent( String filter ) throws LuaException, InterruptedException;
/**
* The same as pullEvent(), except "terminated" events are ignored. Only use this if you want to prevent program termination, which is not recommended. This method is exactly equivalent to os.pullEventRaw() in lua.
* @param filter A specific event to wait for, or null to wait for any event
* @return An object array containing the name of the event that occurred, and any event parameters
* @throws InterruptedException If the user shuts down or reboots the computercraft while pullEventRaw() is waiting for an event, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state.
* @see #pullEvent(String)
*/
public Object[] pullEventRaw( String filter ) throws InterruptedException;
/**
* Yield the current coroutine with some arguments until it is resumed. This method is exactly equivalent to coroutine.yield() in lua. Use pullEvent() if you wish to wait for events.
* @param arguments An object array containing the arguments to pass to coroutine.yield()
* @return An object array containing the return values from coroutine.yield()
* @throws InterruptedException If the user shuts down or reboots the computercraft the coroutine is suspended, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state.
* @see #pullEvent(String)
*/
public Object[] yield( Object[] arguments ) throws InterruptedException;
/**
* Wait for an event to occur on the computer, suspending the thread until it arises. This method is exactly
* equivalent to {@code os.pullEvent()} in lua.
*
* @param filter A specific event to wait for, or null to wait for any event.
* @return An object array containing the name of the event that occurred, and any event parameters.
* @throws LuaException If the user presses CTRL+T to terminate the current program while pullEvent() is
* waiting for an event, a "Terminated" exception will be thrown here.
*
* Do not attempt to catch this exception. You should use {@link #pullEventRaw(String)}
* should you wish to disable termination.
* @throws InterruptedException If the user shuts down or reboots the computer while pullEvent() is waiting for an
* event, InterruptedException will be thrown. This exception must not be caught or
* intercepted, or the computer will leak memory and end up in a broken state.
*/
@Nonnull
Object[] pullEvent( @Nullable String filter ) throws LuaException, InterruptedException;
/**
* TODO: Document me
* @param task
* @return
* The same as {@link #pullEvent(String)}, except "terminated" events are ignored. Only use this if you want to
* prevent program termination, which is not recommended. This method is exactly equivalent to
* {@code os.pullEventRaw()} in lua.
*
* @param filter A specific event to wait for, or null to wait for any event.
* @return An object array containing the name of the event that occurred, and any event parameters.
* @throws InterruptedException If the user shuts down or reboots the computer while pullEventRaw() is waiting for
* an event, InterruptedException will be thrown. This exception must not be caught or
* intercepted, or the computer will leak memory and end up in a broken state.
* @see #pullEvent(String)
*/
public Object[] executeMainThreadTask( ILuaTask task ) throws LuaException, InterruptedException;
@Nonnull
Object[] pullEventRaw( @Nullable String filter ) throws InterruptedException;
/**
* TODO: Document me
* @param task
* @return
* Yield the current coroutine with some arguments until it is resumed. This method is exactly equivalent to
* {@code coroutine.yield()} in lua. Use {@code pullEvent()} if you wish to wait for events.
*
* @param arguments An object array containing the arguments to pass to coroutine.yield()
* @return An object array containing the return values from coroutine.yield()
* @throws InterruptedException If the user shuts down or reboots the computer the coroutine is suspended,
* InterruptedException will be thrown. This exception must not be caught or
* intercepted, or the computer will leak memory and end up in a broken state.
* @see #pullEvent(String)
*/
public long issueMainThreadTask( ILuaTask task ) throws LuaException;
@Nonnull
Object[] yield( @Nullable Object[] arguments ) throws InterruptedException;
/**
* Queue a task to be executed on the main server thread at the beginning of next tick, waiting for it to complete.
* This should be used when you need to interact with the world in a thread-safe manner.
*
* Note that the return values of your task are handled as events, meaning more complex objects such as maps or
* {@link ILuaObject} will not preserve their identities.
*
* @param task The task to execute on the main thread.
* @return The objects returned by {@code task}.
* @throws LuaException If the task could not be queued, or if the task threw an exception.
* @throws InterruptedException If the user shuts down or reboots the computer the coroutine is suspended,
* InterruptedException will be thrown. This exception must not be caught or
* intercepted, or the computer will leak memory and end up in a broken state.
*/
@Nullable
Object[] executeMainThreadTask( @Nonnull ILuaTask task ) throws LuaException, InterruptedException;
/**
* Queue a task to be executed on the main server thread at the beginning of next tick, but do not wait for it to
* complete. This should be used when you need to interact with the world in a thread-safe manner but do not care
* about the result or you wish to run asynchronously.
*
* When the task has finished, it will enqueue a {@code task_completed} event, which takes the task id, a success
* value and the return values, or an error message if it failed. If you need to wait on this event, it may be
* better to use {@link #executeMainThreadTask(ILuaTask)}.
*
* @param task The task to execute on the main thread.
* @return The "id" of the task. This will be the first argument to the {@code task_completed} event.
* @throws LuaException If the task could not be queued.
*/
long issueMainThreadTask( @Nonnull ILuaTask task ) throws LuaException;
}

View File

@@ -1,26 +1,56 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.lua;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* An interface for representing custom objects returned by IPeripheral.callMethod() calls.
* An interface for representing custom objects returned by {@link IPeripheral#callMethod(IComputerAccess, ILuaContext, int, Object[])}
* calls.
*
* Return objects implementing this interface to expose objects with methods to lua.
*/
public interface ILuaObject
{
/**
* Get the names of the methods that this object implements. This works the same as IPeripheral.getMethodNames(). See that method for detailed documentation.
* @see dan200.computercraft.api.peripheral.IPeripheral#getMethodNames()
*/
public String[] getMethodNames();
/**
* Get the names of the methods that this object implements. This works the same as {@link IPeripheral#getMethodNames()}.
* See that method for detailed documentation.
*
* @return The method names this object provides.
* @see IPeripheral#getMethodNames()
*/
@Nonnull
String[] getMethodNames();
/**
* Called when a user calls one of the methods that this object implements. This works the same as IPeripheral.callMethod(). See that method for detailed documentation.
* @see dan200.computercraft.api.peripheral.IPeripheral#callMethod(dan200.computercraft.api.peripheral.IComputerAccess, ILuaContext, int, Object[])
*/
public Object[] callMethod( ILuaContext context, int method, Object[] arguments ) throws LuaException, InterruptedException;
/**
* Called when a user calls one of the methods that this object implements. This works the same as
* {@link IPeripheral#callMethod(IComputerAccess, ILuaContext, int, Object[])}}. See that method for detailed
* documentation.
*
* @param context The context of the currently running lua thread. This can be used to wait for events
* or otherwise yield.
* @param method An integer identifying which of the methods from getMethodNames() the computercraft
* wishes to call. The integer indicates the index into the getMethodNames() table
* that corresponds to the string passed into peripheral.call()
* @param arguments The arguments for this method. See {@link IPeripheral#callMethod(IComputerAccess, ILuaContext, int, Object[])}
* the possible values and conversion rules.
* @return An array of objects, representing the values you wish to return to the Lua program.
* See {@link IPeripheral#callMethod(IComputerAccess, ILuaContext, int, Object[])} for the valid values and
* conversion rules.
* @throws LuaException If the task could not be queued, or if the task threw an exception.
* @throws InterruptedException If the user shuts down or reboots the computer the coroutine is suspended,
* InterruptedException will be thrown. This exception must not be caught or
* intercepted, or the computer will leak memory and end up in a broken state.w
* @see IPeripheral#callMethod(IComputerAccess, ILuaContext, int, Object[])
*/
@Nullable
Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull Object[] arguments ) throws LuaException, InterruptedException;
}

View File

@@ -1,12 +1,33 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.lua;
import javax.annotation.Nullable;
/**
* A task which can be executed via {@link ILuaContext#executeMainThreadTask(ILuaTask)} or
* {@link ILuaContext#issueMainThreadTask(ILuaTask)}. This will be run on the main thread, at the beginning of the
* next tick.
*
* @see ILuaContext#executeMainThreadTask(ILuaTask)
* @see ILuaContext#issueMainThreadTask(ILuaTask)
*/
@FunctionalInterface
public interface ILuaTask
{
public Object[] execute() throws LuaException;
/**
* Execute this task.
*
* @return The arguments to add to the {@code task_completed} event. These will be returned by
* {@link ILuaContext#executeMainThreadTask(ILuaTask)}.
* @throws LuaException If you throw any exception from this function, a lua error will be raised with the
* same message as your exception. Use this to throw appropriate errors if the wrong
* arguments are supplied to your method.
*/
@Nullable
Object[] execute() throws LuaException;
}

View File

@@ -1,16 +1,19 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.lua;
import javax.annotation.Nullable;
/**
* An exception representing an error in Lua, like that raised by the error() function
* An exception representing an error in Lua, like that raised by the {@code error()} function.
*/
public class LuaException extends Exception
{
private static final long serialVersionUID = -6136063076818512651L;
private final int m_level;
public LuaException()
@@ -18,17 +21,23 @@ public class LuaException extends Exception
this( "error", 1 );
}
public LuaException( String message )
public LuaException( @Nullable String message )
{
this( message, 1 );
}
public LuaException( String message, int level )
public LuaException( @Nullable String message, int level )
{
super( message );
m_level = level;
}
/**
* The level this error is raised at. Level 1 is the function's caller, level 2 is that function's caller, and so
* on.
*
* @return The level to raise the error at.
*/
public int getLevel()
{
return m_level;

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. 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-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. 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.
*/
@@ -11,50 +11,65 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.SoundEvent;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Represents an item that can be placed in a disk drive and used by a Computer.
* Implement this interface on your Item class to allow it to be used in the drive.
*/
public interface IMedia
{
/**
* Get a string representing the label of this item. Will be called vi disk.getLabel() in lua.
* @param stack The itemstack to inspect
* @return The label. ie: "Dan's Programs"
*/
public String getLabel( ItemStack stack );
/**
* Get a string representing the label of this item. Will be called via {@code disk.getLabel()} in lua.
*
* @param stack The itemstack to inspect.
* @return The label. ie: "Dan's Programs".
*/
@Nullable
String getLabel( @Nonnull ItemStack stack );
/**
* Set a string representing the label of this item. Will be called vi disk.setLabel() in lua.
* @param stack The itemstack to modify.
* @param label The string to set the label to.
* @return true if the label was updated, false if the label may not be modified.
*/
public boolean setLabel( ItemStack stack, String label );
/**
* If this disk represents an item with audio (like a record), get the readable name of the audio track. ie: "Jonathon Coulton - Still Alive"
* @param stack The itemstack to inspect.
* @return The name, or null if this item does not represent an item with audio.
*/
public String getAudioTitle( ItemStack stack );
/**
* Set a string representing the label of this item. Will be called vi {@code disk.setLabel()} in lua.
*
* @param stack The itemstack to modify.
* @param label The string to set the label to.
* @return true if the label was updated, false if the label may not be modified.
*/
boolean setLabel( @Nonnull ItemStack stack, @Nullable String label );
/**
* If this disk represents an item with audio (like a record), get the resource name of the audio track to play.
* @param stack The itemstack to inspect.
* @return The name, or null if this item does not represent an item with audio.
*/
public SoundEvent getAudio( ItemStack stack );
/**
* If this disk represents an item with data (like a floppy disk), get a mount representing it's contents. This will be mounted onto the filesystem of the computercraft while the media is in the disk drive.
* @param stack The itemstack to inspect.
* @param world The world in which the item and disk drive reside.
* @return The mount, or null if this item does not represent an item with data. If the IMount returned also implements IWritableMount, it will mounted using mountWritable()
* @see dan200.computercraft.api.filesystem.IMount
* @see dan200.computercraft.api.filesystem.IWritableMount
* @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String, long)
* @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String)
*/
public IMount createDataMount( ItemStack stack, World world );
/**
* If this disk represents an item with audio (like a record), get the readable name of the audio track. ie:
* "Jonathon Coulton - Still Alive"
*
* @param stack The itemstack to inspect.
* @return The name, or null if this item does not represent an item with audio.
*/
@Nullable
String getAudioTitle( @Nonnull ItemStack stack );
/**
* If this disk represents an item with audio (like a record), get the resource name of the audio track to play.
*
* @param stack The itemstack to inspect.
* @return The name, or null if this item does not represent an item with audio.
*/
@Nullable
SoundEvent getAudio( @Nonnull ItemStack stack );
/**
* If this disk represents an item with data (like a floppy disk), get a mount representing it's contents. This will
* be mounted onto the filesystem of the computer while the media is in the disk drive.
*
* @param stack The itemstack to inspect.
* @param world The world in which the item and disk drive reside.
* @return The mount, or null if this item does not represent an item with data. If the mount returned also
* implements {@link dan200.computercraft.api.filesystem.IWritableMount}, it will mounted using mountWritable()
* @see dan200.computercraft.api.filesystem.IMount
* @see dan200.computercraft.api.filesystem.IWritableMount
* @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String, long)
* @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String)
*/
@Nullable
IMount createDataMount( @Nonnull ItemStack stack, @Nonnull World world );
}

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. 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.
*/
@@ -8,16 +8,24 @@ package dan200.computercraft.api.media;
import net.minecraft.item.ItemStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* This interface is used to provide IMedia implementations for ItemStack
* This interface is used to provide {@link IMedia} implementations for {@link ItemStack}.
*
* @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider)
*/
@FunctionalInterface
public interface IMediaProvider
{
/**
* Produce an IMedia implementation from an ItemStack.
*
* @param stack The stack from which to extract the media information.
* @return An IMedia implementation, or null if the item is not something you wish to handle
* @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider)
* @return an IMedia implementation, or null if the item is not something you wish to handle
*/
public IMedia getMedia( ItemStack stack );
@Nullable
IMedia getMedia( @Nonnull ItemStack stack );
}

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. 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,59 @@
/*
* 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.api.network;
import javax.annotation.Nonnull;
/**
* A packet network represents a collection of devices which can send and receive packets.
*
* @see Packet
* @see IPacketReceiver
*/
public interface IPacketNetwork
{
/**
* Add a receiver to the network.
*
* @param receiver The receiver to register to the network.
*/
void addReceiver( @Nonnull IPacketReceiver receiver );
/**
* Remove a receiver from the network.
*
* @param receiver The device to remove from the network.
*/
void removeReceiver( @Nonnull IPacketReceiver receiver );
/**
* Determine whether this network is wireless.
*
* @return Whether this network is wireless.
*/
boolean isWireless();
/**
* Submit a packet for transmitting across the network. This will route the packet through the network, sending it
* to all receivers within range (or any interdimensional ones).
*
* @param packet The packet to send.
* @param range The maximum distance this packet will be sent.
* @see #transmitInterdimensional(Packet)
* @see IPacketReceiver#receiveSameDimension(Packet, double)
*/
void transmitSameDimension( @Nonnull Packet packet, double range );
/**
* Submit a packet for transmitting across the network. This will route the packet through the network, sending it
* to all receivers across all dimensions.
*
* @param packet The packet to send.
* @see #transmitSameDimension(Packet, double)
* @see IPacketReceiver#receiveDifferentDimension(Packet)
*/
void transmitInterdimensional( @Nonnull Packet packet );
}

View File

@@ -0,0 +1,84 @@
/*
* 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.api.network;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
/**
* An object on an {@link IPacketNetwork}, capable of receiving packets.
*/
public interface IPacketReceiver
{
/**
* Get the world in which this packet receiver exists.
*
* @return The receivers's world.
*/
@Nonnull
World getWorld();
/**
* Get the position in the world at which this receiver exists.
*
* @return The receiver's position.
*/
@Nonnull
Vec3d getPosition();
/**
* Get the maximum distance this receiver can send and receive messages.
*
* When determining whether a receiver can receive a message, the largest distance of the packet and receiver is
* used - ensuring it is within range. If the packet or receiver is inter-dimensional, then the packet will always
* be received.
*
* @return The maximum distance this device can send and receive messages.
* @see #isInterdimensional()
* @see #receiveSameDimension(Packet packet, double)
* @see IPacketNetwork#transmitInterdimensional(Packet)
*/
double getRange();
/**
* Determine whether this receiver can receive packets from other dimensions.
*
* A device will receive an inter-dimensional packet if either it or the sending device is inter-dimensional.
*
* @return Whether this receiver receives packets from other dimensions.
* @see #getRange()
* @see #receiveDifferentDimension(Packet)
* @see IPacketNetwork#transmitInterdimensional(Packet)
*/
boolean isInterdimensional();
/**
* Receive a network packet from the same dimension.
*
* @param packet The packet to receive. Generally you should check that you are listening on the given channel and,
* if so, queue the appropriate modem event.
* @param distance The distance this packet has travelled from the source.
* @see Packet
* @see #getRange()
* @see IPacketNetwork#transmitSameDimension(Packet, double)
* @see IPacketNetwork#transmitInterdimensional(Packet)
*/
void receiveSameDimension( @Nonnull Packet packet, double distance );
/**
* Receive a network packet from a different dimension.
*
* @param packet The packet to receive. Generally you should check that you are listening on the given channel and,
* if so, queue the appropriate modem event.
* @see Packet
* @see IPacketNetwork#transmitInterdimensional(Packet)
* @see IPacketNetwork#transmitSameDimension(Packet, double)
* @see #isInterdimensional()
*/
void receiveDifferentDimension( @Nonnull Packet packet );
}

View File

@@ -0,0 +1,42 @@
/*
* 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.api.network;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
/**
* An object on a {@link IPacketNetwork}, capable of sending packets.
*/
public interface IPacketSender
{
/**
* Get the world in which this packet sender exists.
*
* @return The sender's world.
*/
@Nonnull
World getWorld();
/**
* Get the position in the world at which this sender exists.
*
* @return The sender's position.
*/
@Nonnull
Vec3d getPosition();
/**
* Get some sort of identification string for this sender. This does not strictly need to be unique, but you
* should be able to extract some identifiable information from it.
*
* @return This device's id.
*/
@Nonnull
String getSenderID();
}

View File

@@ -0,0 +1,118 @@
/*
* 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.api.network;
import com.google.common.base.Preconditions;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Represents a packet which may be sent across a {@link IPacketNetwork}.
*
* @see IPacketSender
* @see IPacketNetwork#transmitSameDimension(Packet, double)
* @see IPacketNetwork#transmitInterdimensional(Packet)
* @see IPacketReceiver#receiveDifferentDimension(Packet)
* @see IPacketReceiver#receiveSameDimension(Packet, double)
*/
public class Packet
{
private final int m_channel;
private final int m_replyChannel;
private final Object m_payload;
private final IPacketSender m_sender;
/**
* Create a new packet, ready for transmitting across the network.
*
* @param channel The channel to send the packet along. Receiving devices should only process packets from on
* channels they are listening to.
* @param replyChannel The channel to reply on.
* @param payload The contents of this packet. This should be a "valid" Lua object, safe for queuing as an
* event or returning from a peripheral call.
* @param sender The object which sent this packet.
*/
public Packet( int channel, int replyChannel, @Nullable Object payload, @Nonnull IPacketSender sender )
{
Preconditions.checkNotNull( sender, "sender cannot be null" );
m_channel = channel;
m_replyChannel = replyChannel;
m_payload = payload;
m_sender = sender;
}
/**
* Get the channel this packet is sent along. Receivers should generally only process packets from on channels they
* are listening to.
*
* @return This packet's channel.
*/
public int getChannel()
{
return m_channel;
}
/**
* The channel to reply on. Objects which will reply should send it along this channel.
*
* @return This channel to reply on.
*/
public int getReplyChannel()
{
return m_replyChannel;
}
/**
* The actual data of this packet. This should be a "valid" Lua object, safe for queuing as an
* event or returning from a peripheral call.
*
* @return The packet's payload
*/
@Nullable
public Object getPayload()
{
return m_payload;
}
/**
* The object which sent this message.
*
* @return The sending object.
*/
@Nonnull
public IPacketSender getSender()
{
return m_sender;
}
@Override
public boolean equals( Object o )
{
if( this == o ) return true;
if( o == null || getClass() != o.getClass() ) return false;
Packet packet = (Packet) o;
if( m_channel != packet.m_channel ) return false;
if( m_replyChannel != packet.m_replyChannel ) return false;
if( m_payload != null ? !m_payload.equals( packet.m_payload ) : packet.m_payload != null ) return false;
return m_sender.equals( packet.m_sender );
}
@Override
public int hashCode()
{
int result;
result = m_channel;
result = 31 * result + m_replyChannel;
result = 31 * result + (m_payload != null ? m_payload.hashCode() : 0);
result = 31 * result + m_sender.hashCode();
return result;
}
}

View File

@@ -0,0 +1,10 @@
/*
* 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.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
@API( owner="ComputerCraft", provides="ComputerCraft|API|Network", apiVersion="${version}" )
package dan200.computercraft.api.network;
import net.minecraftforge.fml.common.API;

View File

@@ -0,0 +1,29 @@
package dan200.computercraft.api.network.wired;
import dan200.computercraft.api.ComputerCraftAPI;
import javax.annotation.Nonnull;
/**
* An object which may be part of a wired network.
*
* Elements should construct a node using {@link ComputerCraftAPI#createWiredNodeForElement(IWiredElement)}. This acts
* as a proxy for all network objects. Whilst the node may change networks, an element's node should remain constant
* for its lifespan.
*
* Elements are generally tied to a block or tile entity in world. In such as case, one should provide the
* {@link IWiredElement} capability for the appropriate sides.
*/
public interface IWiredElement extends IWiredSender
{
/**
* Called when objects on the network change. This may occur when network nodes are added or removed, or when
* peripherals change.
*
* @param change The change which occurred.
* @see IWiredNetworkChange
*/
default void networkChanged( @Nonnull IWiredNetworkChange change )
{
}
}

View File

@@ -0,0 +1,80 @@
package dan200.computercraft.api.network.wired;
import dan200.computercraft.api.peripheral.IPeripheral;
import javax.annotation.Nonnull;
import java.util.Map;
/**
* A wired network is composed of one of more {@link IWiredNode}s, a set of connections between them, and a series
* of peripherals.
*
* Networks from a connected graph. This means there is some path between all nodes on the network. Further more, if
* there is some path between two nodes then they must be on the same network. {@link IWiredNetwork} will automatically
* handle the merging and splitting of networks (and thus changing of available nodes and peripherals) as connections
* change.
*
* This does mean one can not rely on the network remaining consistent between subsequent operations. Consequently,
* it is generally preferred to use the methods provided by {@link IWiredNode}.
*
* @see IWiredNode#getNetwork()
*/
public interface IWiredNetwork
{
/**
* Create a connection between two nodes.
*
* This should only be used on the server thread.
*
* @param left The first node to connect
* @param right The second node to connect
* @return {@code true} if a connection was created or {@code false} if the connection already exists.
* @throws IllegalStateException If neither node is on the network.
* @throws IllegalArgumentException If {@code left} and {@code right} are equal.
* @see IWiredNode#connectTo(IWiredNode)
* @see IWiredNetwork#connect(IWiredNode, IWiredNode)
*/
boolean connect( @Nonnull IWiredNode left, @Nonnull IWiredNode right );
/**
* Destroy a connection between this node and another.
*
* This should only be used on the server thread.
*
* @param left The first node in the connection.
* @param right The second node in the connection.
* @return {@code true} if a connection was destroyed or {@code false} if no connection exists.
* @throws IllegalArgumentException If either node is not on the network.
* @throws IllegalArgumentException If {@code left} and {@code right} are equal.
* @see IWiredNode#disconnectFrom(IWiredNode)
* @see IWiredNetwork#connect(IWiredNode, IWiredNode)
*/
boolean disconnect( @Nonnull IWiredNode left, @Nonnull IWiredNode right );
/**
* Sever all connections this node has, removing it from this network.
*
* This should only be used on the server thread. You should only call this on nodes
* that your network element owns.
*
* @param node The node to remove
* @return Whether this node was removed from the network. One cannot remove a node from a network where it is the
* only element.
* @throws IllegalArgumentException If the node is not in the network.
* @see IWiredNode#remove()
*/
boolean remove( @Nonnull IWiredNode node );
/**
* Update the peripherals a node provides.
*
* This should only be used on the server thread. You should only call this on nodes
* that your network element owns.
*
* @param node The node to attach peripherals for.
* @param peripherals The new peripherals for this node.
* @throws IllegalArgumentException If the node is not in the network.
* @see IWiredNode#updatePeripherals(Map)
*/
void updatePeripherals( @Nonnull IWiredNode node, @Nonnull Map<String, IPeripheral> peripherals );
}

View File

@@ -0,0 +1,32 @@
package dan200.computercraft.api.network.wired;
import dan200.computercraft.api.peripheral.IPeripheral;
import javax.annotation.Nonnull;
import java.util.Map;
/**
* Represents a change to the objects on a wired network.
*
* @see IWiredElement#networkChanged(IWiredNetworkChange)
*/
public interface IWiredNetworkChange
{
/**
* A set of peripherals which have been removed. Note that there may be entries with the same name
* in the added and removed set, but with a different peripheral.
*
* @return The set of removed peripherals.
*/
@Nonnull
Map<String, IPeripheral> peripheralsRemoved();
/**
* A set of peripherals which have been added. Note that there may be entries with the same name
* in the added and removed set, but with a different peripheral.
*
* @return The set of added peripherals.
*/
@Nonnull
Map<String, IPeripheral> peripheralsAdded();
}

View File

@@ -0,0 +1,103 @@
package dan200.computercraft.api.network.wired;
import dan200.computercraft.api.network.IPacketNetwork;
import dan200.computercraft.api.peripheral.IPeripheral;
import javax.annotation.Nonnull;
import java.util.Map;
/**
* Wired nodes act as a layer between {@link IWiredElement}s and {@link IWiredNetwork}s.
*
* Firstly, a node acts as a packet network, capable of sending and receiving modem messages to connected nodes. These
* methods may be safely used on any thread.
*
* When sending a packet, the system will attempt to find the shortest path between the two nodes based on their
* element's position. Note that packet senders and receivers can have different locations from their associated
* element: the distance between the two will be added to the total packet's distance.
*
* Wired nodes also provide several convenience methods for interacting with a wired network. These should only ever
* be used on the main server thread.
*/
public interface IWiredNode extends IPacketNetwork
{
/**
* The associated element for this network node.
*
* @return This node's element.
*/
@Nonnull
IWiredElement getElement();
/**
* The network this node is currently connected to. Note that this may change
* after any network operation, so it should not be cached.
*
* This should only be used on the server thread.
*
* @return This node's network.
*/
@Nonnull
IWiredNetwork getNetwork();
/**
* Create a connection from this node to another.
*
* This should only be used on the server thread.
*
* @param node The other node to connect to.
* @return {@code true} if a connection was created or {@code false} if the connection already exists.
* @see IWiredNetwork#connect(IWiredNode, IWiredNode)
* @see IWiredNode#disconnectFrom(IWiredNode)
*/
default boolean connectTo( @Nonnull IWiredNode node )
{
return getNetwork().connect( this, node );
}
/**
* Destroy a connection between this node and another.
*
* This should only be used on the server thread.
*
* @param node The other node to disconnect from.
* @return {@code true} if a connection was destroyed or {@code false} if no connection exists.
* @throws IllegalArgumentException If {@code node} is not on the same network.
* @see IWiredNetwork#disconnect(IWiredNode, IWiredNode)
* @see IWiredNode#connectTo(IWiredNode)
*/
default boolean disconnectFrom( @Nonnull IWiredNode node )
{
return getNetwork().disconnect( this, node );
}
/**
* Sever all connections this node has, removing it from this network.
*
* This should only be used on the server thread. You should only call this on nodes
* that your network element owns.
*
* @return Whether this node was removed from the network. One cannot remove a node from a network where it is the
* only element.
* @throws IllegalArgumentException If the node is not in the network.
* @see IWiredNetwork#remove(IWiredNode)
*/
default boolean remove()
{
return getNetwork().remove( this );
}
/**
* Mark this node's peripherals as having changed.
*
* This should only be used on the server thread. You should only call this on nodes
* that your network element owns.
*
* @param peripherals The new peripherals for this node.
* @see IWiredNetwork#updatePeripherals(IWiredNode, Map)
*/
default void updatePeripherals( @Nonnull Map<String, IPeripheral> peripherals )
{
getNetwork().updatePeripherals( this, peripherals );
}
}

View File

@@ -0,0 +1,25 @@
package dan200.computercraft.api.network.wired;
import dan200.computercraft.api.network.IPacketSender;
import javax.annotation.Nonnull;
/**
* An object on a {@link IWiredNetwork} capable of sending packets.
*
* Unlike a regular {@link IPacketSender}, this must be associated with the node you are attempting to
* to send the packet from.
*/
public interface IWiredSender extends IPacketSender
{
/**
* The node in the network representing this object.
*
* This should be used as a proxy for the main network. One should send packets
* and register receivers through this object.
*
* @return The node for this element.
*/
@Nonnull
IWiredNode getNode();
}

View File

@@ -0,0 +1,10 @@
/*
* 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.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
@API( owner="ComputerCraft", provides="ComputerCraft|API|Network|Wired", apiVersion="${version}" )
package dan200.computercraft.api.network.wired;
import net.minecraftforge.fml.common.API;

View File

@@ -1,10 +1,10 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
@API( owner="ComputerCraft", provides="ComputerCraft|API", apiVersion="${version}" )
package dan200.computercraft.api;
import net.minecraftforge.fml.common.API;
import net.minecraftforge.fml.common.API;

View File

@@ -1,13 +1,20 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.peripheral;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.api.filesystem.IMount;
import dan200.computercraft.api.filesystem.IWritableMount;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.Map;
/**
* The interface passed to peripherals by computers or turtles, providing methods
@@ -16,87 +23,166 @@ import dan200.computercraft.api.filesystem.IWritableMount;
*/
public interface IComputerAccess
{
/**
* Mount a mount onto the computers' file system in a read only mode.<br>
* @param desiredLocation The location on the computercraft's file system where you would like the mount to be mounted.
* @param mount The mount object to mount on the computercraft. These can be obtained by calling ComputerCraftAPI.createSaveDirMount(), ComputerCraftAPI.createResourceMount() or by creating your own objects that implement the IMount interface.
* @return The location on the computercraft's file system where you the mount mounted, or null if there was already a file in the desired location. Store this value if you wish to unmount the mount later.
* @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String)
* @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String)
* @see #mountWritable(String, dan200.computercraft.api.filesystem.IWritableMount)
* @see #unmount(String)
* @see dan200.computercraft.api.filesystem.IMount
*/
public String mount( String desiredLocation, IMount mount );
/**
* Mount a mount onto the computer's file system in a read only mode.
*
* @param desiredLocation The location on the computer's file system where you would like the mount to be mounted.
* @param mount The mount object to mount on the computer.
* @return The location on the computer's file system where you the mount mounted, or {@code null} if there was already a
* file in the desired location. Store this value if you wish to unmount the mount later.
* @throws RuntimeException If the peripheral has been detached.
* @see ComputerCraftAPI#createSaveDirMount(World, String, long)
* @see ComputerCraftAPI#createResourceMount(Class, String, String)
* @see #mount(String, IMount, String)
* @see #mountWritable(String, IWritableMount)
* @see #unmount(String)
* @see IMount
*/
@Nullable
String mount( @Nonnull String desiredLocation, @Nonnull IMount mount );
/**
* TODO: Document me
* Mount a mount onto the computer's file system in a read only mode.
*
* @param desiredLocation The location on the computer's file system where you would like the mount to be mounted.
* @param mount The mount object to mount on the computer.
* @param driveName A custom name to give for this mount location, as returned by {@code fs.getDrive()}.
* @return The location on the computer's file system where you the mount mounted, or {@code null} if there was already a
* file in the desired location. Store this value if you wish to unmount the mount later.
* @throws RuntimeException If the peripheral has been detached.
* @see ComputerCraftAPI#createSaveDirMount(World, String, long)
* @see ComputerCraftAPI#createResourceMount(Class, String, String)
* @see #mount(String, IMount)
* @see #mountWritable(String, IWritableMount)
* @see #unmount(String)
* @see IMount
*/
public String mount( String desiredLocation, IMount mount, String driveName );
/**
* Mount a mount onto the computers' file system in a writable mode.<br>
* @param desiredLocation The location on the computercraft's file system where you would like the mount to be mounted.
* @param mount The mount object to mount on the computercraft. These can be obtained by calling ComputerCraftAPI.createSaveDirMount() or by creating your own objects that implement the IWritableMount interface.
* @return The location on the computercraft's file system where you the mount mounted, or null if there was already a file in the desired location. Store this value if you wish to unmount the mount later.
* @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String)
* @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String)
* @see #mount(String, IMount)
* @see #unmount(String)
* @see IMount
*/
public String mountWritable( String desiredLocation, IWritableMount mount );
@Nullable
String mount( @Nonnull String desiredLocation, @Nonnull IMount mount, @Nonnull String driveName );
/**
* TODO: Document me
* Mount a mount onto the computer's file system in a writable mode.
*
* @param desiredLocation The location on the computer's file system where you would like the mount to be mounted.
* @param mount The mount object to mount on the computer.
* @return The location on the computer's file system where you the mount mounted, or null if there was already a
* file in the desired location. Store this value if you wish to unmount the mount later.
* @throws RuntimeException If the peripheral has been detached.
* @see ComputerCraftAPI#createSaveDirMount(World, String, long)
* @see ComputerCraftAPI#createResourceMount(Class, String, String)
* @see #mount(String, IMount)
* @see #unmount(String)
* @see IMount
*/
public String mountWritable( String desiredLocation, IWritableMount mount, String driveName );
@Nullable
String mountWritable( @Nonnull String desiredLocation, @Nonnull IWritableMount mount );
/**
* Unmounts a directory previously mounted onto the computers file system by mount() or mountWritable().<br>
* When a directory is unmounted, it will disappear from the computers file system, and the user will no longer be able to
* access it. All directories mounted by a mount or mountWritable are automatically unmounted when the peripheral
* is attached if they have not been explicitly unmounted.
* @param location The desired location in the computers file system of the directory to unmount.
* This must be the location of a directory previously mounted by mount() or mountWritable(), as
* indicated by their return value.
* @see #mount(String, IMount)
* @see #mountWritable(String, IWritableMount)
*/
public void unmount( String location );
/**
* Returns the numerical ID of this computercraft.<br>
* This is the same number obtained by calling os.getComputerID() or running the "id" program from lua,
* and is guarunteed unique. This number will be positive.
* @return The identifier.
*/
public int getID();
/**
* Mount a mount onto the computer's file system in a writable mode.
*
* @param desiredLocation The location on the computer's file system where you would like the mount to be mounted.
* @param mount The mount object to mount on the computer.
* @param driveName A custom name to give for this mount location, as returned by {@code fs.getDrive()}.
* @return The location on the computer's file system where you the mount mounted, or null if there was already a
* file in the desired location. Store this value if you wish to unmount the mount later.
* @throws RuntimeException If the peripheral has been detached.
* @see ComputerCraftAPI#createSaveDirMount(World, String, long)
* @see ComputerCraftAPI#createResourceMount(Class, String, String)
* @see #mount(String, IMount)
* @see #unmount(String)
* @see IMount
*/
String mountWritable( @Nonnull String desiredLocation, @Nonnull IWritableMount mount, @Nonnull String driveName );
/**
* Causes an event to be raised on this computercraft, which the computercraft can respond to by calling
* os.pullEvent(). This can be used to notify the computercraft when things happen in the world or to
* this peripheral.
* @param event A string identifying the type of event that has occurred, this will be
* returned as the first value from os.pullEvent(). It is recommended that you
* you choose a name that is unique, and recognisable as originating from your
* peripheral. eg: If your peripheral type is "button", a suitable event would be
* "button_pressed".
* @param arguments In addition to a name, you may pass an array of extra arguments to the event, that will
* be supplied as extra return values to os.pullEvent(). Objects in the array will be converted
* to lua data types in the same fashion as the return values of IPeripheral.callMethod().<br>
* You may supply null to indicate that no arguments are to be supplied.
* @see dan200.computercraft.api.peripheral.IPeripheral#callMethod
*/
public void queueEvent( String event, Object[] arguments );
/**
* Unmounts a directory previously mounted onto the computers file system by {@link #mount(String, IMount)}
* or {@link #mountWritable(String, IWritableMount)}.
*
* When a directory is unmounted, it will disappear from the computers file system, and the user will no longer be
* able to access it. All directories mounted by a mount or mountWritable are automatically unmounted when the
* peripheral is attached if they have not been explicitly unmounted.
*
* Note that you cannot unmount another peripheral's mounts.
*
* @param location The desired location in the computers file system of the directory to unmount.
* This must be the location of a directory previously mounted by {@link #mount(String, IMount)} or
* {@link #mountWritable(String, IWritableMount)}, as indicated by their return value.
* @throws RuntimeException If the peripheral has been detached.
* @throws RuntimeException If the mount does not exist, or was mounted by another peripheral.
* @see #mount(String, IMount)
* @see #mountWritable(String, IWritableMount)
*/
void unmount( @Nullable String location );
/**
* Get a string, unique to the computercraft, by which the computercraft refers to this peripheral.
* For directly attached peripherals this will be "left","right","front","back",etc, but
* for peripherals attached remotely it will be different. It is good practice to supply
* this string when raising events to the computercraft, so that the computercraft knows from
* which peripheral the event came.
* @return A string unique to the computercraft, but not globally.
*/
public String getAttachmentName();
/**
* Returns the numerical ID of this computer.
*
* This is the same number obtained by calling {@code os.getComputerID()} or running the "id" program from lua,
* and is guaranteed unique. This number will be positive.
*
* @return The identifier.
*/
int getID();
/**
* Causes an event to be raised on this computer, which the computer can respond to by calling
* {@code os.pullEvent()}. This can be used to notify the computer when things happen in the world or to
* this peripheral.
*
* @param event A string identifying the type of event that has occurred, this will be
* returned as the first value from {@code os.pullEvent()}. It is recommended that you
* you choose a name that is unique, and recognisable as originating from your
* peripheral. eg: If your peripheral type is "button", a suitable event would be
* "button_pressed".
* @param arguments In addition to a name, you may pass an array of extra arguments to the event, that will
* be supplied as extra return values to os.pullEvent(). Objects in the array will be converted
* to lua data types in the same fashion as the return values of IPeripheral.callMethod().
*
* You may supply {@code null} to indicate that no arguments are to be supplied.
* @throws RuntimeException If the peripheral has been detached.
* @see dan200.computercraft.api.peripheral.IPeripheral#callMethod
*/
void queueEvent( @Nonnull String event, @Nullable Object[] arguments );
/**
* Get a string, unique to the computer, by which the computer refers to this peripheral.
* For directly attached peripherals this will be "left","right","front","back",etc, but
* for peripherals attached remotely it will be different. It is good practice to supply
* this string when raising events to the computer, so that the computer knows from
* which peripheral the event came.
*
* @return A string unique to the computer, but not globally.
* @throws RuntimeException If the peripheral has been detached.
*/
@Nonnull
String getAttachmentName();
/**
* Get a set of peripherals that this computer access can "see", along with their attachment name.
*
* This may include other peripherals on the wired network or peripherals on other sides of the computer.
*
* @return All reachable peripherals
* @see #getAttachmentName()
* @see #getAvailablePeripheral(String)
*/
@Nonnull
default Map<String, IPeripheral> getAvailablePeripherals()
{
return Collections.emptyMap();
}
/**
* Get a reachable peripheral with the given attachement name. This is a equivalent to
* {@link #getAvailablePeripherals()}{@code .get(name)}, though may be more performant.
*
* @param name The peripheral's attached name
* @return The reachable peripheral, or {@code null} if none can be found.
* @see #getAvailablePeripherals()
*/
@Nullable
default IPeripheral getAvailablePeripheral( @Nonnull String name )
{
return null;
}
}

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. 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.
*/
@@ -9,90 +9,131 @@ package dan200.computercraft.api.peripheral;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.LuaException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* The interface that defines a peripheral. See IPeripheralProvider for how to associate blocks with peripherals.
* The interface that defines a peripheral. See {@link IPeripheralProvider} for how to associate blocks with peripherals.
*/
public interface IPeripheral
{
/**
* Should return a string that uniquely identifies this type of peripheral.
* This can be queried from lua by calling peripheral.getType()
* @return A string identifying the type of peripheral.
*/
public String getType();
/**
* Should return an array of strings that identify the methods that this
* peripheral exposes to Lua. This will be called once before each attachment,
* and should not change when called multiple times.
* @return An array of strings representing method names.
* @see #callMethod
*/
public String[] getMethodNames();
/**
* This is called when a lua program on an attached computercraft calls peripheral.call() with
* one of the methods exposed by getMethodNames().<br>
* <br>
* Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe
* when interacting with minecraft objects.
* @param computer The interface to the computercraft that is making the call. Remember that multiple
* computers can be attached to a peripheral at once.
* @param context The context of the currently running lua thread. This can be used to wait for events
* or otherwise yield.
* @param method An integer identifying which of the methods from getMethodNames() the computercraft
* wishes to call. The integer indicates the index into the getMethodNames() table
* that corresponds to the string passed into peripheral.call()
* @param arguments An array of objects, representing the arguments passed into peripheral.call().<br>
* Lua values of type "string" will be represented by Object type String.<br>
* Lua values of type "number" will be represented by Object type Double.<br>
* Lua values of type "boolean" will be represented by Object type Boolean.<br>
* Lua values of any other type will be represented by a null object.<br>
* This array will be empty if no arguments are passed.
* @return An array of objects, representing values you wish to return to the lua program.<br>
* Integers, Doubles, Floats, Strings, Booleans and null be converted to their corresponding lua type.<br>
* All other types will be converted to nil.<br>
* You may return null to indicate no values should be returned.
* @throws Exception If you throw any exception from this function, a lua error will be raised with the
* same message as your exception. Use this to throw appropriate errors if the wrong
* arguments are supplied to your method.
* @see #getMethodNames
*/
public Object[] callMethod( IComputerAccess computer, ILuaContext context, int method, Object[] arguments ) throws LuaException, InterruptedException;
/**
* Is called when canAttachToSide has returned true, and a computercraft is attaching to the peripheral.
* This will occur when a peripheral is placed next to an active computercraft, when a computercraft is turned on next to a peripheral,
* or when a turtle travels into a square next to a peripheral.
* Between calls to attach() and detach(), the attached computercraft can make method calls on the peripheral using peripheral.call().
* This method can be used to keep track of which computers are attached to the peripheral, or to take action when attachment
* occurs.<br>
* <br>
* Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe
* when interacting with minecraft objects.
* @param computer The interface to the computercraft that is being attached. Remember that multiple
* computers can be attached to a peripheral at once.
* @see #detach
*/
public void attach( IComputerAccess computer );
/**
* Is called when a computercraft is detaching from the peripheral.
* This will occur when a computercraft shuts down, when the peripheral is removed while attached to computers,
* or when a turtle moves away from a square attached to a peripheral.
* This method can be used to keep track of which computers are attached to the peripheral, or to take action when detachment
* occurs.<br>
* <br>
* Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe
* when interacting with minecraft objects.
* @param computer The interface to the computercraft that is being detached. Remember that multiple
* computers can be attached to a peripheral at once.
* @see #detach
*/
public void detach( IComputerAccess computer );
/**
* Should return a string that uniquely identifies this type of peripheral.
* This can be queried from lua by calling {@code peripheral.getType()}
*
* @return A string identifying the type of peripheral.
*/
@Nonnull
String getType();
/**
* TODO: Document me
* Should return an array of strings that identify the methods that this
* peripheral exposes to Lua. This will be called once before each attachment,
* and should not change when called multiple times.
*
* @return An array of strings representing method names.
* @see #callMethod
*/
public boolean equals( IPeripheral other );
@Nonnull
String[] getMethodNames();
/**
* This is called when a lua program on an attached computer calls {@code peripheral.call()} with
* one of the methods exposed by {@link #getMethodNames()}.
*
* Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe
* when interacting with Minecraft objects.
*
* @param computer The interface to the computer that is making the call. Remember that multiple
* computers can be attached to a peripheral at once.
* @param context The context of the currently running lua thread. This can be used to wait for events
* or otherwise yield.
* @param method An integer identifying which of the methods from getMethodNames() the computercraft
* wishes to call. The integer indicates the index into the getMethodNames() table
* that corresponds to the string passed into peripheral.call()
* @param arguments An array of objects, representing the arguments passed into {@code peripheral.call()}.<br>
* Lua values of type "string" will be represented by Object type String.<br>
* Lua values of type "number" will be represented by Object type Double.<br>
* Lua values of type "boolean" will be represented by Object type Boolean.<br>
* Lua values of type "table" will be represented by Object type Map.<br>
* Lua values of any other type will be represented by a null object.<br>
* This array will be empty if no arguments are passed.
* @return An array of objects, representing values you wish to return to the lua program. Integers, Doubles, Floats,
* Strings, Booleans, Maps and ILuaObject and null be converted to their corresponding lua type. All other types
* will be converted to nil.
*
* You may return null to indicate no values should be returned.
* @throws LuaException If you throw any exception from this function, a lua error will be raised with the
* same message as your exception. Use this to throw appropriate errors if the wrong
* arguments are supplied to your method.
* @throws InterruptedException If the user shuts down or reboots the computer the coroutine is suspended,
* InterruptedException will be thrown. This exception must not be caught or
* intercepted, or the computer will leak memory and end up in a broken state.
* @see #getMethodNames
*/
@Nullable
Object[] callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaContext context, int method, @Nonnull Object[] arguments ) throws LuaException, InterruptedException;
/**
* Is called when canAttachToSide has returned true, and a computer is attaching to the peripheral.
*
* This will occur when a peripheral is placed next to an active computer, when a computer is turned on next to a
* peripheral, or when a turtle travels into a square next to a peripheral.
*
* Between calls to attach() and detach(), the attached computer can make method calls on the peripheral using
* {@code peripheral.call()}. This method can be used to keep track of which computers are attached to the
* peripheral, or to take action when attachment occurs.
*
* Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe
* when interacting with Minecraft objects.
*
* @param computer The interface to the computer that is being attached. Remember that multiple
* computers can be attached to a peripheral at once.
* @see #detach
*/
default void attach( @Nonnull IComputerAccess computer )
{
}
/**
* Is called when a computer is detaching from the peripheral.
*
* This will occur when a computer shuts down, when the peripheral is removed while attached to computers,
* or when a turtle moves away from a square attached to a peripheral. This method can be used to keep track of
* which computers are attached to the peripheral, or to take action when detachment
* occurs.
*
* Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe
* when interacting with Minecraft objects.
*
* @param computer The interface to the computer that is being detached. Remember that multiple
* computers can be attached to a peripheral at once.
* @see #detach
*/
default void detach( @Nonnull IComputerAccess computer )
{
}
/**
* Get the object that this peripheral provides methods for. This will generally be the tile entity
* or block, but may be an inventory, entity, etc...
*
* @return The object this peripheral targets
*/
@Nonnull
default Object getTarget()
{
return this;
}
/**
* Determine whether this peripheral is equivalent to another one.
*
* The minimal example should at least check whether they are the same object. However, you may wish to check if
* they point to the same block or tile entity.
*
* @param other The peripheral to compare against. This may be {@code null}.
* @return Whether these peripherals are equivalent.
*/
boolean equals( @Nullable IPeripheral other );
}

View File

@@ -1,25 +1,35 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.peripheral;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* This interface is used to create peripheral implementations for blocks
* This interface is used to create peripheral implementations for blocks.
*
* @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider)
*/
@FunctionalInterface
public interface IPeripheralProvider
{
/**
* Produce an peripheral implementation from a block location.
*
* @param world The world the block is in.
* @param pos The position the block is at.
* @param side The side to get the peripheral from.
* @return A peripheral, or {@code null} if there is not a peripheral here you'd like to handle.
* @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider)
* @return a peripheral, or null if there is not a peripheral here you'd like to handle.
*/
public IPeripheral getPeripheral( World world, BlockPos pos, EnumFacing side );
@Nullable
IPeripheral getPeripheral( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull EnumFacing side );
}

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. 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-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. 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.
*/
@@ -9,12 +9,34 @@ package dan200.computercraft.api.permissions;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
/**
* This interface is used to restrict where turtles can move or build
* This interface is used to restrict where turtles can move or build.
*
* Turtles will call these methods before attempting to perform an action, allowing them to be cancelled.
*
* @see dan200.computercraft.api.ComputerCraftAPI#registerPermissionProvider(ITurtlePermissionProvider)
*/
public interface ITurtlePermissionProvider
{
public boolean isBlockEnterable( World world, BlockPos pos );
public boolean isBlockEditable( World world, BlockPos pos );
/**
* Determine whether a block can be entered by a turtle.
*
* @param world The world the block exists in
* @param pos The location of the block.
* @return Whether the turtle can move into this block.
*/
boolean isBlockEnterable( @Nonnull World world, @Nonnull BlockPos pos );
/**
* Determine whether a block can be modified by a turtle.
*
* This includes breaking and placing blocks.
*
* @param world The world the block exists in
* @param pos The location of the block.
* @return Whether the turtle can modify this block.
*/
boolean isBlockEditable( @Nonnull World world, @Nonnull BlockPos pos );
}

View File

@@ -1,10 +1,10 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
@API( owner="ComputerCraft", provides="ComputerCraft|API|Permissions", apiVersion="${version}" )
package dan200.computercraft.api.permissions;
import net.minecraftforge.fml.common.API;
import net.minecraftforge.fml.common.API;

View File

@@ -0,0 +1,91 @@
package dan200.computercraft.api.pocket;
import dan200.computercraft.api.peripheral.IPeripheral;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Map;
/**
* Wrapper class for pocket computers
*/
public interface IPocketAccess
{
/**
* Gets the entity holding this item.
*
* @return The holding entity. This may be {@code null}.
*/
@Nullable
Entity getEntity();
/**
* Get the colour of this pocket computer as a RGB number.
*
* @return The colour this pocket computer is. This will be a RGB colour between {@code 0x000000} and
* {@code 0xFFFFFF} or -1 if it has no colour.
* @see #setColour(int)
*/
int getColour();
/**
* Set the colour of the pocket computer to a RGB number.
*
* @param colour The colour this pocket computer should be changed to. This should be a RGB colour between
* {@code 0x000000} and {@code 0xFFFFFF} or -1 to reset to the default colour.
* @see #getColour()
*/
void setColour( int colour );
/**
* Get the colour of this pocket computer's light as a RGB number.
*
* @return The colour this light is. This will be a RGB colour between {@code 0x000000} and {@code 0xFFFFFF} or
* -1 if it has no colour.
* @see #setLight(int)
*/
int getLight();
/**
* Set the colour of the pocket computer's light to a RGB number.
*
* @param colour The colour this modem's light will be changed to. This should be a RGB colour between
* {@code 0x000000} and {@code 0xFFFFFF} or -1 to reset to the default colour.
* @see #getLight()
*/
void setLight( int colour );
/**
* Get the upgrade-specific NBT.
*
* This is persisted between computer reboots and chunk loads.
*
* @return The upgrade's NBT.
* @see #updateUpgradeNBTData()
*/
@Nonnull
NBTTagCompound getUpgradeNBTData();
/**
* Mark the upgrade-specific NBT as dirty.
*
* @see #getUpgradeNBTData()
*/
void updateUpgradeNBTData();
/**
* Remove the current peripheral and create a new one. You may wish to do this if the methods available change.
*/
void invalidatePeripheral();
/**
* Get a list of all upgrades for the pocket computer.
*
* @return A collection of all upgrade names.
*/
@Nonnull
Map<ResourceLocation, IPeripheral> getUpgrades();
}

View File

@@ -0,0 +1,96 @@
package dan200.computercraft.api.pocket;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.api.turtle.ITurtleUpgrade;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Additional peripherals for pocket computers.
*
* This is similar to {@link dan200.computercraft.api.turtle.ITurtleUpgrade}.
*/
public interface IPocketUpgrade
{
/**
* Gets a unique identifier representing this type of turtle upgrade. eg: "computercraft:wireless_modem" or
* "my_mod:my_upgrade".
*
* You should use a unique resource domain to ensure this upgrade is uniquely identified. The upgrade will fail
* registration if an already used ID is specified.
*
* @return The upgrade's id.
* @see IPocketUpgrade#getUpgradeID()
* @see ComputerCraftAPI#registerPocketUpgrade(IPocketUpgrade)
*/
@Nonnull
ResourceLocation getUpgradeID();
/**
* Return an unlocalised string to describe the type of pocket computer this upgrade provides.
*
* An example of a built-in adjectives is "Wireless" - this is converted to "Wireless Pocket Computer".
*
* @return The unlocalised adjective.
* @see ITurtleUpgrade#getUnlocalisedAdjective()
*/
@Nonnull
String getUnlocalisedAdjective();
/**
* Return an item stack representing the type of item that a pocket computer must be crafted with to create a
* pocket computer which holds this upgrade. This item stack is also used to determine the upgrade given by
* {@code pocket.equip()}/{@code pocket.unequip()}.
*
* @return The item stack used for crafting. This can be {@link ItemStack#EMPTY} if crafting is disabled.
*/
@Nonnull
ItemStack getCraftingItem();
/**
* Creates a peripheral for the pocket computer.
*
* The peripheral created will be stored for the lifetime of the upgrade, will be passed an argument to
* {@link #update(IPocketAccess, IPeripheral)} and will be attached, detached and have methods called in the same
* manner as an ordinary peripheral.
*
* @param access The access object for the pocket item stack.
* @return The newly created peripheral.
* @see #update(IPocketAccess, IPeripheral)
*/
@Nullable
IPeripheral createPeripheral( @Nonnull IPocketAccess access );
/**
* Called when the pocket computer item stack updates.
*
* @param access The access object for the pocket item stack.
* @param peripheral The peripheral for this upgrade.
* @see #createPeripheral(IPocketAccess)
*/
default void update( @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral )
{
}
/**
* Called when the pocket computer is right clicked.
*
* @param world The world the computer is in.
* @param access The access object for the pocket item stack.
* @param peripheral The peripheral for this upgrade.
* @return {@code true} to stop the GUI from opening, otherwise false. You should always provide some code path
* which returns {@code false}, such as requiring the player to be sneaking - otherwise they will be unable to
* access the GUI.
* @see #createPeripheral(IPocketAccess)
*/
default boolean onRightClick( @Nonnull World world, @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral )
{
return false;
}
}

View File

@@ -1,25 +1,34 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.redstone;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
/**
* This interface is used to provide bundled redstone output for blocks
* This interface is used to provide bundled redstone output for blocks.
*
* @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider)
*/
@FunctionalInterface
public interface IBundledRedstoneProvider
{
/**
* Produce an bundled redstone output from a block location.
*
* @param world The world this block is in.
* @param pos The position this block is at.
* @param side The side to extract the bundled redstone output from.
* @return A number in the range 0-65535 to indicate this block is providing output, or -1 if you do not wish to
* handle this block.
* @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider)
* @return a number in the range 0-65535 to indicate this block is providing output, or -1 if you do not wish to handle this block
*/
public int getBundledRedstoneOutput( World world, BlockPos pos, EnumFacing side );
int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull EnumFacing side );
}

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. 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,126 +1,223 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle;
import com.mojang.authlib.GameProfile;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.peripheral.IPeripheral;
import net.minecraft.inventory.IInventory;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.items.IItemHandlerModifiable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* The interface passed to turtle by turtles, providing methods that they can call.
* This should not be implemented by your classes. Do not interact with turtles except via this interface and ITurtleUpgrade.
*
* This should not be implemented by your classes. Do not interact with turtles except via this interface and
* {@link ITurtleUpgrade}.
*/
public interface ITurtleAccess
{
/**
* Returns the world in which the turtle resides.
* @return the world in which the turtle resides.
*/
public World getWorld();
/**
* Returns a vector containing the integer co-ordinates at which the turtle resides.
* @return a vector containing the integer co-ordinates at which the turtle resides.
*/
public BlockPos getPosition();
/**
* TODO: Document me
* Returns the world in which the turtle resides.
*
* @return the world in which the turtle resides.
*/
public boolean teleportTo( World world, BlockPos pos );
/**
* Returns a vector containing the floating point co-ordinates at which the turtle is rendered.
* This will shift when the turtle is moving.
* @param f The subframe fraction
* @return a vector containing the floating point co-ordinates at which the turtle resides.
*/
public Vec3d getVisualPosition( float f );
@Nonnull
World getWorld();
/**
* TODO: Document me
* Returns a vector containing the integer co-ordinates at which the turtle resides.
*
* @return a vector containing the integer co-ordinates at which the turtle resides.
*/
public float getVisualYaw( float f );
/**
* Returns the world direction the turtle is currently facing.
* @return the world direction the turtle is currently facing.
*/
public EnumFacing getDirection();
@Nonnull
BlockPos getPosition();
/**
* TODO: Document me
* Attempt to move this turtle to a new position.
*
* This will preserve the turtle's internal state, such as it's inventory, computer and upgrades. It should
* be used before playing a movement animation using {@link #playAnimation(TurtleAnimation)}.
*
* @param world The new world to move it to
* @param pos The new position to move it to.
* @return Whether the movement was successful. It may fail if the block was not loaded or the block placement
* was cancelled. Note this will not check
* {@link dan200.computercraft.api.permissions.ITurtlePermissionProvider#isBlockEnterable(World, BlockPos)}.
* @throws UnsupportedOperationException When attempting to teleport on the client side.
*/
public void setDirection( EnumFacing dir );
boolean teleportTo( @Nonnull World world, @Nonnull BlockPos pos );
/**
* TODO: Document me
* Returns a vector containing the floating point co-ordinates at which the turtle is rendered.
* This will shift when the turtle is moving.
*
* @param f The subframe fraction.
* @return A vector containing the floating point co-ordinates at which the turtle resides.
* @see #getVisualYaw(float)
*/
public int getSelectedSlot();
@Nonnull
Vec3d getVisualPosition( float f );
/**
* TODO: Document me
* Returns the yaw the turtle is facing when it is rendered.
*
* @param f The subframe fraction.
* @return The yaw the turtle is facing.
* @see #getVisualPosition(float)
*/
public void setSelectedSlot( int slot );
float getVisualYaw( float f );
/**
* Sets the colour of the turtle, as if the player had dyed it with a dye item.
* @param dyeColour 0-15 to dye the turtle one of the 16 standard minecraft colours, or -1 to remove the dye from the turtle.
* Returns the world direction the turtle is currently facing.
*
* @return The world direction the turtle is currently facing.
* @see #setDirection(EnumFacing)
*/
public void setDyeColour( int dyeColour );
@Nonnull
EnumFacing getDirection();
/**
* Gets the colour the turtle has been dyed.
* @return 0-15 if the turtle has been dyed one of the 16 standard minecraft colours, -1 if the turtle is clean.
* Set the direction the turtle is facing. Note that this will not play a rotation animation, you will also need to
* call {@link #playAnimation(TurtleAnimation)} to do so.
*
* @param dir The new direction to set. This should be on either the x or z axis (so north, south, east or west).
* @see #getDirection()
*/
public int getDyeColour();
void setDirection( @Nonnull EnumFacing dir );
/**
* TODO: Document me
* Get the currently selected slot in the turtle's inventory.
*
* @return An integer representing the current slot.
* @see #getInventory()
* @see #setSelectedSlot(int)
*/
public IInventory getInventory();
int getSelectedSlot();
/**
* TODO: Document me
* Set the currently selected slot in the turtle's inventory.
*
* @param slot The slot to set. This must be greater or equal to 0 and less than the inventory size. Otherwise no
* action will be taken.
* @throws UnsupportedOperationException When attempting to change the slot on the client side.
* @see #getInventory()
* @see #getSelectedSlot()
*/
public boolean isFuelNeeded();
/**
* TODO: Document me
*/
public int getFuelLevel();
void setSelectedSlot( int slot );
/**
* TODO: Document me
* Set the colour of the turtle to a RGB number.
*
* @param colour The colour this turtle should be changed to. This should be a RGB colour between {@code 0x000000}
* and {@code 0xFFFFFF} or -1 to reset to the default colour.
* @see #getColour()
*/
public void setFuelLevel( int fuel );
void setColour( int colour );
/**
* TODO: Document me
* Get the colour of this turtle as a RGB number.
*
* @return The colour this turtle is. This will be a RGB colour between {@code 0x000000} and {@code 0xFFFFFF} or
* -1 if it has no colour.
* @see #setColour(int)
*/
public int getFuelLimit();
int getColour();
/**
* Removes some fuel from the turtles fuel supply. Negative numbers can be passed in to INCREASE the fuel level of the turtle.
* @return Whether the turtle was able to consume the ammount of fuel specified. Will return false if you supply a number
* greater than the current fuel level of the turtle.
*/
public boolean consumeFuel( int fuel );
/**
* TODO: Document me
* Get the player who owns this turtle, namely whoever placed it.
*
* @return This turtle's owner.
*/
public void addFuel( int fuel );
@Nonnull
GameProfile getOwningPlayer();
/**
* Get the inventory of this turtle
*
* @return This turtle's inventory
* @see #getItemHandler()
*/
@Nonnull
IInventory getInventory();
/**
* Get the inventory of this turtle as an {@link IItemHandlerModifiable}.
*
* @return This turtle's inventory
* @see #getInventory()
* @see IItemHandlerModifiable
* @see net.minecraftforge.items.CapabilityItemHandler#ITEM_HANDLER_CAPABILITY
*/
@Nonnull
IItemHandlerModifiable getItemHandler();
/**
* Determine whether this turtle will require fuel when performing actions.
*
* @return Whether this turtle needs fuel.
* @see #getFuelLevel()
* @see #setFuelLevel(int)
*/
boolean isFuelNeeded();
/**
* Get the current fuel level of this turtle.
*
* @return The turtle's current fuel level.
* @see #isFuelNeeded()
* @see #setFuelLevel(int)
*/
int getFuelLevel();
/**
* Set the fuel level to a new value. It is generally preferred to use {@link #consumeFuel(int)}} or {@link #addFuel(int)}
* instead.
*
* @param fuel The new amount of fuel. This must be between 0 and the fuel limit.
* @see #getFuelLevel()
* @see #getFuelLimit()
* @see #addFuel(int)
* @see #consumeFuel(int)
*/
void setFuelLevel( int fuel );
/**
* Get the maximum amount of fuel a turtle can hold.
*
* @return The turtle's fuel limit.
*/
int getFuelLimit();
/**
* Removes some fuel from the turtles fuel supply. Negative numbers can be passed in to INCREASE the fuel level of the turtle.
*
* @param fuel The amount of fuel to consume.
* @return Whether the turtle was able to consume the amount of fuel specified. Will return false if you supply a number
* greater than the current fuel level of the turtle. No fuel will be consumed if {@code false} is returned.
* @throws UnsupportedOperationException When attempting to consume fuel on the client side.
*/
boolean consumeFuel( int fuel );
/**
* Increase the turtle's fuel level by the given amount.
*
* @param fuel The amount to refuel with.
* @throws UnsupportedOperationException When attempting to refuel on the client side.
*/
void addFuel( int fuel );
/**
* Adds a custom command to the turtles command queue. Unlike peripheral methods, these custom commands will be executed
@@ -128,42 +225,80 @@ public interface ITurtleAccess
* with the turtles standard movement and tool commands. An issued command will return an unique integer, which will
* be supplied as a parameter to a "turtle_response" event issued to the turtle after the command has completed. Look at the
* lua source code for "rom/apis/turtle" for how to build a lua wrapper around this functionality.
* @param command an object which will execute the custom command when its point in the queue is reached
* @return the objects the command returned when executed. you should probably return these to the player
*
* @param context The Lua context to pull events from.
* @param command An object which will execute the custom command when its point in the queue is reached
* @return The objects the command returned when executed. you should probably return these to the player
* unchanged if called from a peripheral method.
* @throws UnsupportedOperationException When attempting to execute a command on the client side.
* @throws LuaException If the user presses CTRL+T to terminate the current program while {@code executeCommand()} is
* waiting for an event, a "Terminated" exception will be thrown here.
* @throws InterruptedException If the user shuts down or reboots the computer while pullEvent() is waiting for an
* event, InterruptedException will be thrown. This exception must not be caught or
* intercepted, or the computer will leak memory and end up in a broken state.
* @see ITurtleCommand
* @see ILuaContext#pullEvent(String)
*/
public Object[] executeCommand( ILuaContext context, ITurtleCommand command ) throws LuaException, InterruptedException;
@Nonnull
Object[] executeCommand( @Nonnull ILuaContext context, @Nonnull ITurtleCommand command ) throws LuaException, InterruptedException;
/**
* TODO: Document me
* Start playing a specific animation. This will prevent other turtle commands from executing until
* it is finished.
*
* @param animation The animation to play.
* @throws UnsupportedOperationException When attempting to execute play an animation on the client side.
* @see TurtleAnimation
*/
public void playAnimation( TurtleAnimation animation );
/**
* Returns the turtle on the specified side of the turtle, if there is one.
* @return the turtle on the specified side of the turtle, if there is one.
*/
public ITurtleUpgrade getUpgrade( TurtleSide side );
void playAnimation( @Nonnull TurtleAnimation animation );
/**
* TODO: Document me
* Returns the turtle on the specified side of the turtle, if there is one.
*
* @param side The side to get the upgrade from.
* @return The upgrade on the specified side of the turtle, if there is one.
* @see #setUpgrade(TurtleSide, ITurtleUpgrade)
*/
public void setUpgrade( TurtleSide side, ITurtleUpgrade upgrade );
/**
* Returns the peripheral created by the upgrade on the specified side of the turtle, if there is one.
* @return the peripheral created by the upgrade on the specified side of the turtle, if there is one.
*/
public IPeripheral getPeripheral( TurtleSide side );
@Nullable
ITurtleUpgrade getUpgrade( @Nonnull TurtleSide side );
/**
* TODO: Document me
* Set the upgrade for a given side, resetting peripherals and clearing upgrade specific data.
*
* @param side The side to set the upgrade on.
* @param upgrade The upgrade to set, may be {@code null} to clear.
* @see #getUpgrade(TurtleSide)
*/
public NBTTagCompound getUpgradeNBTData( TurtleSide side );
void setUpgrade( @Nonnull TurtleSide side, @Nullable ITurtleUpgrade upgrade );
/**
* TODO: Document me
* Returns the peripheral created by the upgrade on the specified side of the turtle, if there is one.
*
* @param side The side to get the peripheral from.
* @return The peripheral created by the upgrade on the specified side of the turtle, {@code null} if none exists.
*/
public void updateUpgradeNBTData( TurtleSide side );
@Nullable
IPeripheral getPeripheral( @Nonnull TurtleSide side );
/**
* Get an upgrade-specific NBT compound, which can be used to store arbitrary data.
*
* This will be persisted across turtle restarts and chunk loads, as well as being synced to the client. You must
* call {@link #updateUpgradeNBTData(TurtleSide)} after modifying it.
*
* @param side The side to get the upgrade data for.
* @return The upgrade-specific data.
* @see #updateUpgradeNBTData(TurtleSide)
*/
@Nonnull
NBTTagCompound getUpgradeNBTData( @Nullable TurtleSide side );
/**
* Mark the upgrade-specific data as dirty on a specific side. This is required for the data to be synced to the
* client and persisted.
*
* @param side The side to mark dirty.
* @see #updateUpgradeNBTData(TurtleSide)
*/
void updateUpgradeNBTData( @Nonnull TurtleSide side );
}

View File

@@ -1,25 +1,36 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle;
import dan200.computercraft.api.lua.ILuaContext;
import javax.annotation.Nonnull;
/**
* An interface for objects executing custom turtle commands, used with ITurtleAccess.issueCommand
* @see ITurtleAccess#executeCommand(dan200.computercraft.api.lua.ILuaContext,ITurtleCommand)
* An interface for objects executing custom turtle commands, used with {@link ITurtleAccess#executeCommand(ILuaContext, ITurtleCommand)}.
*
* @see ITurtleAccess#executeCommand(ILuaContext, ITurtleCommand)
*/
@FunctionalInterface
public interface ITurtleCommand
{
/**
* Will be called by the turtle on the main thread when it is time to execute the custom command.
* The handler should either perform the work of the command, and return success, or return
* failure with an error message to indicate the command cannot be executed at this time.
* @param turtle access to the turtle for whom the command was issued
* @return TurtleCommandResult.success() or TurtleCommandResult.failure( errorMessage )
* @see ITurtleAccess#executeCommand(dan200.computercraft.api.lua.ILuaContext,ITurtleCommand)
* @see dan200.computercraft.api.turtle.TurtleCommandResult
*/
public TurtleCommandResult execute( ITurtleAccess turtle );
/**
* Will be called by the turtle on the main thread when it is time to execute the custom command.
*
* The handler should either perform the work of the command, and return success, or return
* failure with an error message to indicate the command cannot be executed at this time.
*
* @param turtle Access to the turtle for whom the command was issued.
* @return A result, indicating whether this action succeeded or not.
* @see ITurtleAccess#executeCommand(ILuaContext, ITurtleCommand)
* @see TurtleCommandResult#success()
* @see TurtleCommandResult#failure(String)
* @see TurtleCommandResult
*/
@Nonnull
TurtleCommandResult execute( @Nonnull ITurtleAccess turtle );
}

View File

@@ -1,108 +1,149 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.api.turtle.event.TurtleAttackEvent;
import dan200.computercraft.api.turtle.event.TurtleBlockEvent;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.entity.player.AttackEntityEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.vecmath.Matrix4f;
/**
* The primary interface for defining an update for Turtles. A turtle update
* can either be a new tool, or a new peripheral.
* @see dan200.computercraft.api.ComputerCraftAPI#registerTurtleUpgrade( dan200.computercraft.api.turtle.ITurtleUpgrade )
*
* @see ComputerCraftAPI#registerTurtleUpgrade(ITurtleUpgrade)
*/
public interface ITurtleUpgrade
{
/**
* Gets a unique identifier representing this type of turtle upgrade. eg: "computercraft:wireless_modem" or "my_mod:my_upgrade".
* You should use a unique resource domain to ensure this upgrade is uniquely identified.
/**
* Gets a unique identifier representing this type of turtle upgrade. eg: "computercraft:wireless_modem" or "my_mod:my_upgrade".
* You should use a unique resource domain to ensure this upgrade is uniquely identified.
* The turtle will fail registration if an already used ID is specified.
* @see dan200.computercraft.api.ComputerCraftAPI#registerTurtleUpgrade( dan200.computercraft.api.turtle.ITurtleUpgrade )
*/
public ResourceLocation getUpgradeID();
*
* @return The unique ID for this upgrade.
* @see ComputerCraftAPI#registerTurtleUpgrade(ITurtleUpgrade)
*/
@Nonnull
ResourceLocation getUpgradeID();
/**
* Gets a numerical identifier representing this type of turtle upgrade,
* for backwards compatibility with pre-1.76 worlds. If your upgrade was
* not released for older ComputerCraft versions, you can return -1 here.
* The turtle will fail registration if an already used positive ID is specified.
* @see dan200.computercraft.api.ComputerCraftAPI#registerTurtleUpgrade( dan200.computercraft.api.turtle.ITurtleUpgrade )
*
* @return The legacy ID, or -1 if is needed.
* @see ComputerCraftAPI#registerTurtleUpgrade(ITurtleUpgrade)
*/
public int getLegacyUpgradeID();
int getLegacyUpgradeID();
/**
* Return a String to describe this type of turtle in turtle item names.
* Examples of built-in adjectives are "Wireless", "Mining" and "Crafty".
*/
public String getUnlocalisedAdjective();
/**
* Return whether this turtle adds a tool or a peripheral to the turtle.
* @see TurtleUpgradeType for the differences between the two.
*/
public TurtleUpgradeType getType();
/**
* Return an item stack representing the type of item that a turtle must be crafted
* with to create a turtle which holds this upgrade. This item stack is also used
* to determine the upgrade given by turtle.equip()
*/
public ItemStack getCraftingItem();
* Return an unlocalised string to describe this type of turtle in turtle item names.
*
* Examples of built-in adjectives are "Wireless", "Mining" and "Crafty".
*
* @return The localisation key for this upgrade's adjective.
*/
@Nonnull
String getUnlocalisedAdjective();
/**
* Will only be called for peripheral upgrades. Creates a peripheral for a turtle
* being placed using this upgrade. The peripheral created will be stored
* for the lifetime of the upgrade, will have update() called once-per-tick, and will be
* attached, detached and have methods called in the same manner as a Computer peripheral.
*
* Return whether this turtle adds a tool or a peripheral to the turtle.
*
* @return The type of upgrade this is.
* @see TurtleUpgradeType for the differences between them.
*/
@Nonnull
TurtleUpgradeType getType();
/**
* Return an item stack representing the type of item that a turtle must be crafted
* with to create a turtle which holds this upgrade. This item stack is also used
* to determine the upgrade given by {@code turtle.equip()}
*
* @return The item stack to craft with, or {@link ItemStack#EMPTY} if it cannot be crafted.
*/
@Nonnull
ItemStack getCraftingItem();
/**
* Will only be called for peripheral upgrades. Creates a peripheral for a turtle being placed using this upgrade.
*
* The peripheral created will be stored for the lifetime of the upgrade and will be passed as an argument to
* {@link #update(ITurtleAccess, TurtleSide)}. It will be attached, detached and have methods called in the same
* manner as a Computer peripheral.
*
* @param turtle Access to the turtle that the peripheral is being created for.
* @param side Which side of the turtle (left or right) that the upgrade resides on.
* @return The newly created peripheral. You may return null if this upgrade is a Tool
* and this method is not expected to be called.
*/
public IPeripheral createPeripheral( ITurtleAccess turtle, TurtleSide side );
* @param side Which side of the turtle (left or right) that the upgrade resides on.
* @return The newly created peripheral. You may return {@code null} if this upgrade is a Tool
* and this method is not expected to be called.
*/
@Nullable
IPeripheral createPeripheral( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side );
/**
* Will only be called for Tool turtle. Called when turtle.dig() or turtle.attack() is called
* by the turtle, and the tool is required to do some work.
* @param turtle Access to the turtle that the tool resides on.
* @param side Which side of the turtle (left or right) the tool resides on.
* @param verb Which action (dig or attack) the turtle is being called on to perform.
* @param direction Which world direction the action should be performed in, relative to the turtles
* position. This will either be up, down, or the direction the turtle is facing, depending on
* whether dig, digUp or digDown was called.
* @return Whether the turtle was able to perform the action, and hence whether the turtle.dig()
* or turtle.attack() lua method should return true. If true is returned, the tool will perform
* a swinging animation. You may return null if this turtle is a Peripheral
* and this method is not expected to be called.
*/
public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, TurtleVerb verb, EnumFacing direction );
/**
* Will only be called for Tool turtle. Called when turtle.dig() or turtle.attack() is called
* by the turtle, and the tool is required to do some work.
*
* Conforming implementations should fire {@link BlockEvent.BreakEvent} and {@link TurtleBlockEvent.Dig}for digging,
* {@link AttackEntityEvent} and {@link TurtleAttackEvent} for attacking.
*
* @param turtle Access to the turtle that the tool resides on.
* @param side Which side of the turtle (left or right) the tool resides on.
* @param verb Which action (dig or attack) the turtle is being called on to perform.
* @param direction Which world direction the action should be performed in, relative to the turtles
* position. This will either be up, down, or the direction the turtle is facing, depending on
* whether dig, digUp or digDown was called.
* @return Whether the turtle was able to perform the action, and hence whether the {@code turtle.dig()}
* or {@code turtle.attack()} lua method should return true. If true is returned, the tool will perform
* a swinging animation. You may return {@code null} if this turtle is a Peripheral and this method is not expected
* to be called.
*/
@Nonnull
TurtleCommandResult useTool( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side, @Nonnull TurtleVerb verb, @Nonnull EnumFacing direction );
/**
* Called to obtain the model to be used when rendering a turtle peripheral.
*
* This can be obtained from {@link net.minecraft.client.renderer.ItemModelMesher#getItemModel(ItemStack)},
* {@link net.minecraft.client.renderer.block.model.ModelManager#getModel(ModelResourceLocation)} or any other
* source.
*
* @param turtle Access to the turtle that the upgrade resides on. This will be null when getting item models!
* @param side Which side of the turtle (left or right) the upgrade resides on.
* @return The model that you wish to be used to render your upgrade, and a transformation to apply to it. Returning a transformation of null has the same effect as the identify matrix.
* @param side Which side of the turtle (left or right) the upgrade resides on.
* @return The model that you wish to be used to render your upgrade, and a transformation to apply to it. Returning
* a transformation of {@code null} has the same effect as the identify matrix.
*/
@SideOnly( Side.CLIENT )
public Pair<IBakedModel, Matrix4f> getModel( ITurtleAccess turtle, TurtleSide side );
@SideOnly(Side.CLIENT)
@Nonnull
Pair<IBakedModel, Matrix4f> getModel( @Nullable ITurtleAccess turtle, @Nonnull TurtleSide side );
/**
* Called once per tick for each turtle which has the upgrade equipped.
*
* @param turtle Access to the turtle that the upgrade resides on.
* @param side Which side of the turtle (left or right) the upgrade resides on.
* @param side Which side of the turtle (left or right) the upgrade resides on.
*/
public void update( ITurtleAccess turtle, TurtleSide side );
default void update( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side )
{
}
}

View File

@@ -1,22 +1,87 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle;
/**
* An animation a turtle will play between executing commands.
*
* Each animation takes 8 ticks to complete unless otherwise specified.
*
* @see ITurtleAccess#playAnimation(TurtleAnimation)
*/
public enum TurtleAnimation
{
/**
* An animation which does nothing. This takes no time to complete.
*
* @see #Wait
* @see #ShortWait
*/
None,
/**
* Make the turtle move forward. Note that the animation starts from the block <em>behind</em> it, and
* moves into this one.
*/
MoveForward,
/**
* Make the turtle move backwards. Note that the animation starts from the block <em>in front</em> it, and
* moves into this one.
*/
MoveBack,
/**
* Make the turtle move backwards. Note that the animation starts from the block <em>above</em> it, and
* moves into this one.
*/
MoveUp,
/**
* Make the turtle move backwards. Note that the animation starts from the block <em>below</em> it, and
* moves into this one.
*/
MoveDown,
/**
* Turn the turtle to the left. Note that the animation starts with the turtle facing <em>right</em>, and
* the turtle turns to face in the current direction.
*/
TurnLeft,
/**
* Turn the turtle to the left. Note that the animation starts with the turtle facing <em>right</em>, and
* the turtle turns to face in the current direction.
*/
TurnRight,
/**
* Swing the tool on the left.
*/
SwingLeftTool,
/**
* Swing the tool on the right.
*/
SwingRightTool,
/**
* Wait until the animation has finished, performing no movement.
*
* @see #ShortWait
* @see #None
*/
Wait,
/**
* Wait until the animation has finished, performing no movement. This takes 4 ticks to complete.
*
* @see #Wait
* @see #None
*/
ShortWait,
}

View File

@@ -1,22 +1,46 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle;
import net.minecraft.util.EnumFacing;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Used to indicate the result of executing a turtle command.
*
* @see ITurtleCommand#execute(ITurtleAccess)
* @see ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, EnumFacing)
*/
public final class TurtleCommandResult
{
private static final TurtleCommandResult s_success = new TurtleCommandResult( true, null, null );
private static final TurtleCommandResult s_emptyFailure = new TurtleCommandResult( false, null, null );
/**
* Create a successful command result with no result.
*
* @return A successful command result with no values.
*/
@Nonnull
public static TurtleCommandResult success()
{
return success( null );
}
public static TurtleCommandResult success( Object[] results )
/**
* Create a successful command result with the given result values.
*
* @param results The results of executing this command.
* @return A successful command result with the given values.
*/
@Nonnull
public static TurtleCommandResult success( @Nullable Object[] results )
{
if( results == null || results.length == 0 )
{
@@ -28,12 +52,25 @@ public final class TurtleCommandResult
}
}
/**
* Create a failed command result with no error message.
*
* @return A failed command result with no message.
*/
@Nonnull
public static TurtleCommandResult failure()
{
return failure( null );
}
public static TurtleCommandResult failure( String errorMessage )
/**
* Create a failed command result with an error message.
*
* @param errorMessage The error message to provide.
* @return A failed command result with a message.
*/
@Nonnull
public static TurtleCommandResult failure( @Nullable String errorMessage )
{
if( errorMessage == null )
{
@@ -56,16 +93,33 @@ public final class TurtleCommandResult
m_results = results;
}
/**
* Determine whether the command executed successfully.
*
* @return If the command was successful.
*/
public boolean isSuccess()
{
return m_success;
}
/**
* Get the error message of this command result.
*
* @return The command's error message, or {@code null} if it was a success.
*/
@Nullable
public String getErrorMessage()
{
return m_errorMessage;
}
/**
* Get the resulting values of this command result.
*
* @return The command's result, or {@code null} if it was a failure.
*/
@Nullable
public Object[] getResults()
{
return m_results;

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. 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.
*/
@@ -11,13 +11,13 @@ package dan200.computercraft.api.turtle;
*/
public enum TurtleSide
{
/**
* The turtles left side (where the pickaxe usually is on a Wireless Mining Turtle)
*/
Left,
/**
* The turtle's left side (where the pickaxe usually is on a Wireless Mining Turtle)
*/
Left,
/**
* The turtles right side (where the modem usually is on a Wireless Mining Turtle)
*/
Right,
/**
* The turtle's right side (where the modem usually is on a Wireless Mining Turtle)
*/
Right,
}

View File

@@ -1,27 +1,44 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle;
/**
* An enum representing the two different types of turtle that an ITurtleUpgrade
* implementation can add to a turtle.
* @see ITurtleUpgrade
* An enum representing the different types of turtle that an {@link ITurtleUpgrade} implementation can add to a turtle.
*
* @see ITurtleUpgrade#getType()
*/
public enum TurtleUpgradeType
{
/**
* A tool is rendered as an item on the side of the turtle, and responds to the turtle.dig()
* and turtle.attack() methods (Such as pickaxe or sword on Mining and Melee turtles).
*/
Tool,
/**
* A peripheral adds a special peripheral which is attached to the side of the turtle,
* and can be interacted with the peripheral API (Such as the modem on Wireless Turtles).
*/
Peripheral,
/**
* A tool is rendered as an item on the side of the turtle, and responds to the {@code turtle.dig()}
* and {@code turtle.attack()} methods (Such as pickaxe or sword on Mining and Melee turtles).
*/
Tool,
/**
* A peripheral adds a special peripheral which is attached to the side of the turtle,
* and can be interacted with the {@code peripheral} API (Such as the modem on Wireless Turtles).
*/
Peripheral,
/**
* An upgrade which provides both a tool and a peripheral. This can be used when you wish
* your upgrade to also provide methods. For example, a pickaxe could provide methods
* determining whether it can break the given block or not.
*/
Both,;
public boolean isTool()
{
return this == Tool || this == Both;
}
public boolean isPeripheral()
{
return this == Peripheral || this == Both;
}
}

View File

@@ -1,26 +1,29 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle;
import net.minecraft.util.EnumFacing;
/**
* An enum representing the two different actions that an ITurtleUpgrade of type
* Tool may be called on to perform by a turtle.
* @see ITurtleUpgrade
* @see ITurtleUpgrade#useTool
* An enum representing the different actions that an {@link ITurtleUpgrade} of type Tool may be called on to perform by
* a turtle.
*
* @see ITurtleUpgrade#getType()
* @see ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, EnumFacing)
*/
public enum TurtleVerb
{
/**
* The turtle called turtle.dig(), turtle.digUp() or turtle.digDown()
*/
Dig,
/**
* The turtle called turtle.attack(), turtle.attackUp() or turtle.attackDown()
*/
Attack,
/**
* The turtle called {@code turtle.dig()}, {@code turtle.digUp()} or {@code turtle.digDown()}
*/
Dig,
/**
* The turtle called {@code turtle.attack()}, {@code turtle.attackUp()} or {@code turtle.attackDown()}
*/
Attack,
}

View File

@@ -0,0 +1,84 @@
/*
* 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.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle.event;
/**
* A basic action that a turtle may perform, as accessed by the {@code turtle} API.
*
* @see TurtleActionEvent
*/
public enum TurtleAction
{
/**
* A turtle moves to a new position.
*
* @see TurtleBlockEvent.Move
*/
MOVE,
/**
* A turtle turns in a specific direction.
*/
TURN,
/**
* A turtle attempts to dig a block.
*
* @see TurtleBlockEvent.Dig
*/
DIG,
/**
* A turtle attempts to place a block or item in the world.
*
* @see TurtleBlockEvent.Place
*/
PLACE,
/**
* A turtle attempts to attack an entity.
*
* @see TurtleActionEvent
*/
ATTACK,
/**
* Drop an item into an inventory/the world.
*
* @see TurtleInventoryEvent.Drop
*/
DROP,
/**
* Suck an item from an inventory or the world.
*
* @see TurtleInventoryEvent.Suck
*/
SUCK,
/**
* Refuel the turtle's fuel levels.
*/
REFUEL,
/**
* Equip or unequip an item.
*/
EQUIP,
/**
* Inspect a block in world
*
* @see TurtleBlockEvent.Inspect
*/
INSPECT,
/**
* Gather metdata about an item in the turtle's inventory.
*/
INSPECT_ITEM,
}

View File

@@ -0,0 +1,76 @@
package dan200.computercraft.api.turtle.event;
import com.google.common.base.Preconditions;
import dan200.computercraft.api.turtle.ITurtleAccess;
import dan200.computercraft.api.turtle.TurtleCommandResult;
import net.minecraftforge.fml.common.eventhandler.Cancelable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* An event fired when a turtle is performing a known action.
*/
@Cancelable
public class TurtleActionEvent extends TurtleEvent
{
private final TurtleAction action;
private String failureMessage;
public TurtleActionEvent( @Nonnull ITurtleAccess turtle, @Nonnull TurtleAction action )
{
super( turtle );
Preconditions.checkNotNull( action, "action cannot be null" );
this.action = action;
}
public TurtleAction getAction()
{
return action;
}
/**
* Sets the cancellation state of this action.
*
* If {@code cancel} is {@code true}, this action will not be carried out.
*
* @param cancel The new canceled value.
* @see TurtleCommandResult#failure()
* @deprecated Use {@link #setCanceled(boolean, String)} instead.
*/
@Override
@Deprecated
public void setCanceled( boolean cancel )
{
setCanceled( cancel, null );
}
/**
* Set the cancellation state of this action, setting a failure message if required.
*
* If {@code cancel} is {@code true}, this action will not be carried out.
*
* @param cancel The new canceled value.
* @param failureMessage The message to return to the user explaining the failure.
* @see TurtleCommandResult#failure(String)
*/
public void setCanceled( boolean cancel, @Nullable String failureMessage )
{
super.setCanceled( cancel );
this.failureMessage = cancel ? failureMessage : null;
}
/**
* Get the message with which this will fail.
*
* @return The failure message.
* @see TurtleCommandResult#failure()
* @see #setCanceled(boolean, String)
*/
@Nullable
public String getFailureMessage()
{
return failureMessage;
}
}

View File

@@ -0,0 +1,80 @@
/*
* 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.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle.event;
import com.google.common.base.Preconditions;
import dan200.computercraft.api.turtle.ITurtleAccess;
import dan200.computercraft.api.turtle.ITurtleUpgrade;
import dan200.computercraft.api.turtle.TurtleSide;
import dan200.computercraft.api.turtle.TurtleVerb;
import net.minecraft.entity.Entity;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.event.entity.player.AttackEntityEvent;
import javax.annotation.Nonnull;
/**
* Fired when a turtle attempts to attack an entity.
*
* This must be fired by {@link ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, EnumFacing)},
* as the base {@code turtle.attack()} command does not fire it.
*
* Note that such commands should also fire {@link AttackEntityEvent}, so you do not need to listen to both.
*
* @see TurtleAction#ATTACK
*/
public class TurtleAttackEvent extends TurtlePlayerEvent
{
private final Entity target;
private final ITurtleUpgrade upgrade;
private final TurtleSide side;
public TurtleAttackEvent( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull Entity target, @Nonnull ITurtleUpgrade upgrade, @Nonnull TurtleSide side )
{
super( turtle, TurtleAction.ATTACK, player );
Preconditions.checkNotNull( target, "target cannot be null" );
Preconditions.checkNotNull( upgrade, "upgrade cannot be null" );
Preconditions.checkNotNull( side, "side cannot be null" );
this.target = target;
this.upgrade = upgrade;
this.side = side;
}
/**
* Get the entity being attacked by this turtle.
*
* @return The entity being attacked.
*/
@Nonnull
public Entity getTarget()
{
return target;
}
/**
* Get the upgrade responsible for attacking.
*
* @return The upgrade responsible for attacking.
*/
@Nonnull
public ITurtleUpgrade getUpgrade()
{
return upgrade;
}
/**
* Get the side the attacking upgrade is on.
*
* @return The upgrade's side.
*/
@Nonnull
public TurtleSide getSide()
{
return side;
}
}

View File

@@ -0,0 +1,241 @@
/*
* 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.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle.event;
import com.google.common.base.Preconditions;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.turtle.ITurtleAccess;
import dan200.computercraft.api.turtle.ITurtleUpgrade;
import dan200.computercraft.api.turtle.TurtleSide;
import dan200.computercraft.api.turtle.TurtleVerb;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.common.eventhandler.Cancelable;
import javax.annotation.Nonnull;
import java.util.Map;
/**
* A general event for when a turtle interacts with a block or region.
*
* You should generally listen to one of the sub-events instead, cancelling them where
* appropriate.
*
* Note that you are not guaranteed to receive this event, if it has been cancelled by other
* mechanisms, such as block protection systems.
*
* Be aware that some events (such as {@link TurtleInventoryEvent}) do not necessarily interact
* with a block, simply objects within that block space.
*/
@Cancelable
public abstract class TurtleBlockEvent extends TurtlePlayerEvent
{
private final World world;
private final BlockPos pos;
protected TurtleBlockEvent( @Nonnull ITurtleAccess turtle, @Nonnull TurtleAction action, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos )
{
super( turtle, action, player );
Preconditions.checkNotNull( world, "world cannot be null" );
Preconditions.checkNotNull( pos, "pos cannot be null" );
this.world = world;
this.pos = pos;
}
/**
* Get the world the turtle is interacting in.
*
* @return The world the turtle is interacting in.
*/
public World getWorld()
{
return world;
}
/**
* Get the position the turtle is interacting with. Note that this is different
* to {@link ITurtleAccess#getPosition()}.
*
* @return The position the turtle is interacting with.
*/
public BlockPos getPos()
{
return pos;
}
/**
* Fired when a turtle attempts to dig a block.
*
* This must be fired by {@link ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, EnumFacing)},
* as the base {@code turtle.dig()} command does not fire it.
*
* Note that such commands should also fire {@link BlockEvent.BreakEvent}, so you do not need to listen to both.
*
* @see TurtleAction#DIG
*/
@Cancelable
public static class Dig extends TurtleBlockEvent
{
private final IBlockState block;
private final ITurtleUpgrade upgrade;
private final TurtleSide side;
public Dig( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull IBlockState block, @Nonnull ITurtleUpgrade upgrade, @Nonnull TurtleSide side )
{
super( turtle, TurtleAction.DIG, player, world, pos );
Preconditions.checkNotNull( block, "block cannot be null" );
Preconditions.checkNotNull( upgrade, "upgrade cannot be null" );
Preconditions.checkNotNull( side, "side cannot be null" );
this.block = block;
this.upgrade = upgrade;
this.side = side;
}
/**
* Get the block which is about to be broken.
*
* @return The block which is going to be broken.
*/
@Nonnull
public IBlockState getBlock()
{
return block;
}
/**
* Get the upgrade doing the digging
*
* @return The upgrade doing the digging.
*/
@Nonnull
public ITurtleUpgrade getUpgrade()
{
return upgrade;
}
/**
* Get the side the upgrade doing the digging is on.
*
* @return The upgrade's side.
*/
@Nonnull
public TurtleSide getSide()
{
return side;
}
}
/**
* Fired when a turtle attempts to move into a block.
*
* @see TurtleAction#MOVE
*/
@Cancelable
public static class Move extends TurtleBlockEvent
{
public Move( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos )
{
super( turtle, TurtleAction.MOVE, player, world, pos );
}
}
/**
* Fired when a turtle attempts to place a block in the world.
*
* @see TurtleAction#PLACE
*/
@Cancelable
public static class Place extends TurtleBlockEvent
{
private final ItemStack stack;
public Place( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull ItemStack stack )
{
super( turtle, TurtleAction.PLACE, player, world, pos );
Preconditions.checkNotNull( stack, "stack cannot be null" );
this.stack = stack;
}
/**
* Get the item stack that will be placed. This should not be modified.
*
* @return The item stack to be placed.
*/
@Nonnull
public ItemStack getStack()
{
return stack;
}
}
/**
* Fired when a turtle gathers data on a block in world.
*
* You may prevent blocks being inspected, or add additional information to the result.
*
* @see TurtleAction#INSPECT
*/
@Cancelable
public static class Inspect extends TurtleBlockEvent
{
private final IBlockState state;
private final Map<String, Object> data;
public Inspect( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull IBlockState state, @Nonnull Map<String, Object> data )
{
super( turtle, TurtleAction.INSPECT, player, world, pos );
Preconditions.checkNotNull( state, "state cannot be null" );
Preconditions.checkNotNull( data, "data cannot be null" );
this.data = data;
this.state = state;
}
/**
* Get the block state which is being inspected.
*
* @return The inspected block state.
*/
@Nonnull
public IBlockState getState()
{
return state;
}
/**
* Get the "inspection data" from this block, which will be returned to the user.
*
* @return This block's inspection data.
*/
@Nonnull
public Map<String, Object> getData()
{
return data;
}
/**
* Add new information to the inspection result. Note this will override fields with the same name.
*
* @param newData The data to add. Note all values should be convertable to Lua (see
* {@link dan200.computercraft.api.peripheral.IPeripheral#callMethod(IComputerAccess, ILuaContext, int, Object[])}).
*/
public void addData( @Nonnull Map<String, ?> newData )
{
Preconditions.checkNotNull( newData, "newData cannot be null" );
data.putAll( newData );
}
}
}

View File

@@ -0,0 +1,43 @@
/*
* 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.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle.event;
import com.google.common.base.Preconditions;
import dan200.computercraft.api.turtle.ITurtleAccess;
import net.minecraftforge.fml.common.eventhandler.Event;
import javax.annotation.Nonnull;
/**
* A base class for all events concerning a turtle. This will only ever constructed and fired on the server side,
* so sever specific methods on {@link ITurtleAccess} are safe to use.
*
* You should generally not need to subscribe to this event, preferring one of the more specific classes.
*
* @see TurtleActionEvent
*/
public abstract class TurtleEvent extends Event
{
private final ITurtleAccess turtle;
protected TurtleEvent( @Nonnull ITurtleAccess turtle )
{
Preconditions.checkNotNull( turtle, "turtle cannot be null" );
this.turtle = turtle;
}
/**
* Get the turtle which is performing this action.
*
* @return The access for this turtle.
*/
@Nonnull
public ITurtleAccess getTurtle()
{
return turtle;
}
}

View File

@@ -0,0 +1,84 @@
package dan200.computercraft.api.turtle.event;
import com.google.common.base.Preconditions;
import dan200.computercraft.api.turtle.ITurtleAccess;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.fml.common.eventhandler.Cancelable;
import net.minecraftforge.items.IItemHandler;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Fired when a turtle attempts to interact with an inventory.
*/
@Cancelable
public abstract class TurtleInventoryEvent extends TurtleBlockEvent
{
private final IItemHandler handler;
protected TurtleInventoryEvent( @Nonnull ITurtleAccess turtle, @Nonnull TurtleAction action, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nullable IItemHandler handler )
{
super( turtle, action, player, world, pos );
this.handler = handler;
}
/**
* Get the inventory being interacted with
*
* @return The inventory being interacted with, {@code null} if the item will be dropped to/sucked from the world.
*/
@Nullable
public IItemHandler getItemHandler()
{
return handler;
}
/**
* Fired when a turtle attempts to suck from an inventory.
*
* @see TurtleAction#SUCK
*/
@Cancelable
public static class Suck extends TurtleInventoryEvent
{
public Suck( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nullable IItemHandler handler )
{
super( turtle, TurtleAction.SUCK, player, world, pos, handler );
}
}
/**
* Fired when a turtle attempts to drop an item into an inventory.
*
* @see TurtleAction#DROP
*/
@Cancelable
public static class Drop extends TurtleInventoryEvent
{
private final ItemStack stack;
public Drop( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nullable IItemHandler handler, @Nonnull ItemStack stack )
{
super( turtle, TurtleAction.DROP, player, world, pos, handler );
Preconditions.checkNotNull( stack, "stack cannot be null" );
this.stack = stack;
}
/**
* The item which will be inserted into the inventory/dropped on the ground.
*
* Note that this is a copy of the original stack, and so should not be modified, as that will have no effect.
*
* @return The item stack which will be dropped.
*/
public ItemStack getStack()
{
return stack.copy();
}
}
}

View File

@@ -0,0 +1,44 @@
/*
* 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.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.turtle.event;
import com.google.common.base.Preconditions;
import dan200.computercraft.api.turtle.ITurtleAccess;
import net.minecraftforge.common.util.FakePlayer;
import javax.annotation.Nonnull;
/**
* An action done by a turtle which is normally done by a player.
*
* {@link #getPlayer()} may be used to modify the player's attributes or perform permission checks.
*/
public abstract class TurtlePlayerEvent extends TurtleActionEvent
{
private final FakePlayer player;
protected TurtlePlayerEvent( @Nonnull ITurtleAccess turtle, @Nonnull TurtleAction action, @Nonnull FakePlayer player )
{
super( turtle, action );
Preconditions.checkNotNull( player, "player cannot be null" );
this.player = player;
}
/**
* A fake player, representing this turtle.
*
* This may be used for triggering permission checks.
*
* @return A {@link FakePlayer} representing this turtle.
*/
@Nonnull
public FakePlayer getPlayer()
{
return player;
}
}

View File

@@ -0,0 +1,10 @@
/*
* 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.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
@API(owner = "ComputerCraft", provides = "ComputerCraft|API|Turtle|Event", apiVersion = "${version}")
package dan200.computercraft.api.turtle.event;
import net.minecraftforge.fml.common.API;

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. This API may be redistributed unmodified and in full only.
* Copyright Daniel Ratcliffe, 2011-2017. 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,24 +1,27 @@
/**
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.gui;
import dan200.computercraft.core.terminal.TextBuffer;
import dan200.computercraft.shared.util.Colour;
import dan200.computercraft.shared.util.Palette;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import java.util.Arrays;
public class FixedWidthFontRenderer
{
public static ResourceLocation font = new ResourceLocation( "computercraft", "textures/gui/termFont.png" );
public static ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/termBackground.png" );
private static ResourceLocation font = new ResourceLocation( "computercraft", "textures/gui/term_font.png" );
public static ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/term_background.png" );
public static int FONT_HEIGHT = 9;
public static int FONT_WIDTH = 6;
@@ -30,24 +33,53 @@ public class FixedWidthFontRenderer
m_textureManager = textureManager;
}
private void drawChar( VertexBuffer renderer, double x, double y, int index, int color )
private static void greyscaleify( double[] rgb )
{
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 )
{
int column = index % 16;
int row = index / 16;
Colour colour = Colour.values()[ 15 - color ];
renderer.pos( x, y + FONT_HEIGHT, 0.0 ).tex( (double) (column * FONT_WIDTH) / 256.0, (double) ((row + 1) * FONT_HEIGHT) / 256.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( x + FONT_WIDTH, y + FONT_HEIGHT, 0.0 ).tex( (double) ((column + 1) * FONT_WIDTH) / 256.0, (double) ((row + 1) * FONT_HEIGHT) / 256.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( x + FONT_WIDTH, y, 0.0 ).tex( (double) ((column + 1) * FONT_WIDTH) / 256.0, (double) (row * FONT_HEIGHT) / 256.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( x, y, 0.0 ).tex( (double) (column * FONT_WIDTH) / 256.0, (double) (row * FONT_HEIGHT ) / 256.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
double[] colour = p.getColour( 15 - color );
if(greyscale)
{
greyscaleify( colour );
}
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);
renderer.pos( x, y, 0.0 ).tex( xStart / 256.0, yStart / 256.0 ).color( r, g, b, 1.0f ).endVertex();
renderer.pos( x, y + FONT_HEIGHT, 0.0 ).tex( xStart / 256.0, (yStart + FONT_HEIGHT) / 256.0 ).color( r, g, b, 1.0f ).endVertex();
renderer.pos( x + FONT_WIDTH, y, 0.0 ).tex( (xStart + FONT_WIDTH) / 256.0, yStart / 256.0 ).color( r, g, b, 1.0f ).endVertex();
renderer.pos( x + FONT_WIDTH, y, 0.0 ).tex( (xStart + FONT_WIDTH) / 256.0, yStart / 256.0 ).color( r, g, b, 1.0f ).endVertex();
renderer.pos( x, y + FONT_HEIGHT, 0.0 ).tex( xStart / 256.0, (yStart + FONT_HEIGHT) / 256.0 ).color( r, g, b, 1.0f ).endVertex();
renderer.pos( x + FONT_WIDTH, y + FONT_HEIGHT, 0.0 ).tex( (xStart + FONT_WIDTH) / 256.0, (yStart + FONT_HEIGHT) / 256.0 ).color( r, g, b, 1.0f ).endVertex();
}
private void drawQuad( VertexBuffer renderer, double x, double y, int color, double width )
private void drawQuad( BufferBuilder renderer, double x, double y, int color, double width, Palette p, boolean greyscale )
{
Colour colour = Colour.values()[ 15 - color ];
renderer.pos( x, y + FONT_HEIGHT, 0.0 ).tex( 0.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( x + width, y + FONT_HEIGHT, 0.0 ).tex( 1.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( x + width, y, 0.0 ).tex( 1.0, 0.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( x, y, 0.0 ).tex( 0.0, 0.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
double[] colour = p.getColour( 15 - color );
if(greyscale)
{
greyscaleify( colour );
}
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();
renderer.pos( x + width, y, 0.0 ).color( r, g, b, 1.0f ).endVertex();
renderer.pos( x + width, 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();
renderer.pos( x + width, y + FONT_HEIGHT, 0.0 ).color( r, g, b, 1.0f ).endVertex();
}
private boolean isGreyScale( int colour )
@@ -55,12 +87,12 @@ public class FixedWidthFontRenderer
return (colour == 0 || colour == 15 || colour == 7 || colour == 8);
}
public void drawStringBackgroundPart( int x, int y, TextBuffer backgroundColour, double leftMarginSize, double rightMarginSize, boolean greyScale )
public void drawStringBackgroundPart( int x, int y, TextBuffer backgroundColour, double leftMarginSize, double rightMarginSize, boolean greyScale, Palette p )
{
// Draw the quads
Tessellator tessellator = Tessellator.getInstance();
VertexBuffer renderer = tessellator.getBuffer();
renderer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR );
BufferBuilder renderer = tessellator.getBuffer();
renderer.begin( GL11.GL_TRIANGLES, DefaultVertexFormats.POSITION_COLOR );
if( leftMarginSize > 0.0 )
{
int colour1 = "0123456789abcdef".indexOf( backgroundColour.charAt( 0 ) );
@@ -68,7 +100,7 @@ public class FixedWidthFontRenderer
{
colour1 = 15;
}
drawQuad( renderer, x - leftMarginSize, y, colour1, leftMarginSize );
drawQuad( renderer, x - leftMarginSize, y, colour1, leftMarginSize, p, greyScale );
}
if( rightMarginSize > 0.0 )
{
@@ -77,7 +109,7 @@ public class FixedWidthFontRenderer
{
colour2 = 15;
}
drawQuad( renderer, x + backgroundColour.length() * FONT_WIDTH, y, colour2, rightMarginSize );
drawQuad( renderer, x + backgroundColour.length() * FONT_WIDTH, y, colour2, rightMarginSize, p, greyScale );
}
for( int i = 0; i < backgroundColour.length(); i++ )
{
@@ -86,17 +118,19 @@ public class FixedWidthFontRenderer
{
colour = 15;
}
drawQuad( renderer, x + i * FONT_WIDTH, y, colour, FONT_WIDTH );
drawQuad( renderer, x + i * FONT_WIDTH, y, colour, FONT_WIDTH, p, greyScale );
}
GlStateManager.disableTexture2D();
tessellator.draw();
GlStateManager.enableTexture2D();
}
public void drawStringTextPart( int x, int y, TextBuffer s, TextBuffer textColour, boolean greyScale )
public void drawStringTextPart( int x, int y, TextBuffer s, TextBuffer textColour, boolean greyScale, Palette p )
{
// Draw the quads
Tessellator tessellator = Tessellator.getInstance();
VertexBuffer renderer = tessellator.getBuffer();
renderer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR );
BufferBuilder renderer = tessellator.getBuffer();
renderer.begin( GL11.GL_TRIANGLES, DefaultVertexFormats.POSITION_TEX_COLOR );
for( int i = 0; i < s.length(); i++ )
{
// Switch colour
@@ -107,37 +141,37 @@ public class FixedWidthFontRenderer
}
// Draw char
int index = (int)s.charAt( i );
int index = s.charAt( i );
if( index < 0 || index > 255 )
{
index = (int)'?';
index = '?';
}
drawChar( renderer, x + i * FONT_WIDTH, y, index, colour );
drawChar( renderer, x + i * FONT_WIDTH, y, index, colour, p, greyScale );
}
tessellator.draw();
}
public void drawString( TextBuffer s, int x, int y, TextBuffer textColour, TextBuffer backgroundColour, double leftMarginSize, double rightMarginSize, boolean greyScale )
public void drawString( TextBuffer s, int x, int y, TextBuffer textColour, TextBuffer backgroundColour, double leftMarginSize, double rightMarginSize, boolean greyScale, Palette p )
{
// Draw background
if( backgroundColour != null )
{
// Bind the background texture
m_textureManager.bindTexture( background );
// Bind the background texture
m_textureManager.bindTexture( background );
// Draw the quads
drawStringBackgroundPart( x, y, backgroundColour, leftMarginSize, rightMarginSize, greyScale );
}
// Draw text
drawStringBackgroundPart( x, y, backgroundColour, leftMarginSize, rightMarginSize, greyScale, p );
}
// Draw text
if( s != null && textColour != null )
{
// Bind the font texture
m_textureManager.bindTexture( font );
{
// Bind the font texture
bindFont();
// Draw the quads
drawStringTextPart( x, y, s, textColour, greyScale );
}
drawStringTextPart( x, y, s, textColour, greyScale, p );
}
}
public int getStringWidth(String s)
@@ -148,4 +182,10 @@ public class FixedWidthFontRenderer
}
return s.length() * FONT_WIDTH;
}
public void bindFont()
{
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-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -11,7 +11,6 @@ import dan200.computercraft.client.gui.widgets.WidgetTerminal;
import dan200.computercraft.shared.computer.blocks.TileComputer;
import dan200.computercraft.shared.computer.core.ComputerFamily;
import dan200.computercraft.shared.computer.core.IComputer;
import dan200.computercraft.shared.computer.core.IComputerContainer;
import dan200.computercraft.shared.computer.inventory.ContainerComputer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
@@ -25,16 +24,16 @@ import java.io.IOException;
public class GuiComputer extends GuiContainer
{
private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/corners.png" );
private static final ResourceLocation backgroundAdvanced = new ResourceLocation( "computercraft", "textures/gui/corners2.png" );
private static final ResourceLocation backgroundCommand = new ResourceLocation( "computercraft", "textures/gui/cornersCommand.png" );
private 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 final ComputerFamily m_family;
private final IComputer m_computer;
private final int m_termWidth;
private final int m_termHeight;
private WidgetTerminal m_terminal;
private WidgetTerminal m_terminal;
protected GuiComputer( Container container, ComputerFamily family, IComputer computer, int termWidth, int termHeight )
public GuiComputer( Container container, ComputerFamily family, IComputer computer, int termWidth, int termHeight )
{
super( container );
m_family = family;
@@ -46,85 +45,78 @@ public class GuiComputer extends GuiContainer
public GuiComputer( TileComputer computer )
{
this(
this(
new ContainerComputer( computer ),
computer.getFamily(),
computer.createComputer(),
ComputerCraft.terminalWidth_computer,
ComputerCraft.terminalHeight_computer
);
}
}
@Override
public void initGui()
{
super.initGui();
Keyboard.enableRepeatEvents( true );
super.initGui();
Keyboard.enableRepeatEvents( true );
m_terminal = new WidgetTerminal( 0, 0, m_termWidth, m_termHeight, new IComputerContainer()
{
@Override
public IComputer getComputer()
{
return m_computer;
}
}, 2, 2, 2, 2 );
m_terminal = new WidgetTerminal( 0, 0, m_termWidth, m_termHeight, () -> m_computer, 2, 2, 2, 2 );
m_terminal.setAllowFocusLoss( false );
xSize = m_terminal.getWidth() + 24;
ySize = m_terminal.getHeight() + 24;
}
}
@Override
public void onGuiClosed()
{
super.onGuiClosed();
super.onGuiClosed();
Keyboard.enableRepeatEvents( false );
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
public boolean doesGuiPauseGame()
{
return false;
}
@Override
public void updateScreen()
{
super.updateScreen();
m_terminal.update();
super.updateScreen();
m_terminal.update();
}
@Override
@Override
protected void keyTyped(char c, int k) throws IOException
{
if( k == 1 )
{
super.keyTyped( c, k );
}
else
{
m_terminal.keyTyped( c, k );
}
if( k == 1 )
{
super.keyTyped( c, k );
}
else
{
m_terminal.keyTyped( c, k );
}
}
@Override
@Override
protected void mouseClicked( int x, int y, int button )
{
int startX = (width - m_terminal.getWidth()) / 2;
int startY = (height - m_terminal.getHeight()) / 2;
m_terminal.mouseClicked( x - startX, y - startY, button );
m_terminal.mouseClicked( x - startX, y - startY, button );
}
@Override
@Override
public void handleMouseInput() throws IOException
{
super.handleMouseInput();
super.handleMouseInput();
int x = Mouse.getEventX() * width / mc.displayWidth;
int y = height - Mouse.getEventY() * height / mc.displayHeight - 1;
int startX = (width - m_terminal.getWidth()) / 2;
int startY = (height - m_terminal.getHeight()) / 2;
m_terminal.handleMouseInput( x - startX, y - startY );
m_terminal.handleMouseInput( x - startX, y - startY );
}
@Override
@@ -134,17 +126,17 @@ public class GuiComputer extends GuiContainer
m_terminal.handleKeyboardInput();
}
@Override
@Override
protected void drawGuiContainerForegroundLayer(int par1, int par2)
{
}
@Override
@Override
protected void drawGuiContainerBackgroundLayer( float var1, int var2, int var3 )
{
}
@Override
@Override
public void drawScreen( int mouseX, int mouseY, float f )
{
// Work out where to draw
@@ -153,14 +145,14 @@ public class GuiComputer extends GuiContainer
int endX = startX + m_terminal.getWidth();
int endY = startY + m_terminal.getHeight();
// Draw background
drawDefaultBackground();
// 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 );
// Draw a border around the terminal
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
switch( m_family )
{
case Normal:
@@ -181,15 +173,15 @@ public class GuiComputer extends GuiContainer
}
}
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

@@ -0,0 +1,61 @@
package dan200.computercraft.client.gui;
import dan200.computercraft.ComputerCraft;
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;
}
public static class Factory
implements IModGuiFactory
{
@Override
public void initialize( Minecraft minecraft )
{
}
@Override
public boolean hasConfigGui()
{
return true;
}
@Override
public GuiScreen createConfigGui( GuiScreen parentScreen )
{
return new GuiConfigCC( parentScreen );
}
@Override
public Set<RuntimeOptionCategoryElement> runtimeGuiCategories()
{
return null;
}
}
}

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -30,8 +30,8 @@ public class GuiDiskDrive extends GuiContainer
protected void drawGuiContainerForegroundLayer(int par1, int par2)
{
String title = m_diskDrive.getDisplayName().getUnformattedText();
fontRendererObj.drawString( title, (xSize - fontRendererObj.getStringWidth(title)) / 2, 6, 0x404040 );
fontRendererObj.drawString( I18n.format("container.inventory"), 8, (ySize - 96) + 2, 0x404040 );
fontRenderer.drawString( title, (xSize - fontRenderer.getStringWidth(title)) / 2, 6, 0x404040 );
fontRenderer.drawString( I18n.format("container.inventory"), 8, (ySize - 96) + 2, 0x404040 );
}
@Override
@@ -43,4 +43,12 @@ public class GuiDiskDrive extends GuiContainer
int i1 = (height - ySize) / 2;
drawTexturedModalRect(l, i1, 0, 0, xSize, ySize);
}
@Override
public void drawScreen( int mouseX, int mouseY, float partialTicks)
{
drawDefaultBackground();
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-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -32,8 +32,8 @@ public class GuiPrinter extends GuiContainer
protected void drawGuiContainerForegroundLayer(int par1, int par2)
{
String title = m_printer.getDisplayName().getUnformattedText();
fontRendererObj.drawString( title, (xSize - fontRendererObj.getStringWidth(title)) / 2, 6, 0x404040 );
fontRendererObj.drawString( I18n.format("container.inventory"), 8, (ySize - 96) + 2, 0x404040 );
fontRenderer.drawString( title, (xSize - fontRenderer.getStringWidth(title)) / 2, 6, 0x404040 );
fontRenderer.drawString( I18n.format("container.inventory"), 8, (ySize - 96) + 2, 0x404040 );
}
@Override
@@ -48,7 +48,15 @@ public class GuiPrinter extends GuiContainer
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)
{
drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
renderHoveredToolTip(mouseX, mouseY);
}
}

View File

@@ -1,127 +1,104 @@
/**
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.gui;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.core.terminal.TextBuffer;
import dan200.computercraft.shared.media.inventory.ContainerHeldItem;
import dan200.computercraft.shared.media.items.ItemPrintout;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import java.io.IOException;
import static dan200.computercraft.client.render.PrintoutRenderer.*;
public class GuiPrintout extends GuiContainer
{
private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/printout.png" );
private static final int xSize = 172;
private static final int ySize = 209;
private final boolean m_book;
private final int m_pages;
private final TextBuffer[] m_text;
private final TextBuffer[] m_colours;
private int m_page;
private final boolean m_book;
private final int m_pages;
private final TextBuffer[] m_text;
private final TextBuffer[] m_colours;
private int m_page;
public GuiPrintout( ContainerHeldItem container )
{
super( container );
m_book = (ItemPrintout.getType( container.getStack() ) == ItemPrintout.Type.Book);
String[] text = ItemPrintout.getText( container.getStack() );
m_text = new TextBuffer[ text.length ];
for( int i=0; i<m_text.length; ++i )
{
m_text[i] = new TextBuffer( text[i] );
}
String[] colours = ItemPrintout.getColours( container.getStack() );
m_colours = new TextBuffer[ colours.length ];
for( int i=0; i<m_colours.length; ++i )
{
m_colours[i] = new TextBuffer( colours[i] );
}
m_text = new TextBuffer[ text.length ];
for( int i = 0; i < m_text.length; ++i ) m_text[ i ] = new TextBuffer( text[ i ] );
m_pages = Math.max( m_text.length / ItemPrintout.LINES_PER_PAGE, 1 );
m_page = 0;
}
String[] colours = ItemPrintout.getColours( container.getStack() );
m_colours = new TextBuffer[ colours.length ];
for( int i = 0; i < m_colours.length; ++i ) m_colours[ i ] = new TextBuffer( colours[ i ] );
m_page = 0;
m_pages = Math.max( m_text.length / ItemPrintout.LINES_PER_PAGE, 1 );
m_book = ItemPrintout.getType( container.getStack() ) == ItemPrintout.Type.Book;
}
@Override
public void initGui()
{
super.initGui();
}
super.initGui();
}
@Override
public void onGuiClosed()
{
super.onGuiClosed();
super.onGuiClosed();
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
public boolean doesGuiPauseGame()
{
return false;
}
@Override
public void updateScreen()
{
super.updateScreen();
super.updateScreen();
}
@Override
protected void keyTyped(char c, int k) throws IOException
protected void keyTyped( char c, int k ) throws IOException
{
super.keyTyped( c, k );
super.keyTyped( c, k );
if( k == 205 )
{
// Right
if( m_page < m_pages - 1 )
{
m_page = m_page + 1;
}
}
else if( k == 203 )
{
// Left
if( m_page > 0 )
{
m_page = m_page - 1;
}
}
if( k == 205 )
{
// Right
if( m_page < m_pages - 1 ) m_page++;
}
else if( k == 203 )
{
// Left
if( m_page > 0 ) m_page--;
}
}
@Override
public void handleMouseInput() throws IOException
{
super.handleMouseInput();
super.handleMouseInput();
int mouseWheelChange = Mouse.getEventDWheel();
if (mouseWheelChange < 0)
{
// Up
if( m_page < m_pages - 1 )
{
m_page = m_page + 1;
}
}
else if (mouseWheelChange > 0)
{
// Down
if( m_page > 0 )
{
m_page = m_page - 1;
}
}
int mouseWheelChange = Mouse.getEventDWheel();
if( mouseWheelChange < 0 )
{
// Up
if( m_page < m_pages - 1 ) m_page++;
}
else if( mouseWheelChange > 0 )
{
// Down
if( m_page > 0 ) m_page--;
}
}
@Override
@@ -135,78 +112,20 @@ public class GuiPrintout extends GuiContainer
}
@Override
public void drawScreen(int mouseX, int mouseY, float f)
public void drawScreen( int mouseX, int mouseY, float f )
{
// Draw background
drawDefaultBackground();
// Draw the printout
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
this.mc.getTextureManager().bindTexture( background );
int startY = (height - ySize) / 2;
//int startX = (width - xSize) / 2 - (m_page * 8);
int startX = (width - (xSize + (m_pages - 1)*8)) / 2;
if( m_book )
{
// Border
drawTexturedModalRect( startX - 8, startY - 8, xSize + 48, 0, 12, ySize + 24);
drawTexturedModalRect( startX + xSize + (m_pages - 1)*8 - 4, startY - 8, xSize + 48 + 12, 0, 12, ySize + 24);
drawTexturedModalRect( startX, startY - 8, 0, ySize, xSize, 12);
drawTexturedModalRect( startX, startY + ySize - 4, 0, ySize + 12, xSize, 12);
for( int n=1; n<m_pages; ++n )
{
drawTexturedModalRect( startX + xSize + (n-1)*8, startY - 8, 0, ySize, 8, 12);
drawTexturedModalRect( startX + xSize + (n-1)*8, startY + ySize - 4, 0, ySize + 12, 8, 12);
}
}
// Left half
if( m_page == 0 )
{
drawTexturedModalRect( startX, startY, 24, 0, xSize / 2, ySize);
drawTexturedModalRect( startX, startY, 0, 0, 12, ySize);
}
else
{
drawTexturedModalRect( startX, startY, 0, 0, 12, ySize);
for( int n=1; n<m_page; ++n )
{
drawTexturedModalRect( startX + n*8, startY, 12, 0, 12, ySize);
}
drawTexturedModalRect( startX + m_page*8, startY, 24, 0, xSize / 2, ySize);
}
// Right half
if( m_page == (m_pages - 1) )
{
drawTexturedModalRect( startX + m_page*8 + xSize/2, startY, 24 + xSize / 2, 0, xSize / 2, ySize);
drawTexturedModalRect( startX + m_page*8 + (xSize - 12), startY, 24 + xSize + 12, 0, 12, ySize);
}
else
{
drawTexturedModalRect( startX + (m_pages - 1)*8 + (xSize - 12), startY, 24 + xSize + 12, 0, 12, ySize);
for( int n=m_pages-2; n>=m_page; --n )
{
drawTexturedModalRect( startX + n*8 + (xSize - 12), startY, 24 + xSize, 0, 12, ySize);
}
drawTexturedModalRect( startX + m_page*8 + xSize/2, startY, 24 + xSize / 2, 0, xSize / 2, ySize);
}
// Draw background
zLevel = zLevel - 1;
drawDefaultBackground();
zLevel = zLevel + 1;
// Draw the text
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer)ComputerCraft.getFixedWidthFontRenderer();
int x = startX + m_page * 8 + 13;
int y = startY + 11;
for( int line=0; line<ItemPrintout.LINES_PER_PAGE; ++line )
{
int lineIdx = ItemPrintout.LINES_PER_PAGE * m_page + line;
if( lineIdx >= 0 && lineIdx < m_text.length )
{
fontRenderer.drawString( m_text[lineIdx], x, y, m_colours[lineIdx], null, 0, 0, false );
}
y = y + FixedWidthFontRenderer.FONT_HEIGHT;
}
}
// Draw the printout
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
int startY = (height - Y_SIZE) / 2;
int startX = (width - X_SIZE) / 2;
drawBorder( startX, startY, zLevel, m_page, m_pages, m_book );
drawText( startX + X_TEXT_MARGIN, startY + Y_TEXT_MARGIN, ItemPrintout.LINES_PER_PAGE * m_page, m_text, m_colours );
}
}

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -11,7 +11,6 @@ import dan200.computercraft.api.turtle.ITurtleAccess;
import dan200.computercraft.client.gui.widgets.WidgetTerminal;
import dan200.computercraft.shared.computer.core.ComputerFamily;
import dan200.computercraft.shared.computer.core.IComputer;
import dan200.computercraft.shared.computer.core.IComputerContainer;
import dan200.computercraft.shared.turtle.blocks.TileTurtle;
import dan200.computercraft.shared.turtle.inventory.ContainerTurtle;
import net.minecraft.client.Minecraft;
@@ -28,10 +27,10 @@ import java.io.IOException;
public class GuiTurtle extends GuiContainer
{
private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/turtle.png" );
private static final ResourceLocation backgroundAdvanced = new ResourceLocation( "computercraft", "textures/gui/turtle2.png" );
private static final ResourceLocation backgroundAdvanced = new ResourceLocation( "computercraft", "textures/gui/turtle_advanced.png" );
protected World m_world;
protected ContainerTurtle m_container;
protected World m_world;
protected ContainerTurtle m_container;
protected final ComputerFamily m_family;
protected final ITurtleAccess m_turtle;
@@ -40,15 +39,15 @@ public class GuiTurtle extends GuiContainer
public GuiTurtle( World world, InventoryPlayer inventoryplayer, TileTurtle turtle )
{
this( world, turtle, new ContainerTurtle( inventoryplayer, turtle.getAccess() ) );
this( world, turtle, new ContainerTurtle( inventoryplayer, turtle.getAccess() ) );
}
protected GuiTurtle( World world, TileTurtle turtle, ContainerTurtle container )
{
super( container );
super( container );
m_world = world;
m_container = container;
m_world = world;
m_container = container;
m_family = turtle.getFamily();
m_turtle = turtle.getAccess();
m_computer = turtle.createComputer();
@@ -60,67 +59,60 @@ public class GuiTurtle extends GuiContainer
@Override
public void initGui()
{
super.initGui();
Keyboard.enableRepeatEvents(true);
m_terminalGui = new WidgetTerminal(
super.initGui();
Keyboard.enableRepeatEvents(true);
m_terminalGui = new WidgetTerminal(
( width - xSize ) / 2 + 8,
( height - ySize ) / 2 + 8,
ComputerCraft.terminalWidth_turtle,
ComputerCraft.terminalHeight_turtle,
new IComputerContainer()
{
@Override
public IComputer getComputer()
{
return m_computer;
}
},
() -> m_computer,
2, 2, 2, 2
);
m_terminalGui.setAllowFocusLoss( false );
}
}
@Override
public void onGuiClosed()
{
super.onGuiClosed();
super.onGuiClosed();
Keyboard.enableRepeatEvents(false);
}
@Override
public void updateScreen()
{
super.updateScreen();
m_terminalGui.update();
super.updateScreen();
m_terminalGui.update();
}
@Override
protected void keyTyped(char c, int k) throws IOException
{
if( k == 1 )
{
super.keyTyped( c, k );
}
else
{
m_terminalGui.keyTyped( c, k );
}
if( k == 1 )
{
super.keyTyped( c, k );
}
else
{
m_terminalGui.keyTyped( c, k );
}
}
@Override
@Override
protected void mouseClicked(int x, int y, int button) throws IOException
{
super.mouseClicked( x, y, button );
m_terminalGui.mouseClicked( x, y, button );
super.mouseClicked( x, y, button );
m_terminalGui.mouseClicked( x, y, button );
}
@Override
@Override
public void handleMouseInput() throws IOException
{
super.handleMouseInput();
super.handleMouseInput();
int x = Mouse.getEventX() * this.width / mc.displayWidth;
int y = this.height - Mouse.getEventY() * this.height / mc.displayHeight - 1;
m_terminalGui.handleMouseInput( x, y );
m_terminalGui.handleMouseInput( x, y );
}
@Override
@@ -135,32 +127,40 @@ public class GuiTurtle extends GuiContainer
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);
}
// Draw selection slot
int slot = m_container.getSelectedSlot();
if( slot >= 0 )
{
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
int slotX = (slot%4);
int slotY = (slot/4);
this.mc.getTextureManager().bindTexture( advanced ? backgroundAdvanced : background );
drawTexturedModalRect(x + m_container.m_turtleInvStartX - 2 + slotX * 18, y + m_container.m_playerInvStartY - 2 + slotY * 18, 0, 217, 24, 24);
}
}
@Override
@Override
protected void drawGuiContainerBackgroundLayer( float f, int mouseX, int mouseY )
{
// Draw term
// Draw term
boolean advanced = (m_family == ComputerFamily.Advanced);
m_terminalGui.draw( Minecraft.getMinecraft(), 0, 0, mouseX, mouseY );
// Draw border/inventory
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 ? backgroundAdvanced : background );
int x = (width - xSize) / 2;
int y = (height - ySize) / 2;
drawTexturedModalRect(x, y, 0, 0, xSize, ySize);
drawSelectionSlot( advanced );
}
@Override
public void drawScreen( int mouseX, int mouseY, float partialTicks)
{
drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
renderHoveredToolTip(mouseX, mouseY);
}
}

View File

@@ -0,0 +1,19 @@
/*
* 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.client.gui.widgets;
public class MousePos
{
public int x;
public int y;
public MousePos( int x, int y )
{
this.x = x;
this.y = y;
}
}

View File

@@ -1,25 +1,22 @@
/**
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.gui.widgets;
import dan200.computercraftedu.client.gui.widgets.MousePos;
import dan200.computercraftedu.client.gui.widgets.WidgetContainer;
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.RenderItem;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import javax.annotation.Nonnull;
public abstract class Widget extends Gui
{
@@ -178,10 +175,10 @@ public abstract class Widget extends Gui
{
Tessellator tessellator = Tessellator.getInstance();
tessellator.getBuffer().begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX );
tessellator.getBuffer().pos( (double) ( x + 0 ), (double) ( y + h ), (double) this.zLevel ).tex( 0.0, 1.0 ).endVertex();
tessellator.getBuffer().pos( (double) ( x + w ), (double) ( y + h ), (double) this.zLevel ).tex( 1.0, 1.0 ).endVertex();
tessellator.getBuffer().pos( (double) ( x + w ), (double) ( y + 0 ), (double) this.zLevel ).tex( 1.0, 0.0 ).endVertex();
tessellator.getBuffer().pos( (double) ( x + 0 ), (double) ( y + 0 ), (double) this.zLevel ).tex( 0.0, 0.0 ).endVertex();
tessellator.getBuffer().pos( x + 0, y + h, this.zLevel ).tex( 0.0, 1.0 ).endVertex();
tessellator.getBuffer().pos( x + w, y + h, this.zLevel ).tex( 1.0, 1.0 ).endVertex();
tessellator.getBuffer().pos( x + w, y + 0, this.zLevel ).tex( 1.0, 0.0 ).endVertex();
tessellator.getBuffer().pos( x + 0, y + 0, this.zLevel ).tex( 0.0, 0.0 ).endVertex();
tessellator.draw();
}
@@ -268,12 +265,11 @@ public abstract class Widget extends Gui
protected void drawTooltip( String[] lines, int x, int y )
{
Minecraft mc = Minecraft.getMinecraft();
FontRenderer fontRenderer = mc.fontRendererObj;
FontRenderer fontRenderer = mc.fontRenderer;
int width = 0;
for( int i=0; i<lines.length; ++i )
for( String line : lines )
{
String line = lines[i];
width = Math.max( fontRenderer.getStringWidth( line ), width );
}
int startX = x + 12;
@@ -328,9 +324,9 @@ public abstract class Widget extends Gui
}
}
protected void drawItemStack( int x, int y, ItemStack stack )
protected void drawItemStack( int x, int y, @Nonnull ItemStack stack )
{
if( stack != null )
if( !stack.isEmpty() )
{
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
GlStateManager.enableLighting();
@@ -344,7 +340,7 @@ public abstract class Widget extends Gui
if( renderItem != null )
{
renderItem.renderItemAndEffectIntoGUI( stack, x, y );
renderItem.renderItemOverlayIntoGUI( mc.fontRendererObj, stack, x, y, null );
renderItem.renderItemOverlayIntoGUI( mc.fontRenderer, stack, x, y, null );
}
}
finally
@@ -364,7 +360,7 @@ public abstract class Widget extends Gui
Minecraft mc = Minecraft.getMinecraft();
try
{
mc.fontRendererObj.drawString( s, x, y, color );
mc.fontRenderer.drawString( s, x, y, color );
}
finally
{
@@ -375,7 +371,7 @@ public abstract class Widget extends Gui
protected int getStringWidth( String s )
{
Minecraft mc = Minecraft.getMinecraft();
return mc.fontRendererObj.getStringWidth( s );
return mc.fontRenderer.getStringWidth( s );
}
protected void playClickSound()

View File

@@ -0,0 +1,336 @@
/*
* 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.client.gui.widgets;
import dan200.computercraft.client.gui.widgets.Widget;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import java.util.ArrayList;
public class WidgetContainer extends Widget
{
private ArrayList<Widget> m_widgets;
private Widget m_modalWidget;
public WidgetContainer( int x, int y, int w, int h )
{
super( x, y, w, h );
m_widgets = new ArrayList<>();
m_modalWidget = null;
}
public void addWidget( Widget widget )
{
m_widgets.add( widget );
widget.setParent( this );
}
public void setModalWidget( Widget widget )
{
m_modalWidget = widget;
if( widget != null )
{
widget.setParent( this );
}
}
public Widget getModalWidget()
{
return m_modalWidget;
}
@Override
public void update()
{
for( Widget m_widget : m_widgets )
{
m_widget.update();
}
if( m_modalWidget != null )
{
m_modalWidget.update();
}
}
@Override
public void draw( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY )
{
for( Widget widget : m_widgets )
{
if( widget.isVisible() )
{
widget.draw(
mc,
xOrigin + getXPosition(),
yOrigin + getYPosition(),
(m_modalWidget == null) ? (mouseX - getXPosition()) : -99,
(m_modalWidget == null) ? (mouseY - getYPosition()) : -99
);
}
}
if( m_modalWidget != null )
{
if( m_modalWidget.isVisible() )
{
GlStateManager.pushMatrix();
try
{
GlStateManager.translate( 0.0f, 0.0f, 200.0f );
m_modalWidget.draw(
mc,
xOrigin + getXPosition(),
yOrigin + getYPosition(),
mouseX - getXPosition(),
mouseY - getYPosition()
);
}
finally
{
GlStateManager.popMatrix();
}
}
}
}
@Override
public void drawForeground( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY )
{
for( Widget widget : m_widgets )
{
if( widget.isVisible() )
{
widget.drawForeground(
mc,
xOrigin + getXPosition(),
yOrigin + getYPosition(),
(m_modalWidget == null) ? (mouseX - getXPosition()) : -99,
(m_modalWidget == null) ? (mouseY - getYPosition()) : -99
);
}
}
if( m_modalWidget != null )
{
if( m_modalWidget.isVisible() )
{
GlStateManager.pushMatrix();
try
{
GlStateManager.translate( 0.0f, 0.0f, 200.0f );
m_modalWidget.drawForeground(
mc,
xOrigin + getXPosition(),
yOrigin + getYPosition(),
mouseX - getXPosition(),
mouseY - getYPosition()
);
}
finally
{
GlStateManager.popMatrix();
}
}
}
}
@Override
public void modifyMousePosition( MousePos pos )
{
pos.x -= getXPosition();
pos.y -= getYPosition();
if( m_modalWidget == null )
{
for( Widget widget : m_widgets )
{
if( widget.isVisible() )
{
widget.modifyMousePosition( pos );
}
}
}
else
{
if( m_modalWidget.isVisible() )
{
m_modalWidget.modifyMousePosition( pos );
}
}
pos.x += getXPosition();
pos.y += getYPosition();
}
@Override
public boolean suppressItemTooltips( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY )
{
if( m_modalWidget == null )
{
for( Widget widget : m_widgets )
{
if( widget.isVisible() )
{
if( widget.suppressItemTooltips(
mc,
xOrigin + getXPosition(),
yOrigin + getYPosition(),
mouseX - getXPosition(),
mouseY - getYPosition()
) )
{
return true;
}
}
}
}
else
{
if( m_modalWidget.isVisible() && m_modalWidget.suppressItemTooltips(
mc,
xOrigin + getXPosition(),
yOrigin + getYPosition(),
mouseX - getXPosition(),
mouseY - getYPosition()
) )
{
return true;
}
}
return false;
}
@Override
public boolean suppressKeyPress( char c, int k )
{
if( m_modalWidget == null )
{
for( Widget widget : m_widgets )
{
if( widget.isVisible() )
{
if( widget.suppressKeyPress( c, k ) )
{
return true;
}
}
}
}
else
{
if( m_modalWidget.isVisible() )
{
if( m_modalWidget.suppressKeyPress( c, k ) )
{
return true;
}
}
}
return false;
}
@Override
public void handleMouseInput( int mouseX, int mouseY )
{
if( m_modalWidget == null )
{
for( Widget widget : m_widgets )
{
if( widget.isVisible() )
{
widget.handleMouseInput(
mouseX - getXPosition(),
mouseY - getYPosition()
);
}
}
}
else
{
if( m_modalWidget.isVisible() )
{
m_modalWidget.handleMouseInput(
mouseX - getXPosition(),
mouseY - getYPosition()
);
}
}
}
@Override
public void handleKeyboardInput()
{
if( m_modalWidget == null )
{
for( Widget widget : m_widgets )
{
if( widget.isVisible() )
{
widget.handleKeyboardInput();
}
}
}
else
{
if( m_modalWidget.isVisible() )
{
m_modalWidget.handleKeyboardInput();
}
}
}
@Override
public void mouseClicked( int mouseX, int mouseY, int mouseButton )
{
if( m_modalWidget == null )
{
for( Widget widget : m_widgets )
{
if( widget.isVisible() )
{
widget.mouseClicked(
mouseX - getXPosition(),
mouseY - getYPosition(),
mouseButton
);
}
}
}
else
{
if( m_modalWidget.isVisible() )
{
m_modalWidget.mouseClicked(
mouseX - getXPosition(),
mouseY - getYPosition(),
mouseButton
);
}
}
}
@Override
public void keyTyped( char c, int k )
{
if( m_modalWidget == null )
{
for( Widget widget : m_widgets )
{
if( widget.isVisible() )
{
widget.keyTyped( c, k );
}
}
}
else
{
if( m_modalWidget.isVisible() )
{
m_modalWidget.keyTyped( c, k );
}
}
}
}

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -13,6 +13,7 @@ import dan200.computercraft.core.terminal.TextBuffer;
import dan200.computercraft.shared.computer.core.IComputer;
import dan200.computercraft.shared.computer.core.IComputerContainer;
import dan200.computercraft.shared.util.Colour;
import dan200.computercraft.shared.util.Palette;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
@@ -25,18 +26,18 @@ import java.util.ArrayList;
public class WidgetTerminal extends Widget
{
private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/termBackground.png" );
private static final ResourceLocation background = new ResourceLocation( "computercraft", "textures/gui/term_background.png" );
private static float TERMINATE_TIME = 0.5f;
private IComputerContainer m_computer;
private final IComputerContainer m_computer;
private float m_terminateTimer;
private float m_rebootTimer;
private float m_shutdownTimer;
private int m_lastClickButton;
private int m_lastClickX;
private int m_lastClickY;
private int m_lastClickButton;
private int m_lastClickX;
private int m_lastClickY;
private boolean m_focus;
private boolean m_allowFocusLoss;
@@ -75,7 +76,7 @@ public class WidgetTerminal extends Widget
m_topMargin = topMargin;
m_bottomMargin = bottomMargin;
m_keysDown = new ArrayList<Integer>();
m_keysDown = new ArrayList<>();
}
public void setAllowFocusLoss( boolean allowFocusLoss )
@@ -167,9 +168,9 @@ public class WidgetTerminal extends Widget
@Override
public void mouseClicked( int mouseX, int mouseY, int button )
{
if( mouseX >= getXPosition() && mouseX < getXPosition() + getWidth() &&
mouseY >= getYPosition() && mouseY < getYPosition() + getHeight() )
{
if( mouseX >= getXPosition() && mouseX < getXPosition() + getWidth() &&
mouseY >= getYPosition() && mouseY < getYPosition() + getHeight() )
{
if( !m_focus && button == 0)
{
m_focus = true;
@@ -198,7 +199,7 @@ public class WidgetTerminal extends Widget
}
}
}
}
}
else
{
if( m_focus && button == 0 && m_allowFocusLoss )
@@ -229,8 +230,8 @@ public class WidgetTerminal extends Widget
}
@Override
public void handleMouseInput( int mouseX, int mouseY )
{
public void handleMouseInput( int mouseX, int mouseY )
{
IComputer computer = m_computer.getComputer();
if( mouseX >= getXPosition() && mouseX < getXPosition() + getWidth() &&
mouseY >= getYPosition() && mouseY < getYPosition() + getHeight() &&
@@ -287,159 +288,160 @@ public class WidgetTerminal extends Widget
}
}
}
}
}
@Override
public void update()
{
{
// Handle special keys
if( m_focus && !m_locked && (Keyboard.isKeyDown( 29 ) || Keyboard.isKeyDown( 157 )) )
{
// Ctrl+T for terminate
if( Keyboard.isKeyDown( 20 ) )
{
if( m_terminateTimer < TERMINATE_TIME )
{
m_terminateTimer = m_terminateTimer + 0.05f;
if( m_terminateTimer >= TERMINATE_TIME )
{
if( m_focus && !m_locked && (Keyboard.isKeyDown( 29 ) || Keyboard.isKeyDown( 157 )) )
{
// Ctrl+T for terminate
if( Keyboard.isKeyDown( 20 ) )
{
if( m_terminateTimer < TERMINATE_TIME )
{
m_terminateTimer = m_terminateTimer + 0.05f;
if( m_terminateTimer >= TERMINATE_TIME )
{
queueEvent( "terminate" );
}
}
}
else
{
m_terminateTimer = 0.0f;
}
// Ctrl+R for reboot
if( Keyboard.isKeyDown(19) )
{
if( m_rebootTimer < TERMINATE_TIME )
{
m_rebootTimer = m_rebootTimer + 0.05f;
if( m_rebootTimer >= TERMINATE_TIME )
{
}
}
}
else
{
m_terminateTimer = 0.0f;
}
// Ctrl+R for reboot
if( Keyboard.isKeyDown(19) )
{
if( m_rebootTimer < TERMINATE_TIME )
{
m_rebootTimer = m_rebootTimer + 0.05f;
if( m_rebootTimer >= TERMINATE_TIME )
{
IComputer computer = m_computer.getComputer();
if( computer != null )
{
if( computer != null )
{
computer.reboot();
}
}
}
}
else
{
m_rebootTimer = 0.0f;
}
}
}
}
}
else
{
m_rebootTimer = 0.0f;
}
// Ctrl+S for shutdown
if( Keyboard.isKeyDown(31) )
{
if( m_shutdownTimer < TERMINATE_TIME )
{
m_shutdownTimer = m_shutdownTimer + 0.05f;
if( m_shutdownTimer >= TERMINATE_TIME )
{
// Ctrl+S for shutdown
if( Keyboard.isKeyDown(31) )
{
if( m_shutdownTimer < TERMINATE_TIME )
{
m_shutdownTimer = m_shutdownTimer + 0.05f;
if( m_shutdownTimer >= TERMINATE_TIME )
{
IComputer computer = m_computer.getComputer();
if( computer != null )
{
computer.shutdown();
}
}
}
}
else
{
m_shutdownTimer = 0.0f;
}
}
else
{
m_terminateTimer = 0.0f;
m_rebootTimer = 0.0f;
m_shutdownTimer = 0.0f;
}
}
}
}
}
}
else
{
m_shutdownTimer = 0.0f;
}
}
else
{
m_terminateTimer = 0.0f;
m_rebootTimer = 0.0f;
m_shutdownTimer = 0.0f;
}
}
@Override
public void draw( Minecraft mc, int xOrigin, int yOrigin, int mouseX, int mouseY )
{
int startX = xOrigin + getXPosition();
int startY = yOrigin + getYPosition();
int startX = xOrigin + getXPosition();
int startY = yOrigin + getYPosition();
// Draw the screen contents
IComputer computer = m_computer.getComputer();
Terminal terminal = (computer != null) ? computer.getTerminal() : null;
if( terminal != null )
{
// Draw the terminal
boolean greyscale = !computer.isColour();
synchronized( terminal )
{
// Get the data from the terminal first
// Unfortunately we have to keep the lock for the whole of drawing, so the text doesn't change under us.
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer)ComputerCraft.getFixedWidthFontRenderer();
boolean tblink = m_focus && terminal.getCursorBlink() && ComputerCraft.getGlobalCursorBlink();
int tw = terminal.getWidth();
int th = terminal.getHeight();
int tx = terminal.getCursorX();
int ty = terminal.getCursorY();
int x = startX + m_leftMargin;
int y = startY + m_topMargin;
synchronized( m_computer )
{
// Draw the screen contents
IComputer computer = m_computer.getComputer();
Terminal terminal = ( computer != null ) ? computer.getTerminal() : null;
if( terminal != null )
{
// Draw the terminal
boolean greyscale = !computer.isColour();
Palette palette = terminal.getPalette();
// Get the data from the terminal first
// Unfortunately we have to keep the lock for the whole of drawing, so the text doesn't change under us.
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer) ComputerCraft.getFixedWidthFontRenderer();
boolean tblink = m_focus && terminal.getCursorBlink() && ComputerCraft.getGlobalCursorBlink();
int tw = terminal.getWidth();
int th = terminal.getHeight();
int tx = terminal.getCursorX();
int ty = terminal.getCursorY();
int x = startX + m_leftMargin;
int y = startY + m_topMargin;
// Draw margins
TextBuffer emptyLine = new TextBuffer( ' ', tw );
TextBuffer emptyLine = new TextBuffer( ' ', tw );
if( m_topMargin > 0 )
{
fontRenderer.drawString( emptyLine, x, startY, terminal.getTextColourLine( 0 ), terminal.getBackgroundColourLine( 0 ), m_leftMargin, m_rightMargin, greyscale );
fontRenderer.drawString( emptyLine, x, startY, terminal.getTextColourLine( 0 ), terminal.getBackgroundColourLine( 0 ), m_leftMargin, m_rightMargin, greyscale, palette );
}
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 );
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 )
{
TextBuffer text = terminal.getLine(line);
for( int line = 0; line < th; ++line )
{
TextBuffer text = terminal.getLine( line );
TextBuffer colour = terminal.getTextColourLine( line );
TextBuffer backgroundColour = terminal.getBackgroundColourLine( line );
fontRenderer.drawString( text, x, y, colour, backgroundColour, m_leftMargin, m_rightMargin, greyscale );
if( tblink && ty == line )
{
if( tx >= 0 && tx < tw )
{
TextBuffer cursor = new TextBuffer( '_', 1 );
TextBuffer cursorColour = new TextBuffer( "0123456789abcdef".charAt( terminal.getTextColour() ), 1 );
fontRenderer.drawString(
cursor,
x + FixedWidthFontRenderer.FONT_WIDTH * tx,
y,
cursorColour, null,
0, 0,
greyscale
);
}
}
y = y + FixedWidthFontRenderer.FONT_HEIGHT;
}
}
}
else
{
// Draw a black background
mc.getTextureManager().bindTexture( background );
Colour black = Colour.Black;
GlStateManager.color( black.getR(), black.getG(), black.getB(), 1.0f );
try
fontRenderer.drawString( text, x, y, colour, backgroundColour, m_leftMargin, m_rightMargin, greyscale, palette );
y += FixedWidthFontRenderer.FONT_HEIGHT;
}
if( tblink && tx >= 0 && ty >= 0 && tx < tw && ty < th )
{
TextBuffer cursor = new TextBuffer( '_', 1 );
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
);
}
} else
{
drawTexturedModalRect( startX, startY, 0, 0, getWidth(), getHeight() );
}
finally
{
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
// Draw a black background
mc.getTextureManager().bindTexture( background );
Colour black = Colour.Black;
GlStateManager.color( black.getR(), black.getG(), black.getB(), 1.0f );
try
{
drawTexturedModalRect( startX, startY, 0, 0, getWidth(), getHeight() );
} finally
{
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
}
}
}
}

View File

@@ -1,86 +1,98 @@
/**
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.client.proxy;
import com.google.common.base.Function;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.client.render.TileEntityTurtleRenderer;
import dan200.computercraft.client.render.TurtleSmartItemModel;
import dan200.computercraft.shared.proxy.CCTurtleProxyCommon;
import dan200.computercraft.shared.turtle.blocks.TileTurtle;
import dan200.computercraft.shared.turtle.core.TurtleBrain;
import 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.texture.TextureAtlasSprite;
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.IResourceManager;
import net.minecraft.client.resources.SimpleReloadableResourceManager;
import net.minecraft.client.renderer.block.model.IBakedModel;
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.FMLCommonHandler;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import java.io.IOException;
import javax.annotation.Nonnull;
public class CCTurtleProxyClient extends CCTurtleProxyCommon
{
public CCTurtleProxyClient()
{
}
// IComputerCraftProxy implementation
@Override
public void init()
{
super.init();
// IComputerCraftProxy implementation
@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( ItemStack stack )
public ModelResourceLocation getModelLocation( @Nonnull ItemStack stack )
{
return turtle_dynamic;
}
};
String[] turtleModelNames = new String[] {
"turtle_dynamic",
"CC-Turtle", "CC-TurtleAdvanced",
"turtle_black", "turtle_red", "turtle_green", "turtle_brown",
"turtle_blue", "turtle_purple", "turtle_cyan", "turtle_lightGrey",
"turtle_grey", "turtle_pink", "turtle_lime", "turtle_yellow",
"turtle_lightBlue", "turtle_magenta", "turtle_orange", "turtle_white",
"turtle", "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 );
}
@Override
public void init()
{
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() );
// Setup client forge handlers
registerForgeHandlers();
}
}
private void registerItemModel( Block block, ItemMeshDefinition definition, String[] names )
{
@@ -95,17 +107,32 @@ public class CCTurtleProxyClient extends CCTurtleProxyCommon
resources[i] = new ResourceLocation( "computercraft:" + names[i] );
}
ModelBakery.registerItemVariants( item, resources );
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register( item, definition );
ModelLoader.setCustomMeshDefinition( item, definition );
}
private void registerForgeHandlers()
{
private void registerForgeHandlers()
{
ForgeHandlers handlers = new ForgeHandlers();
MinecraftForge.EVENT_BUS.register( handlers );
}
}
public class ForgeHandlers
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()
@@ -131,22 +158,27 @@ public class CCTurtleProxyClient extends CCTurtleProxyCommon
@SubscribeEvent
public void onTextureStitchEvent( TextureStitchEvent.Pre event )
{
event.getMap().registerSprite( new ResourceLocation( "computercraft", "blocks/craftyUpgrade" ) );
// 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 )
{
loadModel( event, "turtle_modem_off_left" );
loadModel( event, "turtle_modem_on_left" );
loadModel( event, "turtle_modem_off_right" );
loadModel( event, "turtle_modem_on_right" );
loadModel( event, "turtle_crafting_table_left" );
loadModel( event, "turtle_crafting_table_right" );
loadModel( event, "advanced_turtle_modem_off_left" );
loadModel( event, "advanced_turtle_modem_on_left" );
loadModel( event, "advanced_turtle_modem_off_right" );
loadModel( event, "advanced_turtle_modem_on_right" );
// Load all upgrade models
for( String upgrade : TURTLE_UPGRADES )
{
loadModel( event, upgrade );
}
loadSmartModel( event, "turtle_dynamic", m_turtleSmartItemModel );
}
@@ -158,14 +190,7 @@ public class CCTurtleProxyClient extends CCTurtleProxyCommon
IBakedModel bakedModel = model.bake(
model.getDefaultState(),
DefaultVertexFormats.ITEM,
new Function<ResourceLocation, TextureAtlasSprite>()
{
@Override
public TextureAtlasSprite apply( ResourceLocation location )
{
return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite( location.toString() );
}
}
location -> Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite( location.toString() )
);
event.getModelRegistry().putObject(
new ModelResourceLocation( "computercraft:" + name, "inventory" ),
@@ -181,4 +206,20 @@ public class CCTurtleProxyClient extends CCTurtleProxyCommon
);
}
}
private static class TurtleItemColour implements IItemColor
{
@Override
public int colorMultiplier( @Nonnull ItemStack stack, int tintIndex )
{
if( tintIndex == 0 )
{
ItemTurtleBase turtle = (ItemTurtleBase) stack.getItem();
int colour = turtle.getColour( stack );
if( colour != -1 ) return colour;
}
return 0xFFFFFF;
}
}
}

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -8,176 +8,235 @@ package dan200.computercraft.client.proxy;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.client.gui.*;
import dan200.computercraft.client.render.ItemPocketRenderer;
import dan200.computercraft.client.render.ItemPrintoutRenderer;
import dan200.computercraft.client.render.RenderOverlayCable;
import dan200.computercraft.client.render.TileEntityCableRenderer;
import dan200.computercraft.client.render.TileEntityMonitorRenderer;
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.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 gnu.trove.map.hash.TIntIntHashMap;
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.server.MinecraftServer;
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.IThreadListener;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.World;
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.fml.client.FMLClientHandler;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import org.lwjgl.opengl.GL11;
import 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 long m_tick;
private long m_renderFrame;
private FixedWidthFontRenderer m_fixedWidthFontRenderer;
private static TIntIntHashMap lastCounts = new TIntIntHashMap();
public ComputerCraftProxyClient()
{
}
// IComputerCraftProxy implementation
@Override
public void init()
{
super.init();
m_tick = 0;
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;
// Load textures
Minecraft mc = Minecraft.getMinecraft();
m_fixedWidthFontRenderer = new FixedWidthFontRenderer( mc.getTextureManager() );
// Setup client forge handlers
registerForgeHandlers();
}
@SubscribeEvent
public void registerModels( ModelRegistryEvent event )
{
// Register item models
registerItemModel( ComputerCraft.Blocks.computer, new ItemMeshDefinition()
{
private ModelResourceLocation computer = new ModelResourceLocation( "computercraft:CC-Computer", "inventory" );
private ModelResourceLocation computer = new ModelResourceLocation( "computercraft:computer", "inventory" );
private ModelResourceLocation advanced_computer = new ModelResourceLocation( "computercraft:advanced_computer", "inventory" );
@Nonnull
@Override
public ModelResourceLocation getModelLocation( ItemStack stack )
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[]{ "CC-Computer", "advanced_computer" } );
registerItemModel( ComputerCraft.Blocks.peripheral, 0, "CC-Peripheral" );
}, 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, "CC-Cable" );
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, "diskExpanded" );
registerItemModel( ComputerCraft.Items.treasureDisk, "treasureDisk" );
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:pocketComputer", "inventory" );
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 pocket_computer_on_modem_on = new ModelResourceLocation( "computercraft:pocket_computer_on_modem_on", "inventory" );
private ModelResourceLocation pocket_computer_blinking_modem_on = new ModelResourceLocation( "computercraft:pocket_computer_blinking_modem_on", "inventory" );
private ModelResourceLocation advanced_pocket_computer_off = new ModelResourceLocation( "computercraft:advanced_pocket_computer_off", "inventory" );
private ModelResourceLocation advanced_pocket_computer_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 advanced_pocket_computer_on_modem_on = new ModelResourceLocation( "computercraft:advanced_pocket_computer_on_modem_on", "inventory" );
private ModelResourceLocation advanced_pocket_computer_blinking_modem_on = new ModelResourceLocation( "computercraft:advanced_pocket_computer_blinking_modem_on", "inventory" );
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( ItemStack stack )
public ModelResourceLocation getModelLocation( @Nonnull ItemStack stack )
{
ItemPocketComputer itemPocketComputer = (ItemPocketComputer)stack.getItem();
boolean modemOn = itemPocketComputer.getModemState( stack );
switch( itemPocketComputer.getFamily( stack ) )
ItemPocketComputer itemPocketComputer = (ItemPocketComputer) stack.getItem();
ComputerState state = itemPocketComputer.getState( stack );
if( itemPocketComputer.getColour( stack ) == -1 )
{
case Advanced:
switch( itemPocketComputer.getFamily( stack ) )
{
switch( itemPocketComputer.getState( stack ) )
{
case Off:
default:
case Advanced:
switch( state )
{
return advanced_pocket_computer_off;
case Off:
default:
return advanced_pocket_computer_off;
case On:
return advanced_pocket_computer_on;
case Blinking:
return advanced_pocket_computer_blinking;
}
case On:
case Normal:
default:
switch( state )
{
return modemOn ? advanced_pocket_computer_on_modem_on : advanced_pocket_computer_on;
case Off:
default:
return pocket_computer_off;
case On:
return pocket_computer_on;
case Blinking:
return pocket_computer_blinking;
}
case Blinking:
{
return modemOn ? advanced_pocket_computer_blinking_modem_on : advanced_pocket_computer_blinking;
}
}
}
case Normal:
default:
}
else
{
switch( state )
{
switch( itemPocketComputer.getState( stack ) )
{
case Off:
default:
{
return pocket_computer_off;
}
case On:
{
return modemOn ? pocket_computer_on_modem_on : pocket_computer_on;
}
case Blinking:
{
return modemOn ? pocket_computer_blinking_modem_on : pocket_computer_blinking;
}
}
case Off:
default:
return colour_pocket_computer_off;
case On:
return colour_pocket_computer_on;
case Blinking:
return colour_pocket_computer_blinking;
}
}
}
}, new String[] {
"pocketComputer", "pocket_computer_on", "pocket_computer_blinking", "pocket_computer_on_modem_on", "pocket_computer_blinking_modem_on",
"advanced_pocket_computer_off", "advanced_pocket_computer_on", "advanced_pocket_computer_blinking", "advanced_pocket_computer_on_modem_on", "advanced_pocket_computer_blinking_modem_on",
"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 ) ->
{
switch( layer )
{
case 0:
default:
return 0xFFFFFF;
case 1:
{
// Frame colour
int colour = ComputerCraft.Items.pocketComputer.getColour( stack );
return colour == -1 ? 0xFFFFFF : colour;
}
case 2:
{
// Light colour
int colour = ComputerCraft.Items.pocketComputer.getLightState( stack );
return colour == -1 ? Colour.Black.getHex() : colour;
}
}
}, ComputerCraft.Items.pocketComputer );
// Setup renderers
ClientRegistry.bindTileEntitySpecialRenderer( TileMonitor.class, new TileEntityMonitorRenderer() );
// Setup client forge handlers
registerForgeHandlers();
}
ClientRegistry.bindTileEntitySpecialRenderer( TileCable.class, new TileEntityCableRenderer() );
}
private void registerItemModel( Block block, int damage, String name )
{
@@ -188,7 +247,7 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
{
ModelResourceLocation res = new ModelResourceLocation( "computercraft:" + name, "inventory" );
ModelBakery.registerItemVariants( item, new ResourceLocation( "computercraft", name ) );
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register( item, damage, res );
ModelLoader.setCustomModelResourceLocation( item, damage, res );
}
private void registerItemModel( Block block, String name )
@@ -200,10 +259,11 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
{
final ModelResourceLocation res = new ModelResourceLocation( "computercraft:" + name, "inventory" );
ModelBakery.registerItemVariants( item, new ResourceLocation( "computercraft", name ) );
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register( item, new ItemMeshDefinition()
ModelLoader.setCustomMeshDefinition( item, new ItemMeshDefinition()
{
@Nonnull
@Override
public ModelResourceLocation getModelLocation( ItemStack stack )
public ModelResourceLocation getModelLocation( @Nonnull ItemStack stack )
{
return res;
}
@@ -223,20 +283,20 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
resources[i] = new ResourceLocation( "computercraft", names[i] );
}
ModelBakery.registerItemVariants( item, resources );
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register( item, definition );
ModelLoader.setCustomMeshDefinition( item, definition );
}
@Override
public boolean isClient()
{
return true;
}
@Override
public boolean getGlobalCursorBlink()
{
return ( m_tick / 8) % 2 == 0;
}
@Override
public boolean isClient()
{
return true;
}
@Override
public boolean getGlobalCursorBlink()
{
return ( m_tick / 8) % 2 == 0;
}
@Override
public long getRenderFrame()
@@ -245,57 +305,40 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
}
@Override
public void deleteDisplayLists( int list, int range )
public Object getFixedWidthFontRenderer()
{
GL11.glDeleteLists( list, range );
return m_fixedWidthFontRenderer;
}
@Override
public Object getFixedWidthFontRenderer()
{
return m_fixedWidthFontRenderer;
}
@Override
public String getRecordInfo( ItemStack recordStack )
{
List info = new ArrayList(1);
recordStack.getItem().addInformation( recordStack, null, info, false );
if( info.size() > 0 ) {
return info.get(0).toString();
} else {
return super.getRecordInfo( recordStack );
}
}
@Override
public void playRecord( SoundEvent record, String recordInfo, World world, BlockPos pos )
{
Minecraft mc = FMLClientHandler.instance().getClient();
world.playRecord( pos, record );
if( record != null )
{
mc.ingameGUI.setRecordPlayingMessage( recordInfo );
}
}
@Override
public Object getDiskDriveGUI( InventoryPlayer inventory, TileDiskDrive drive )
{
return new GuiDiskDrive( inventory, drive );
}
@Override
public Object getComputerGUI( TileComputer computer )
{
return new GuiComputer( computer );
}
@Override
public Object getPrinterGUI( InventoryPlayer inventory, TilePrinter printer )
{
return new GuiPrinter( inventory, printer );
}
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 )
@@ -304,32 +347,39 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
}
@Override
public Object getPrintoutGUI( InventoryPlayer inventory )
{
ContainerHeldItem container = new ContainerHeldItem( inventory );
if( container.getStack() != null && container.getStack().getItem() instanceof ItemPrintout )
public Object getPrintoutGUI( EntityPlayer player, EnumHand hand )
{
ContainerHeldItem container = new ContainerHeldItem( player, hand );
if( container.getStack().getItem() instanceof ItemPrintout )
{
return new GuiPrintout( container );
return new GuiPrintout( container );
}
return null;
}
}
@Override
public Object getPocketComputerGUI( InventoryPlayer inventory )
public Object getPocketComputerGUI( EntityPlayer player, EnumHand hand )
{
ContainerHeldItem container = new ContainerHeldItem( inventory );
if( container.getStack() != null && container.getStack().getItem() instanceof ItemPocketComputer )
ContainerPocketComputer container = new ContainerPocketComputer( player, hand );
if( container.getStack().getItem() instanceof ItemPocketComputer )
{
return new GuiPocketComputer( container );
}
return null;
}
@Override
public File getWorldDir( World world )
{
@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 )
@@ -337,7 +387,10 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
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();
@@ -349,14 +402,7 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
}
else
{
listener.addScheduledTask( new Runnable()
{
@Override
public void run()
{
processPacket( packet, player );
}
} );
listener.addScheduledTask( () -> processPacket( packet, player ) );
}
}
break;
@@ -378,13 +424,14 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
// 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, (EntityPlayer) player );
ComputerCraft.clientComputerRegistry.get( instanceID ).handlePacket( packet, player );
break;
}
case ComputerCraftPacket.ComputerDeleted:
@@ -396,21 +443,69 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
}
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();
FMLCommonHandler.instance().bus().register( handlers );
private void registerForgeHandlers()
{
ForgeHandlers handlers = new ForgeHandlers();
MinecraftForge.EVENT_BUS.register( handlers );
}
public class ForgeHandlers
{
public ForgeHandlers()
{
}
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 )
@@ -490,5 +585,31 @@ public class ComputerCraftProxyClient extends ComputerCraftProxyCommon
m_renderFrame++;
}
}
}
@SubscribeEvent
public void onWorldUnload( WorldEvent.Unload event )
{
if( event.getWorld().isRemote )
{
ClientMonitor.destroyAll();
}
}
}
@SideOnly(Side.CLIENT)
private static class DiskColorHandler implements IItemColor
{
private final ItemDiskLegacy disk;
private DiskColorHandler( ItemDiskLegacy disk )
{
this.disk = disk;
}
@Override
public int colorMultiplier( @Nonnull ItemStack stack, int layer )
{
return layer == 0 ? 0xFFFFFF : disk.getColour( stack );
}
}
}

View File

@@ -0,0 +1,264 @@
package dan200.computercraft.client.render;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.client.gui.FixedWidthFontRenderer;
import dan200.computercraft.core.terminal.Terminal;
import dan200.computercraft.core.terminal.TextBuffer;
import dan200.computercraft.shared.computer.core.ClientComputer;
import dan200.computercraft.shared.pocket.items.ItemPocketComputer;
import dan200.computercraft.shared.util.Palette;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.ItemRenderer;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumHandSide;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.event.RenderSpecificHandEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
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;
import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_WIDTH;
/**
* Emulates map rendering for pocket computers
*/
@SideOnly(Side.CLIENT)
public class ItemPocketRenderer
{
@SubscribeEvent
public 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();
}
/**
* 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 )
{
// Setup various transformations. Note that these are partially adapated from the corresponding method
// in ItemRenderer
GlStateManager.disableLighting();
GlStateManager.rotate( 180f, 0f, 1f, 0f );
GlStateManager.rotate( 180f, 0f, 0f, 1f );
GlStateManager.scale( 0.5, 0.5, 0.5 );
ItemPocketComputer pocketComputer = ComputerCraft.Items.pocketComputer;
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.
GlStateManager.pushMatrix();
GlStateManager.scale( 1.0f, -1.0f, 1.0f );
Minecraft minecraft = Minecraft.getMinecraft();
TextureManager textureManager = minecraft.getTextureManager();
RenderItem renderItem = minecraft.getRenderItem();
// Copy of RenderItem#renderItemModelIntoGUI but without the translation or scaling
textureManager.bindTexture( TextureMap.LOCATION_BLOCKS_TEXTURE );
textureManager.getTexture( TextureMap.LOCATION_BLOCKS_TEXTURE ).setBlurMipmap( false, false );
GlStateManager.enableRescaleNormal();
GlStateManager.enableAlpha();
GlStateManager.alphaFunc( GL11.GL_GREATER, 0.1F );
GlStateManager.enableBlend();
GlStateManager.blendFunc( GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA );
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
IBakedModel bakedmodel = renderItem.getItemModelWithOverrides( stack, null, null );
bakedmodel = ForgeHooksClient.handleCameraTransforms( bakedmodel, ItemCameraTransforms.TransformType.GUI, false );
renderItem.renderItem( stack, bakedmodel );
GlStateManager.disableAlpha();
GlStateManager.disableRescaleNormal();
GlStateManager.popMatrix();
}
// If we've a computer and terminal then attempt to render it.
if( computer != null )
{
Terminal terminal = computer.getTerminal();
if( terminal != null )
{
synchronized( terminal )
{
GlStateManager.pushMatrix();
GlStateManager.disableDepth();
// Reset the position to be at the top left corner of the pocket computer
// Note we translate towards the screen slightly too.
GlStateManager.translate( -8 / 16.0, -8 / 16.0, 0.5 / 16.0 );
// Translate to the top left of the screen.
GlStateManager.translate( 4 / 16.0, 3 / 16.0, 0 );
// Work out the scaling required to resize the terminal in order to fit on the computer
final int margin = 2;
int tw = terminal.getWidth();
int th = terminal.getHeight();
int width = tw * FONT_WIDTH + margin * 2;
int height = th * FONT_HEIGHT + margin * 2;
int max = Math.max( height, width );
// The grid is 8 * 8 wide, so we start with a base of 1/2 (8 / 16).
double scale = 1.0 / 2.0 / max;
GlStateManager.scale( scale, scale, scale );
// The margin/start positions are determined in order for the terminal to be centred.
int startX = (max - width) / 2 + margin;
int startY = (max - height) / 2 + margin;
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer) ComputerCraft.getFixedWidthFontRenderer();
boolean greyscale = !computer.isColour();
Palette palette = terminal.getPalette();
// Render the actual text
for( int line = 0; line < th; ++line )
{
TextBuffer text = terminal.getLine( line );
TextBuffer colour = terminal.getTextColourLine( line );
TextBuffer backgroundColour = terminal.getBackgroundColourLine( line );
fontRenderer.drawString(
text, startX, startY + line * FONT_HEIGHT,
colour, backgroundColour, margin, margin, greyscale, palette
);
}
// And render the cursor;
int tx = terminal.getCursorX(), ty = terminal.getCursorY();
if( terminal.getCursorBlink() && ComputerCraft.getGlobalCursorBlink() &&
tx >= 0 && ty >= 0 && tx < tw && ty < th )
{
TextBuffer cursorColour = new TextBuffer( "0123456789abcdef".charAt( terminal.getTextColour() ), 1 );
fontRenderer.drawString(
new TextBuffer( '_', 1 ), startX + FONT_WIDTH * tx, startY + FONT_HEIGHT * ty,
cursorColour, null, 0, 0, greyscale, palette
);
}
GlStateManager.enableDepth();
GlStateManager.popMatrix();
}
}
}
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

@@ -0,0 +1,197 @@
package dan200.computercraft.client.render;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.shared.media.items.ItemPrintout;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.ItemRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumHandSide;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.client.event.RenderItemInFrameEvent;
import net.minecraftforge.client.event.RenderSpecificHandEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT;
import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_WIDTH;
import static dan200.computercraft.client.render.PrintoutRenderer.*;
import static dan200.computercraft.shared.media.items.ItemPrintout.LINES_PER_PAGE;
import static dan200.computercraft.shared.media.items.ItemPrintout.LINE_MAX_LENGTH;
public class ItemPrintoutRenderer
{
@SubscribeEvent
public 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();
}
/**
* 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 )
{
// Setup various transformations. Note that these are partially adapated from the corresponding method
// in ItemRenderer.renderMapFirstPerson
GlStateManager.disableLighting();
GlStateManager.rotate( 180f, 0f, 1f, 0f );
GlStateManager.rotate( 180f, 0f, 0f, 1f );
GlStateManager.scale( 0.42f, 0.42f, -0.42f );
GlStateManager.translate( -0.5f, -0.48f, 0.0f );
drawPrintout( stack );
GlStateManager.enableLighting();
}
@SubscribeEvent
public void onRenderInFrame( RenderItemInFrameEvent event )
{
ItemStack stack = event.getItem();
if( stack.getItem() != ComputerCraft.Items.printout ) return;
event.setCanceled( true );
GlStateManager.disableLighting();
// Move a little bit forward to ensure we're not clipping with the frame
GlStateManager.translate( 0.0f, 0.0f, -0.001f );
GlStateManager.rotate( 180f, 0f, 0f, 1f );
GlStateManager.scale( 0.95f, 0.95f, -0.95f );
GlStateManager.translate( -0.5f, -0.5f, 0.0f );
drawPrintout( stack );
GlStateManager.enableLighting();
}
private static void drawPrintout( ItemStack stack )
{
int pages = ItemPrintout.getPageCount( stack );
boolean book = ItemPrintout.getType( stack ) == ItemPrintout.Type.Book;
double width = LINE_MAX_LENGTH * FONT_WIDTH + X_TEXT_MARGIN * 2;
double height = LINES_PER_PAGE * FONT_HEIGHT + Y_TEXT_MARGIN * 2;
// Non-books will be left aligned
if( !book ) width += offsetAt( pages );
double visualWidth = width, visualHeight = height;
// Meanwhile books will be centred
if( book )
{
visualWidth += 2 * COVER_SIZE + 2 * offsetAt( pages );
visualHeight += 2 * COVER_SIZE;
}
double max = Math.max( visualHeight, visualWidth );
// Scale the printout to fit correctly.
double scale = 1.0 / max;
GlStateManager.scale( scale, scale, scale );
GlStateManager.translate( (max - width) / 2.0f, (max - height) / 2.0f, 0.0f );
drawBorder( 0, 0, -0.01, 0, pages, book );
drawText( X_TEXT_MARGIN, Y_TEXT_MARGIN, 0, ItemPrintout.getText( stack ), ItemPrintout.getColours( stack ) );
}
}

View File

@@ -0,0 +1,264 @@
package dan200.computercraft.client.render;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.pipeline.IVertexConsumer;
import net.minecraftforge.client.model.pipeline.LightUtil;
import net.minecraftforge.client.model.pipeline.VertexTransformer;
import net.minecraftforge.common.model.TRSRTransformation;
import javax.annotation.Nonnull;
import javax.vecmath.Matrix4f;
import javax.vecmath.Point3f;
import javax.vecmath.Vector3f;
import java.util.List;
/**
* Transforms vertices of a model, remaining aware of winding order, and rearranging
* vertices if needed.
*/
public final class ModelTransformer
{
private static final Matrix4f identity;
static
{
identity = new Matrix4f();
identity.setIdentity();
}
private ModelTransformer()
{
}
public static void transformQuadsTo( List<BakedQuad> output, List<BakedQuad> input, Matrix4f transform )
{
if( transform == null || transform.equals( identity ) )
{
output.addAll( input );
}
else
{
Matrix4f normalMatrix = new Matrix4f( transform );
normalMatrix.invert();
normalMatrix.transpose();
for( BakedQuad quad : input ) output.add( doTransformQuad( quad, transform, normalMatrix ) );
}
}
public static BakedQuad transformQuad( BakedQuad input, Matrix4f transform )
{
if( transform == null || transform.equals( identity ) ) return input;
Matrix4f normalMatrix = new Matrix4f( transform );
normalMatrix.invert();
normalMatrix.transpose();
return doTransformQuad( input, transform, normalMatrix );
}
private static BakedQuad doTransformQuad( BakedQuad input, Matrix4f positionMatrix, Matrix4f normalMatrix )
{
BakedQuadBuilder builder = new BakedQuadBuilder( input.getFormat() );
NormalAwareTransformer transformer = new NormalAwareTransformer( builder, positionMatrix, normalMatrix );
input.pipe( transformer );
if( transformer.areNormalsInverted() )
{
builder.swap( 1, 3 );
transformer.areNormalsInverted();
}
return builder.build();
}
/**
* A vertex transformer that tracks whether the normals have been inverted and so the vertices
* should be reordered so backface culling works as expected.
*/
private static class NormalAwareTransformer extends VertexTransformer
{
private final Matrix4f positionMatrix;
private final Matrix4f normalMatrix;
private int vertexIndex = 0, elementIndex = 0;
private final Point3f[] before = new Point3f[ 4 ];
private final Point3f[] after = new Point3f[ 4 ];
public NormalAwareTransformer( IVertexConsumer parent, Matrix4f positionMatrix, Matrix4f normalMatrix )
{
super( parent );
this.positionMatrix = positionMatrix;
this.normalMatrix = normalMatrix;
}
@Override
public void setQuadOrientation( EnumFacing orientation )
{
super.setQuadOrientation( orientation == null ? orientation : TRSRTransformation.rotate( positionMatrix, orientation ) );
}
@Override
public void put( int element, @Nonnull float... data )
{
switch( getVertexFormat().getElement( element ).getUsage() )
{
case POSITION:
{
Point3f vec = new Point3f( data );
Point3f newVec = new Point3f();
positionMatrix.transform( vec, newVec );
float[] newData = new float[ 4 ];
newVec.get( newData );
super.put( element, newData );
before[ vertexIndex ] = vec;
after[ vertexIndex ] = newVec;
break;
}
case NORMAL:
{
Vector3f vec = new Vector3f( data );
normalMatrix.transform( vec );
float[] newData = new float[ 4 ];
vec.get( newData );
super.put( element, newData );
break;
}
default:
super.put( element, data );
break;
}
elementIndex++;
if( elementIndex == getVertexFormat().getElementCount() )
{
vertexIndex++;
elementIndex = 0;
}
}
public boolean areNormalsInverted()
{
Vector3f temp1 = new Vector3f(), temp2 = new Vector3f();
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 ] );
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 ] );
crossAfter.cross( temp1, temp2 );
// 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;
}
}
/**
* A vertex consumer which is capable of building {@link BakedQuad}s.
*
* Equivalent to {@link net.minecraftforge.client.model.pipeline.UnpackedBakedQuad.Builder} but more memory
* efficient.
*
* This also provides the ability to swap vertices through {@link #swap(int, int)} to allow reordering.
*/
private static class BakedQuadBuilder implements IVertexConsumer
{
private final VertexFormat format;
private final int[] vertexData;
private int vertexIndex = 0, elementIndex = 0;
private EnumFacing orientation;
private int quadTint;
private boolean diffuse;
private TextureAtlasSprite texture;
private BakedQuadBuilder( VertexFormat format )
{
this.format = format;
this.vertexData = new int[ format.getSize() ];
}
@Nonnull
@Override
public VertexFormat getVertexFormat()
{
return format;
}
@Override
public void setQuadTint( int tint )
{
this.quadTint = tint;
}
@Override
public void setQuadOrientation( @Nonnull EnumFacing orientation )
{
this.orientation = orientation;
}
@Override
public void setApplyDiffuseLighting( boolean diffuse )
{
this.diffuse = diffuse;
}
@Override
public void setTexture( @Nonnull TextureAtlasSprite texture )
{
this.texture = texture;
}
@Override
public void put( int element, @Nonnull float... data )
{
LightUtil.pack( data, vertexData, format, vertexIndex, element );
elementIndex++;
if( elementIndex == getVertexFormat().getElementCount() )
{
vertexIndex++;
elementIndex = 0;
}
}
public void swap( int a, int b )
{
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;
}
}
public BakedQuad build()
{
if( elementIndex != 0 || vertexIndex != 4 )
{
throw new IllegalStateException( "Got an unexpected number of elements/vertices" );
}
if( texture == null )
{
throw new IllegalStateException( "Texture has not been set" );
}
return new BakedQuad( vertexData, quadTint, orientation, texture, diffuse, format );
}
}
}

View File

@@ -0,0 +1,169 @@
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;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT;
import static dan200.computercraft.shared.media.items.ItemPrintout.LINES_PER_PAGE;
public class PrintoutRenderer
{
private static final ResourceLocation BG = new ResourceLocation( "computercraft", "textures/gui/printout.png" );
private static final double BG_SIZE = 256.0;
/**
* Width of a page
*/
public static final int X_SIZE = 172;
/**
* Height of a page
*/
public static final int Y_SIZE = 209;
/**
* Padding between the left and right of a page and the text
*/
public static final int X_TEXT_MARGIN = 13;
/**
* Padding between the top and bottom of a page and the text
*/
public static final int Y_TEXT_MARGIN = 11;
/**
* Width of the extra page texture
*/
private static final int X_FOLD_SIZE = 12;
/**
* Size of the leather cover
*/
public static final int COVER_SIZE = 12;
private static final int COVER_Y = Y_SIZE;
private static final int COVER_X = X_SIZE + 4 * X_FOLD_SIZE;
public static void drawText( int x, int y, int start, TextBuffer[] text, TextBuffer[] colours )
{
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer) ComputerCraft.getFixedWidthFontRenderer();
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 );
}
}
public static void drawText( int x, int y, int start, String[] text, String[] colours )
{
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
GlStateManager.enableBlend();
GlStateManager.enableTexture2D();
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer) ComputerCraft.getFixedWidthFontRenderer();
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 );
}
}
public static void drawBorder( double x, double y, double z, int page, int pages, boolean isBook )
{
GlStateManager.color( 1.0f, 1.0f, 1.0f, 1.0f );
GlStateManager.enableBlend();
GlStateManager.enableTexture2D();
Minecraft.getMinecraft().getTextureManager().bindTexture( BG );
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder buffer = tessellator.getBuffer();
buffer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX );
int leftPages = page;
int rightPages = pages - page - 1;
if( isBook )
{
// Border
double offset = offsetAt( pages );
final double left = x - 4 - offset;
final double right = x + X_SIZE + offset - 4;
// Left and right border
drawTexture( buffer, left - 4, y - 8, z - 0.02, COVER_X, 0, COVER_SIZE, Y_SIZE + COVER_SIZE * 2 );
drawTexture( buffer, right, y - 8, z - 0.02, COVER_X + COVER_SIZE, 0, COVER_SIZE, Y_SIZE + COVER_SIZE * 2 );
// 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
);
double borderX = left;
while( borderX < right )
{
double thisWidth = Math.min( right - borderX, X_SIZE );
drawTexture( buffer, borderX, y - 8, z - 0.02, 0, COVER_Y, thisWidth, COVER_SIZE );
drawTexture( buffer, borderX, y + Y_SIZE - 4, z - 0.02, 0, COVER_Y + COVER_SIZE, thisWidth, COVER_SIZE );
borderX += thisWidth;
}
}
// Left half
drawTexture( buffer, x, y, z, X_FOLD_SIZE * 2, 0, X_SIZE / 2, Y_SIZE );
for( int n = 0; n <= leftPages; n++ )
{
drawTexture( buffer,
x - offsetAt( n ), y, z - 1e-3 * n,
// Use the left "bold" fold for the outermost page
n == leftPages ? 0 : X_FOLD_SIZE, 0,
X_FOLD_SIZE, Y_SIZE
);
}
// Right half
drawTexture( buffer, x + X_SIZE / 2, y, z, X_FOLD_SIZE * 2 + X_SIZE / 2, 0, X_SIZE / 2, Y_SIZE );
for( int n = 0; n <= rightPages; n++ )
{
drawTexture( buffer,
x + (X_SIZE - X_FOLD_SIZE) + offsetAt( n ), y, z - 1e-3 * n,
// Two folds, then the main page. Use the right "bold" fold for the outermost page.
X_FOLD_SIZE * 2 + X_SIZE + (n == rightPages ? X_FOLD_SIZE : 0), 0,
X_FOLD_SIZE, Y_SIZE
);
}
tessellator.draw();
}
private static void drawTexture( BufferBuilder buffer, double x, double y, double z, double u, double v, double width, double height )
{
buffer.pos( x, y + height, z ).tex( u / BG_SIZE, (v + height) / BG_SIZE ).endVertex();
buffer.pos( x + width, y + height, z ).tex( (u + width) / BG_SIZE, (v + height) / BG_SIZE ).endVertex();
buffer.pos( x + width, y, z ).tex( (u + width) / BG_SIZE, v / BG_SIZE ).endVertex();
buffer.pos( x, y, z ).tex( u / BG_SIZE, v / BG_SIZE ).endVertex();
}
private static void drawTexture( BufferBuilder buffer, double x, double y, double z, double width, double height, double u, double v, double tWidth, double tHeight )
{
buffer.pos( x, y + height, z ).tex( u / BG_SIZE, (v + tHeight) / BG_SIZE ).endVertex();
buffer.pos( x + width, y + height, z ).tex( (u + tWidth) / BG_SIZE, (v + tHeight) / BG_SIZE ).endVertex();
buffer.pos( x + width, y, z ).tex( (u + tWidth) / BG_SIZE, v / BG_SIZE ).endVertex();
buffer.pos( x, y, z ).tex( u / BG_SIZE, v / BG_SIZE ).endVertex();
}
public static double offsetAt( int page )
{
return 32 * (1 - Math.pow( 1.2, -page ));
}
}

View File

@@ -0,0 +1,213 @@
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.util.WorldUtil;
import net.minecraft.block.state.IBlockState;
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.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.eventhandler.SubscribeEvent;
import org.lwjgl.opengl.GL11;
public class RenderOverlayCable
{
private static final float EXPAND = 0.002f;
private static final double MIN = TileCable.MIN - EXPAND;
private static final double MAX = TileCable.MAX + EXPAND;
@SubscribeEvent
public void drawHighlight( DrawBlockHighlightEvent event )
{
if( event.getTarget().typeOfHit != RayTraceResult.Type.BLOCK ) return;
BlockPos pos = event.getTarget().getBlockPos();
World world = event.getPlayer().getEntityWorld();
IBlockState state = world.getBlockState( pos );
if( state.getBlock() != ComputerCraft.Blocks.cable ) return;
TileEntity tile = world.getTileEntity( pos );
if( tile == null || !(tile instanceof TileCable) ) return;
event.setCanceled( true );
TileCable cable = (TileCable) tile;
PeripheralType type = cable.getPeripheralType();
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0 );
GlStateManager.color( 0.0f, 0.0f, 0.0f, 0.4f );
GL11.glLineWidth( 2.0F );
GlStateManager.disableTexture2D();
GlStateManager.depthMask( false );
GlStateManager.pushMatrix();
{
EntityPlayer player = event.getPlayer();
double x = player.lastTickPosX + (player.posX - player.lastTickPosX) * event.getPartialTicks();
double y = player.lastTickPosY + (player.posY - player.lastTickPosY) * event.getPartialTicks();
double z = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * event.getPartialTicks();
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() ) ) )
{
RenderGlobal.drawSelectionBoundingBox( cable.getModemBounds(), 0, 0, 0, 0.4f );
}
else
{
int flags = 0;
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder buffer = tessellator.getBuffer();
for( EnumFacing facing : EnumFacing.VALUES )
{
if( BlockCable.doesConnectVisually( state, world, pos, facing ) )
{
flags |= 1 << facing.ordinal();
switch( facing.getAxis() )
{
case X:
{
double offset = facing == EnumFacing.WEST ? -EXPAND : 1 + EXPAND;
double centre = facing == EnumFacing.WEST ? MIN : MAX;
buffer.begin( GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION );
buffer.pos( offset, MIN, MIN ).endVertex();
buffer.pos( offset, MAX, MIN ).endVertex();
buffer.pos( offset, MAX, MAX ).endVertex();
buffer.pos( offset, MIN, MAX ).endVertex();
buffer.pos( offset, MIN, MIN ).endVertex();
tessellator.draw();
buffer.begin( GL11.GL_LINES, DefaultVertexFormats.POSITION );
buffer.pos( offset, MIN, MIN ).endVertex();
buffer.pos( centre, MIN, MIN ).endVertex();
buffer.pos( offset, MAX, MIN ).endVertex();
buffer.pos( centre, MAX, MIN ).endVertex();
buffer.pos( offset, MAX, MAX ).endVertex();
buffer.pos( centre, MAX, MAX ).endVertex();
buffer.pos( offset, MIN, MAX ).endVertex();
buffer.pos( centre, MIN, MAX ).endVertex();
tessellator.draw();
break;
}
case Y:
{
double offset = facing == EnumFacing.DOWN ? -EXPAND : 1 + EXPAND;
double centre = facing == EnumFacing.DOWN ? MIN : MAX;
buffer.begin( GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION );
buffer.pos( MIN, offset, MIN ).endVertex();
buffer.pos( MAX, offset, MIN ).endVertex();
buffer.pos( MAX, offset, MAX ).endVertex();
buffer.pos( MIN, offset, MAX ).endVertex();
buffer.pos( MIN, offset, MIN ).endVertex();
tessellator.draw();
buffer.begin( GL11.GL_LINES, DefaultVertexFormats.POSITION );
buffer.pos( MIN, offset, MIN ).endVertex();
buffer.pos( MIN, centre, MIN ).endVertex();
buffer.pos( MAX, offset, MIN ).endVertex();
buffer.pos( MAX, centre, MIN ).endVertex();
buffer.pos( MAX, offset, MAX ).endVertex();
buffer.pos( MAX, centre, MAX ).endVertex();
buffer.pos( MIN, offset, MAX ).endVertex();
buffer.pos( MIN, centre, MAX ).endVertex();
tessellator.draw();
break;
}
case Z:
{
double offset = facing == EnumFacing.NORTH ? -EXPAND : 1 + EXPAND;
double centre = facing == EnumFacing.NORTH ? MIN : MAX;
buffer.begin( GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION );
buffer.pos( MIN, MIN, offset ).endVertex();
buffer.pos( MAX, MIN, offset ).endVertex();
buffer.pos( MAX, MAX, offset ).endVertex();
buffer.pos( MIN, MAX, offset ).endVertex();
buffer.pos( MIN, MIN, offset ).endVertex();
tessellator.draw();
buffer.begin( GL11.GL_LINES, DefaultVertexFormats.POSITION );
buffer.pos( MIN, MIN, offset ).endVertex();
buffer.pos( MIN, MIN, centre ).endVertex();
buffer.pos( MAX, MIN, offset ).endVertex();
buffer.pos( MAX, MIN, centre ).endVertex();
buffer.pos( MAX, MAX, offset ).endVertex();
buffer.pos( MAX, MAX, centre ).endVertex();
buffer.pos( MIN, MAX, offset ).endVertex();
buffer.pos( MIN, MAX, centre ).endVertex();
tessellator.draw();
break;
}
}
}
}
buffer.begin( GL11.GL_LINES, DefaultVertexFormats.POSITION );
draw( buffer, flags, EnumFacing.WEST, EnumFacing.DOWN, EnumFacing.Axis.Z );
draw( buffer, flags, EnumFacing.WEST, EnumFacing.UP, EnumFacing.Axis.Z );
draw( buffer, flags, EnumFacing.EAST, EnumFacing.DOWN, EnumFacing.Axis.Z );
draw( buffer, flags, EnumFacing.EAST, EnumFacing.UP, EnumFacing.Axis.Z );
draw( buffer, flags, EnumFacing.WEST, EnumFacing.NORTH, EnumFacing.Axis.Y );
draw( buffer, flags, EnumFacing.WEST, EnumFacing.SOUTH, EnumFacing.Axis.Y );
draw( buffer, flags, EnumFacing.EAST, EnumFacing.NORTH, EnumFacing.Axis.Y );
draw( buffer, flags, EnumFacing.EAST, EnumFacing.SOUTH, EnumFacing.Axis.Y );
draw( buffer, flags, EnumFacing.DOWN, EnumFacing.NORTH, EnumFacing.Axis.X );
draw( buffer, flags, EnumFacing.DOWN, EnumFacing.SOUTH, EnumFacing.Axis.X );
draw( buffer, flags, EnumFacing.UP, EnumFacing.NORTH, EnumFacing.Axis.X );
draw( buffer, flags, EnumFacing.UP, EnumFacing.SOUTH, EnumFacing.Axis.X );
tessellator.draw();
}
GlStateManager.popMatrix();
GlStateManager.depthMask( true );
GlStateManager.enableTexture2D();
GlStateManager.disableBlend();
}
private static void draw( BufferBuilder buffer, int flags, EnumFacing a, EnumFacing b, EnumFacing.Axis other )
{
if( ((flags >> a.ordinal()) & 1) != ((flags >> b.ordinal()) & 1) ) return;
double offA = a.getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE ? MIN : MAX;
double offB = b.getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE ? MIN : MAX;
switch( other )
{
case X:
buffer.pos( MIN, offA, offB ).endVertex();
buffer.pos( MAX, offA, offB ).endVertex();
break;
case Y:
buffer.pos( offA, MIN, offB ).endVertex();
buffer.pos( offA, MAX, offB ).endVertex();
break;
case Z:
buffer.pos( offA, offB, MIN ).endVertex();
buffer.pos( offA, offB, MAX ).endVertex();
break;
}
}
}

View File

@@ -0,0 +1,122 @@
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.util.WorldUtil;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
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;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.MinecraftForgeClient;
import org.lwjgl.opengl.GL11;
import javax.annotation.Nonnull;
/**
* Render breaking animation only over part of a {@link TileCable}.
*/
public class TileEntityCableRenderer extends TileEntitySpecialRenderer<TileCable>
{
@Override
public void render( @Nonnull TileCable te, double x, double y, double z, float partialTicks, int destroyStage, float alpha )
{
if( destroyStage < 0 ) return;
BlockPos pos = te.getPos();
Minecraft mc = Minecraft.getMinecraft();
RayTraceResult hit = mc.objectMouseOver;
if( hit == null || !hit.getBlockPos().equals( pos ) ) return;
if( MinecraftForgeClient.getRenderPass() != 0 ) return;
World world = te.getWorld();
IBlockState state = world.getBlockState( pos );
Block block = state.getBlock();
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() ) ) )
{
state = block.getDefaultState().withProperty( BlockCable.Properties.MODEM, state.getValue( BlockCable.Properties.MODEM ) );
}
else
{
state = state.withProperty( BlockCable.Properties.MODEM, BlockCableModemVariant.None );
}
IBakedModel model = mc.getBlockRendererDispatcher().getModelForState( state );
if( model == null ) return;
preRenderDamagedBlocks();
BufferBuilder buffer = Tessellator.getInstance().getBuffer();
buffer.begin( GL11.GL_QUADS, DefaultVertexFormats.BLOCK );
buffer.setTranslation( x - pos.getX(), y - pos.getY(), z - pos.getZ() );
buffer.noColor();
ForgeHooksClient.setRenderLayer( block.getRenderLayer() );
// See BlockRendererDispatcher#renderBlockDamage
TextureAtlasSprite breakingTexture = mc.getTextureMapBlocks().getAtlasSprite( "minecraft:blocks/destroy_stage_" + destroyStage );
Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelRenderer().renderModel(
world,
ForgeHooksClient.getDamageModel( model, breakingTexture, state, world, pos ),
state, pos, buffer, true
);
ForgeHooksClient.setRenderLayer( BlockRenderLayer.SOLID );
buffer.setTranslation( 0, 0, 0 );
Tessellator.getInstance().draw();
postRenderDamagedBlocks();
}
/**
* @see RenderGlobal#preRenderDamagedBlocks()
*/
private void preRenderDamagedBlocks()
{
GlStateManager.disableLighting();
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate( GlStateManager.SourceFactor.DST_COLOR, GlStateManager.DestFactor.SRC_COLOR, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO );
GlStateManager.enableBlend();
GlStateManager.color( 1.0F, 1.0F, 1.0F, 0.5F );
GlStateManager.doPolygonOffset( -3.0F, -3.0F );
GlStateManager.enablePolygonOffset();
GlStateManager.alphaFunc( 516, 0.1F );
GlStateManager.enableAlpha();
GlStateManager.pushMatrix();
}
/**
* @see RenderGlobal#postRenderDamagedBlocks()
*/
private void postRenderDamagedBlocks()
{
GlStateManager.disableAlpha();
GlStateManager.doPolygonOffset( 0.0F, 0.0F );
GlStateManager.disablePolygonOffset();
GlStateManager.disablePolygonOffset();
GlStateManager.depthMask( true );
GlStateManager.popMatrix();
}
}

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -10,22 +10,20 @@ import dan200.computercraft.ComputerCraft;
import dan200.computercraft.client.gui.FixedWidthFontRenderer;
import dan200.computercraft.core.terminal.Terminal;
import dan200.computercraft.core.terminal.TextBuffer;
import dan200.computercraft.shared.common.ClientTerminal;
import dan200.computercraft.shared.common.ITerminal;
import dan200.computercraft.shared.peripheral.monitor.ClientMonitor;
import dan200.computercraft.shared.peripheral.monitor.TileMonitor;
import dan200.computercraft.shared.util.Colour;
import dan200.computercraft.shared.util.DirectionUtil;
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.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraft.util.math.BlockPos;
import org.lwjgl.opengl.GL11;
public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMonitor>
@@ -35,7 +33,7 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
}
@Override
public void renderTileEntityAt( TileMonitor tileEntity, double posX, double posY, double posZ, float f, int i )
public void render( TileMonitor tileEntity, double posX, double posY, double posZ, float f, int i, float f2 )
{
if( tileEntity != null )
{
@@ -46,25 +44,24 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
private void renderMonitorAt( TileMonitor monitor, double posX, double posY, double posZ, float f, int i )
{
// Render from the origin monitor
TileMonitor origin = monitor.getOrigin();
if( origin == null )
{
return;
}
ClientMonitor originTerminal = monitor.getClientMonitor();
// Ensure each monitor is rendered only once
long renderFrame = ComputerCraft.getRenderFrame();
if( origin.m_lastRenderFrame == renderFrame )
{
return;
}
else
{
origin.m_lastRenderFrame = renderFrame;
}
boolean redraw = origin.pollChanged();
if( originTerminal == null ) return;
TileMonitor origin = originTerminal.getOrigin();
BlockPos monitorPos = monitor.getPos();
// Ensure each monitor terminal is rendered only once. We allow rendering a specific tile
// multiple times in a single frame to ensure compatibility with shaders which may run a
// pass multiple times.
long renderFrame = ComputerCraft.getRenderFrame();
if( originTerminal.lastRenderFrame == renderFrame && !monitorPos.equals( originTerminal.lastRenderPos ) )
{
return;
}
originTerminal.lastRenderFrame = renderFrame;
originTerminal.lastRenderPos = monitorPos;
BlockPos originPos = origin.getPos();
posX += originPos.getX() - monitorPos.getX();
posY += originPos.getY() - monitorPos.getY();
@@ -85,49 +82,52 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
GlStateManager.rotate( pitch, 1.0f, 0.0f, 0.0f );
GlStateManager.translate(
-0.5 + TileMonitor.RENDER_BORDER + TileMonitor.RENDER_MARGIN,
((double)origin.getHeight() - 0.5) - (TileMonitor.RENDER_BORDER + TileMonitor.RENDER_MARGIN),
(origin.getHeight() - 0.5) - (TileMonitor.RENDER_BORDER + TileMonitor.RENDER_MARGIN),
0.5
);
double xSize = (double)origin.getWidth() - 2.0 * ( TileMonitor.RENDER_MARGIN + TileMonitor.RENDER_BORDER );
double ySize = (double)origin.getHeight() - 2.0 * ( TileMonitor.RENDER_MARGIN + TileMonitor.RENDER_BORDER );
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();
Tessellator tessellator = Tessellator.getInstance();
VertexBuffer renderer = tessellator.getBuffer();
BufferBuilder renderer = tessellator.getBuffer();
// Get terminal
ClientTerminal clientTerminal = (ClientTerminal)origin.getTerminal();
Terminal terminal = (clientTerminal != null) ? clientTerminal.getTerminal() : null;
redraw = redraw || (clientTerminal != null && clientTerminal.hasTerminalChanged());
boolean redraw = originTerminal.pollTerminalChanged();
// Draw the contents
GlStateManager.depthMask( false );
OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, 0xFF, 0xFF );
GlStateManager.disableLighting();
mc.entityRenderer.disableLightmap();
try
{
Terminal terminal = originTerminal.getTerminal();
if( terminal != null )
{
Palette palette = terminal.getPalette();
// Allocate display lists
if( origin.m_renderDisplayList < 0 )
if( originTerminal.renderDisplayLists == null )
{
origin.m_renderDisplayList = GL11.glGenLists( 3 );
originTerminal.createLists();
redraw = true;
}
// Draw a terminal
boolean greyscale = !clientTerminal.isColour();
boolean greyscale = !originTerminal.isColour();
int width = terminal.getWidth();
int height = terminal.getHeight();
int cursorX = terminal.getCursorX();
int cursorY = terminal.getCursorY();
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer)ComputerCraft.getFixedWidthFontRenderer();
FixedWidthFontRenderer fontRenderer = (FixedWidthFontRenderer) ComputerCraft.getFixedWidthFontRenderer();
GlStateManager.pushMatrix();
try
{
double xScale = xSize / (double) ( width * FixedWidthFontRenderer.FONT_WIDTH );
double yScale = ySize / (double) ( 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
@@ -135,26 +135,26 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
if( redraw )
{
// Build background display list
GL11.glNewList( origin.m_renderDisplayList, GL11.GL_COMPILE );
GlStateManager.glNewList( originTerminal.renderDisplayLists[0], GL11.GL_COMPILE );
try
{
double marginXSize = TileMonitor.RENDER_MARGIN / xScale;
double marginYSize = TileMonitor.RENDER_MARGIN / yScale;
double marginSquash = marginYSize / (double) FixedWidthFontRenderer.FONT_HEIGHT;
double marginSquash = marginYSize / FixedWidthFontRenderer.FONT_HEIGHT;
// Top and bottom margins
GL11.glPushMatrix();
GlStateManager.pushMatrix();
try
{
GL11.glScaled( 1.0, marginSquash, 1.0 );
GL11.glTranslated( 0.0, -marginYSize / marginSquash, 0.0 );
fontRenderer.drawStringBackgroundPart( 0, 0, terminal.getBackgroundColourLine( 0 ), marginXSize, marginXSize, greyscale );
GL11.glTranslated( 0.0, ( marginYSize + height * FixedWidthFontRenderer.FONT_HEIGHT ) / marginSquash, 0.0 );
fontRenderer.drawStringBackgroundPart( 0, 0, terminal.getBackgroundColourLine( height - 1 ), marginXSize, marginXSize, greyscale );
GlStateManager.scale( 1.0, marginSquash, 1.0 );
GlStateManager.translate( 0.0, -marginYSize / marginSquash, 0.0 );
fontRenderer.drawStringBackgroundPart( 0, 0, terminal.getBackgroundColourLine( 0 ), marginXSize, marginXSize, greyscale, palette );
GlStateManager.translate( 0.0, (marginYSize + height * FixedWidthFontRenderer.FONT_HEIGHT) / marginSquash, 0.0 );
fontRenderer.drawStringBackgroundPart( 0, 0, terminal.getBackgroundColourLine( height - 1 ), marginXSize, marginXSize, greyscale, palette );
}
finally
{
GL11.glPopMatrix();
GlStateManager.popMatrix();
}
// Backgrounds
@@ -164,23 +164,25 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
0, FixedWidthFontRenderer.FONT_HEIGHT * y,
terminal.getBackgroundColourLine( y ),
marginXSize, marginXSize,
greyscale
greyscale,
palette
);
}
}
finally
{
GL11.glEndList();
GlStateManager.glEndList();
}
}
GlStateManager.callList( origin.m_renderDisplayList );
GlStateManager.callList( originTerminal.renderDisplayLists[0] );
GlStateManager.resetColor();
// Draw text
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.font );
fontRenderer.bindFont();
if( redraw )
{
// Build text display list
GL11.glNewList( origin.m_renderDisplayList + 1, GL11.GL_COMPILE );
GlStateManager.glNewList( originTerminal.renderDisplayLists[1], GL11.GL_COMPILE );
try
{
// Lines
@@ -190,23 +192,25 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
0, FixedWidthFontRenderer.FONT_HEIGHT * y,
terminal.getLine( y ),
terminal.getTextColourLine( y ),
greyscale
greyscale,
palette
);
}
}
finally
{
GL11.glEndList();
GlStateManager.glEndList();
}
}
GlStateManager.callList( origin.m_renderDisplayList + 1 );
GlStateManager.callList( originTerminal.renderDisplayLists[1] );
GlStateManager.resetColor();
// Draw cursor
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.font );
fontRenderer.bindFont();
if( redraw )
{
// Build cursor display list
GL11.glNewList( origin.m_renderDisplayList + 2, GL11.GL_COMPILE );
GlStateManager.glNewList( originTerminal.renderDisplayLists[2], GL11.GL_COMPILE );
try
{
// Cursor
@@ -220,18 +224,20 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
FixedWidthFontRenderer.FONT_HEIGHT * cursorY,
cursorColour, null,
0, 0,
greyscale
greyscale,
palette
);
}
}
finally
{
GL11.glEndList();
GlStateManager.glEndList();
}
}
if( ComputerCraft.getGlobalCursorBlink() )
{
GlStateManager.callList( origin.m_renderDisplayList + 2 );
GlStateManager.callList( originTerminal.renderDisplayLists[2] );
GlStateManager.resetColor();
}
}
finally
@@ -243,19 +249,24 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
{
// Draw a big black quad
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.background );
renderer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR );
Colour colour = Colour.Black;
renderer.pos( -TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 0.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( xSize + TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 1.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( xSize + TileMonitor.RENDER_MARGIN, TileMonitor.RENDER_MARGIN, 0.0D ).tex( 1.0, 0.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( -TileMonitor.RENDER_MARGIN, TileMonitor.RENDER_MARGIN, 0.0D ).tex( 0.0, 0.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( -TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 0.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
final Colour colour = Colour.Black;
final float r = colour.getR();
final float g = colour.getG();
final float b = colour.getB();
renderer.begin( GL11.GL_TRIANGLE_STRIP, DefaultVertexFormats.POSITION_TEX_COLOR );
renderer.pos( -TileMonitor.RENDER_MARGIN, TileMonitor.RENDER_MARGIN, 0.0D ).tex( 0.0, 0.0 ).color( r, g, b, 1.0f ).endVertex();
renderer.pos( -TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 0.0, 1.0 ).color( r, g, b, 1.0f ).endVertex();
renderer.pos( xSize + TileMonitor.RENDER_MARGIN, TileMonitor.RENDER_MARGIN, 0.0D ).tex( 1.0, 0.0 ).color( r, g, b, 1.0f ).endVertex();
renderer.pos( xSize + TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 1.0, 1.0 ).color( r, g, b, 1.0f ).endVertex();
tessellator.draw();
}
}
finally
{
GlStateManager.depthMask( true );
mc.entityRenderer.enableLightmap();
GlStateManager.enableLighting();
}
@@ -264,13 +275,11 @@ public class TileEntityMonitorRenderer extends TileEntitySpecialRenderer<TileMon
try
{
mc.getTextureManager().bindTexture( FixedWidthFontRenderer.background );
renderer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR );
Colour colour = Colour.Black;
renderer.pos( -TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 0.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( xSize + TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 1.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( xSize + TileMonitor.RENDER_MARGIN, TileMonitor.RENDER_MARGIN, 0.0D ).tex( 1.0, 0.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( -TileMonitor.RENDER_MARGIN, TileMonitor.RENDER_MARGIN, 0.0D ).tex( 0.0, 0.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
renderer.pos( -TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).tex( 0.0, 1.0 ).color( colour.getR(), colour.getG(), colour.getB(), 1.0f ).endVertex();
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();
renderer.pos( xSize + TileMonitor.RENDER_MARGIN, TileMonitor.RENDER_MARGIN, 0.0 ).endVertex();
renderer.pos( xSize + TileMonitor.RENDER_MARGIN, -ySize - TileMonitor.RENDER_MARGIN, 0.0 ).endVertex();
tessellator.draw();
}
finally

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -9,79 +9,46 @@ package dan200.computercraft.client.render;
import dan200.computercraft.api.turtle.ITurtleUpgrade;
import dan200.computercraft.api.turtle.TurtleSide;
import dan200.computercraft.shared.computer.core.ComputerFamily;
import dan200.computercraft.shared.computer.core.IComputer;
import dan200.computercraft.shared.turtle.blocks.TileTurtle;
import dan200.computercraft.shared.turtle.entity.TurtleVisionCamera;
import dan200.computercraft.shared.util.Colour;
import dan200.computercraft.shared.util.Holiday;
import dan200.computercraft.shared.util.HolidayUtil;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelManager;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.entity.Entity;
import net.minecraft.util.*;
import net.minecraft.util.math.*;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.model.pipeline.LightUtil;
import org.apache.commons.lang3.tuple.Pair;
import org.lwjgl.opengl.GL11;
import javax.vecmath.Matrix4f;
import java.util.Iterator;
import java.util.List;
public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurtle>
{
private static ModelResourceLocation NORMAL_TURTLE_MODEL = new ModelResourceLocation( "computercraft:CC-Turtle", "inventory" );
private static ModelResourceLocation ADVANCED_TURTLE_MODEL = new ModelResourceLocation( "computercraft:CC-TurtleAdvanced", "inventory" );
private static ModelResourceLocation[] COLOUR_TURTLE_MODELS = new ModelResourceLocation[] {
new ModelResourceLocation( "computercraft:turtle_black", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_red", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_green", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_brown", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_blue", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_purple", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_cyan", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_lightGrey", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_grey", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_pink", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_lime", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_yellow", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_lightBlue", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_magenta", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_orange", "inventory" ),
new ModelResourceLocation( "computercraft:turtle_white", "inventory" ),
};
private static ModelResourceLocation 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_MODELS = new ModelResourceLocation[] {
new ModelResourceLocation( "computercraftedu:turtleJunior_black", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_red", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_green", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_brown", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_blue", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_purple", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_cyan", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_lightGrey", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_grey", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_pink", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_lime", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_yellow", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_lightBlue", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_magenta", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_orange", "inventory" ),
new ModelResourceLocation( "computercraftedu:turtleJunior_white", "inventory" ),
};
private static ModelResourceLocation 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()
@@ -89,7 +56,7 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
}
@Override
public void renderTileEntityAt( TileTurtle tileEntity, double posX, double posY, double posZ, float f, int i )
public void render( TileTurtle tileEntity, double posX, double posY, double posZ, float f, int i, float f2 )
{
if( tileEntity != null )
{
@@ -97,7 +64,7 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
Entity viewEntity = Minecraft.getMinecraft().getRenderViewEntity();
if( viewEntity != null && viewEntity instanceof TurtleVisionCamera )
{
TurtleVisionCamera camera = (TurtleVisionCamera)viewEntity;
TurtleVisionCamera camera = (TurtleVisionCamera) viewEntity;
if( camera.getTurtle() == tileEntity.getAccess() )
{
return;
@@ -109,44 +76,17 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
}
}
public static ModelResourceLocation getTurtleModel( ComputerFamily family, Colour colour )
public static ModelResourceLocation getTurtleModel( ComputerFamily family, boolean coloured )
{
switch( family )
{
case Normal:
default:
{
if( colour != null )
{
return COLOUR_TURTLE_MODELS[ colour.ordinal() ];
}
else
{
return NORMAL_TURTLE_MODEL;
}
}
return coloured ? COLOUR_TURTLE_MODEL : NORMAL_TURTLE_MODEL;
case Advanced:
{
if( colour != null )
{
return COLOUR_TURTLE_MODELS[ colour.ordinal() ];
}
else
{
return ADVANCED_TURTLE_MODEL;
}
}
return coloured ? COLOUR_TURTLE_MODEL : ADVANCED_TURTLE_MODEL;
case Beginners:
{
if( colour != null )
{
return BEGINNER_TURTLE_COLOUR_MODELS[ colour.ordinal() ];
}
else
{
return BEGINNER_TURTLE_MODEL;
}
}
return coloured ? BEGINNER_TURTLE_COLOUR_MODEL : BEGINNER_TURTLE_MODEL;
}
}
@@ -175,48 +115,36 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
// Setup the transform
Vec3d offset;
float yaw;
if( turtle != null )
{
offset = turtle.getRenderOffset( f );
yaw = turtle.getRenderYaw( f );
}
else
{
offset = new Vec3d( 0.0, 0.0, 0.0 );
yaw = 0.0f;
}
GlStateManager.translate( posX + offset.xCoord, posY + offset.yCoord, posZ + offset.zCoord );
offset = turtle.getRenderOffset( f );
yaw = turtle.getRenderYaw( f );
GlStateManager.translate( posX + offset.x, posY + offset.y, posZ + offset.z );
// Render the label
IComputer computer = (turtle != null) ? turtle.getComputer() : null;
String label = (computer != null) ? computer.getLabel() : null;
String label = turtle.createProxy().getLabel();
if( label != null )
{
renderLabel( turtle.getAccess().getPosition(), label );
}
// Render the turtle
GlStateManager.translate( 0.5f, 0.0f, 0.5f );
GlStateManager.translate( 0.5f, 0.5f, 0.5f );
GlStateManager.rotate( 180.0f - yaw, 0.0f, 1.0f, 0.0f );
GlStateManager.translate( -0.5f, 0.0f, -0.5f );
if( label != null && (label.equals( "Dinnerbone" ) || label.equals( "Grumm" )) )
{
// Flip the model and swap the cull face as winding order will have changed.
GlStateManager.scale( 1.0f, -1.0f, 1.0f );
GlStateManager.cullFace( GlStateManager.CullFace.FRONT );
}
GlStateManager.translate( -0.5f, -0.5f, -0.5f );
// Render the turtle
Colour colour;
int colour;
ComputerFamily family;
ResourceLocation overlay;
if( turtle != null )
{
colour = turtle.getColour();
family = turtle.getFamily();
overlay = turtle.getOverlay();
}
else
{
colour = null;
family = ComputerFamily.Normal;
overlay = null;
}
renderModel( state, getTurtleModel( family, colour ) );
colour = turtle.getColour();
family = turtle.getFamily();
overlay = turtle.getOverlay();
renderModel( state, getTurtleModel( family, colour != -1 ), colour == -1 ? null : new int[] { colour } );
// Render the overlay
ModelResourceLocation overlayModel = getTurtleOverlayModel(
@@ -231,7 +159,7 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
GlStateManager.blendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA );
try
{
renderModel( state, overlayModel );
renderModel( state, overlayModel, null );
}
finally
{
@@ -241,15 +169,13 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
}
// Render the upgrades
if( turtle != null )
{
renderUpgrade( state, turtle, TurtleSide.Left, f );
renderUpgrade( state, turtle, TurtleSide.Right, f );
}
renderUpgrade( state, turtle, TurtleSide.Left, f );
renderUpgrade( state, turtle, TurtleSide.Right, f );
}
finally
{
GlStateManager.popMatrix();
GlStateManager.cullFace( GlStateManager.CullFace.BACK );
}
}
@@ -275,7 +201,7 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
}
if( pair.getLeft() != null )
{
renderModel( state, pair.getLeft() );
renderModel( state, pair.getLeft(), null );
}
}
}
@@ -286,35 +212,32 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
}
}
private void renderModel( IBlockState state, ModelResourceLocation modelLocation )
private void renderModel( IBlockState state, ModelResourceLocation modelLocation, int[] tints )
{
Minecraft mc = Minecraft.getMinecraft();
ModelManager modelManager = mc.getRenderItem().getItemModelMesher().getModelManager();
renderModel( state, modelManager.getModel( modelLocation ) );
renderModel( state, modelManager.getModel( modelLocation ), tints );
}
private void renderModel( IBlockState state, IBakedModel model )
private void renderModel( IBlockState state, IBakedModel model, int[] tints )
{
Minecraft mc = Minecraft.getMinecraft();
Tessellator tessellator = Tessellator.getInstance();
mc.getTextureManager().bindTexture( TextureMap.LOCATION_BLOCKS_TEXTURE );
renderQuads( tessellator, model.getQuads( state, null, 0 ) );
renderQuads( tessellator, model.getQuads( state, null, 0 ), tints );
for( EnumFacing facing : EnumFacing.VALUES )
{
renderQuads( tessellator, model.getQuads( state, facing, 0 ) );
renderQuads( tessellator, model.getQuads( state, facing, 0 ), tints );
}
}
private void renderQuads( Tessellator tessellator, List quads )
private void renderQuads( Tessellator tessellator, List<BakedQuad> quads, int[] tints )
{
int color = 0xFFFFFFFF;
Iterator it = quads.iterator();
VertexBuffer buffer = tessellator.getBuffer();
BufferBuilder buffer = tessellator.getBuffer();
VertexFormat format = DefaultVertexFormats.ITEM;
buffer.begin( GL11.GL_QUADS, format );
while( it.hasNext() )
for (BakedQuad quad : quads)
{
BakedQuad quad = (BakedQuad)it.next();
VertexFormat quadFormat = quad.getFormat();
if( quadFormat != format )
{
@@ -322,7 +245,15 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
format = quadFormat;
buffer.begin( GL11.GL_QUADS, format );
}
net.minecraftforge.client.model.pipeline.LightUtil.renderQuadColor( buffer, quad, color );
int colour = 0xFFFFFFFF;
if( quad.hasTintIndex() && tints != null )
{
int index = quad.getTintIndex();
if( index >= 0 && index < tints.length ) colour = tints[ index ] | 0xFF000000;
}
LightUtil.renderQuadColor( buffer, quad, colour );
}
tessellator.draw();
}
@@ -361,12 +292,12 @@ public class TileEntityTurtleRenderer extends TileEntitySpecialRenderer<TileTurt
try
{
Tessellator tessellator = Tessellator.getInstance();
VertexBuffer renderer = tessellator.getBuffer();
BufferBuilder renderer = tessellator.getBuffer();
renderer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR );
renderer.pos( (double) ( -xOffset - 1 ), (double) ( -1 + yOffset ), 0.0D ).color( 0.0F, 0.0F, 0.0F, 0.25F ).endVertex();
renderer.pos( (double) ( -xOffset - 1 ), (double) ( 8 + yOffset ), 0.0D ).color( 0.0F, 0.0F, 0.0F, 0.25F ).endVertex();
renderer.pos( (double) ( xOffset + 1 ), (double) ( 8 + yOffset ), 0.0D ).color( 0.0F, 0.0F, 0.0F, 0.25F ).endVertex();
renderer.pos( (double) ( xOffset + 1 ), (double) ( -1 + yOffset ), 0.0D ).color( 0.0F, 0.0F, 0.0F, 0.25F ).endVertex();
renderer.pos( -xOffset - 1, -1 + yOffset, 0.0D ).color( 0.0F, 0.0F, 0.0F, 0.25F ).endVertex();
renderer.pos( -xOffset - 1, 8 + yOffset, 0.0D ).color( 0.0F, 0.0F, 0.0F, 0.25F ).endVertex();
renderer.pos( xOffset + 1, 8 + yOffset, 0.0D ).color( 0.0F, 0.0F, 0.0F, 0.25F ).endVertex();
renderer.pos( xOffset + 1, -1 + yOffset, 0.0D ).color( 0.0F, 0.0F, 0.0F, 0.25F ).endVertex();
tessellator.draw();
}
finally

View File

@@ -1,35 +1,33 @@
package dan200.computercraft.client.render;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.*;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.block.model.ItemOverrideList;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.renderer.vertex.VertexFormatElement;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.vecmath.Matrix4f;
import javax.vecmath.Point3f;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TurtleMultiModel implements IBakedModel
{
private IBakedModel m_baseModel;
private IBakedModel m_overlayModel;
private IBakedModel m_leftUpgradeModel;
private Matrix4f m_leftUpgradeTransform;
private IBakedModel m_rightUpgradeModel;
private Matrix4f m_rightUpgradeTransform;
private final IBakedModel m_baseModel;
private final IBakedModel m_overlayModel;
private final Matrix4f m_generalTransform;
private final IBakedModel m_leftUpgradeModel;
private final Matrix4f m_leftUpgradeTransform;
private final IBakedModel m_rightUpgradeModel;
private final Matrix4f m_rightUpgradeTransform;
private List<BakedQuad> m_generalQuads;
private List<BakedQuad> m_faceQuads[];
private Map<EnumFacing, List<BakedQuad>> m_faceQuads;
public TurtleMultiModel( IBakedModel baseModel, IBakedModel overlayModel, IBakedModel leftUpgradeModel, Matrix4f leftUpgradeTransform, IBakedModel rightUpgradeModel, Matrix4f rightUpgradeTransform )
public TurtleMultiModel( IBakedModel baseModel, IBakedModel overlayModel, Matrix4f generalTransform, IBakedModel leftUpgradeModel, Matrix4f leftUpgradeTransform, IBakedModel rightUpgradeModel, Matrix4f rightUpgradeTransform )
{
// Get the models
m_baseModel = baseModel;
@@ -38,57 +36,63 @@ public class TurtleMultiModel implements IBakedModel
m_leftUpgradeTransform = leftUpgradeTransform;
m_rightUpgradeModel = rightUpgradeModel;
m_rightUpgradeTransform = rightUpgradeTransform;
m_generalTransform = generalTransform;
m_generalQuads = null;
m_faceQuads = new List[6];
m_faceQuads = new HashMap<>();
}
@Nonnull
@Override
public List<BakedQuad> getQuads( IBlockState state, EnumFacing side, long rand )
{
if( side != null )
{
if( m_faceQuads[ side.ordinal() ] == null )
{
List<BakedQuad> quads = new ArrayList<BakedQuad>();
if( m_overlayModel != null )
{
quads.addAll( m_overlayModel.getQuads( state, side, rand ) );
}
if( m_leftUpgradeModel != null )
{
quads.addAll( transformQuads( m_leftUpgradeModel.getQuads( state, side, rand ), m_leftUpgradeTransform ) );
}
if( m_rightUpgradeModel != null )
{
quads.addAll( transformQuads( m_rightUpgradeModel.getQuads( state, side, rand ), m_rightUpgradeTransform ) );
}
m_faceQuads[ side.ordinal() ] = quads;
}
return m_faceQuads[ side.ordinal() ];
if( !m_faceQuads.containsKey( side ) ) m_faceQuads.put( side, buildQuads( state, side, rand ) );
return m_faceQuads.get( side );
}
else
{
if( m_generalQuads == null )
{
m_generalQuads = new ArrayList<BakedQuad>();
m_generalQuads.addAll( m_baseModel.getQuads( state, side, rand ) );
if( m_overlayModel != null )
{
m_generalQuads.addAll( m_overlayModel.getQuads( state, side, rand ) );
}
if( m_leftUpgradeModel != null )
{
m_generalQuads.addAll( transformQuads( m_leftUpgradeModel.getQuads( state, side, rand ), m_leftUpgradeTransform ) );
}
if( m_rightUpgradeModel != null )
{
m_generalQuads.addAll( transformQuads( m_rightUpgradeModel.getQuads( state, side, rand ), m_rightUpgradeTransform ) );
}
}
if( m_generalQuads == null ) m_generalQuads = buildQuads( state, side, rand );
return m_generalQuads;
}
}
private List<BakedQuad> buildQuads( IBlockState state, EnumFacing side, long rand )
{
ArrayList<BakedQuad> quads = new ArrayList<>();
ModelTransformer.transformQuadsTo( quads, m_baseModel.getQuads( state, side, rand ), m_generalTransform );
if( m_overlayModel != null )
{
ModelTransformer.transformQuadsTo( quads, m_overlayModel.getQuads( state, side, rand ), m_generalTransform );
}
if( m_overlayModel != null )
{
ModelTransformer.transformQuadsTo( quads, m_overlayModel.getQuads( state, side, rand ), m_generalTransform );
}
if( m_leftUpgradeModel != null )
{
Matrix4f upgradeTransform = m_generalTransform;
if( m_leftUpgradeTransform != null )
{
upgradeTransform = new Matrix4f( m_generalTransform );
upgradeTransform.mul( m_leftUpgradeTransform );
}
ModelTransformer.transformQuadsTo( quads, m_leftUpgradeModel.getQuads( state, side, rand ), upgradeTransform );
}
if( m_rightUpgradeModel != null )
{
Matrix4f upgradeTransform = m_generalTransform;
if( m_rightUpgradeTransform != null )
{
upgradeTransform = new Matrix4f( m_generalTransform );
upgradeTransform.mul( m_rightUpgradeTransform );
}
ModelTransformer.transformQuadsTo( quads, m_rightUpgradeModel.getQuads( state, side, rand ), upgradeTransform );
}
quads.trimToSize();
return quads;
}
@Override
public boolean isAmbientOcclusion()
{
@@ -107,81 +111,25 @@ public class TurtleMultiModel implements IBakedModel
return m_baseModel.isBuiltInRenderer();
}
@Nonnull
@Override
public TextureAtlasSprite getParticleTexture()
{
return m_baseModel.getParticleTexture();
}
@Nonnull
@Override
@Deprecated
public ItemCameraTransforms getItemCameraTransforms()
{
return m_baseModel.getItemCameraTransforms();
}
@Nonnull
@Override
public ItemOverrideList getOverrides()
{
return ItemOverrideList.NONE;
}
private List<BakedQuad> transformQuads( List<BakedQuad> input, Matrix4f transform )
{
if( transform == null || input.size() == 0 )
{
return input;
}
else
{
List<BakedQuad> output = new ArrayList<BakedQuad>( input.size() );
for( int i=0; i<input.size(); ++i )
{
BakedQuad quad = input.get( i );
output.add( transformQuad( quad, transform ) );
}
return output;
}
}
private BakedQuad transformQuad( BakedQuad quad, Matrix4f transform )
{
int[] vertexData = quad.getVertexData().clone();
int offset = 0;
BakedQuad copy = new BakedQuad( vertexData, quad.getTintIndex(), quad.getFace(), quad.getSprite(), quad.shouldApplyDiffuseLighting(), quad.getFormat() );
VertexFormat format = copy.getFormat();
for( int i=0; i<format.getElementCount(); ++i ) // For each vertex element
{
VertexFormatElement element = format.getElement( i );
if( element.isPositionElement() &&
element.getType() == VertexFormatElement.EnumType.FLOAT &&
element.getElementCount() == 3 ) // When we find a position element
{
for( int j=0; j<4; ++j ) // For each corner of the quad
{
int start = offset + j * format.getNextOffset();
if( (start % 4) == 0 )
{
start = start / 4;
// Extract the position
Point3f pos = new Point3f(
Float.intBitsToFloat( vertexData[ start ] ),
Float.intBitsToFloat( vertexData[ start + 1 ] ),
Float.intBitsToFloat( vertexData[ start + 2 ] )
);
// Transform the position
transform.transform( pos );
// Insert the position
vertexData[ start ] = Float.floatToRawIntBits( pos.x );
vertexData[ start + 1 ] = Float.floatToRawIntBits( pos.y );
vertexData[ start + 2 ] = Float.floatToRawIntBits( pos.z );
}
}
}
offset += element.getSize();
}
return copy;
}
}

View File

@@ -1,6 +1,6 @@
/**
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2016. Do not distribute without permission.
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
@@ -11,8 +11,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.items.ItemTurtleBase;
import dan200.computercraft.shared.turtle.items.TurtleItemFactory;
import dan200.computercraft.shared.util.Colour;
import dan200.computercraft.shared.util.Holiday;
import dan200.computercraft.shared.util.HolidayUtil;
import net.minecraft.block.state.IBlockState;
@@ -26,10 +24,10 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ISmartVariant;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.vecmath.Matrix4f;
import java.util.ArrayList;
import java.util.HashMap;
@@ -37,16 +35,30 @@ import java.util.List;
public class TurtleSmartItemModel implements IBakedModel, IResourceManagerReloadListener
{
private static final Matrix4f s_identity, s_flip;
static
{
s_identity = new Matrix4f();
s_identity.setIdentity();
s_flip = new Matrix4f();
s_flip.setIdentity();
s_flip.m11 = -1; // Flip on the y axis
s_flip.m13 = 1; // Models go from (0,0,0) to (1,1,1), so push back up.
}
private static class TurtleModelCombination
{
public final ComputerFamily m_family;
public final Colour m_colour;
public final boolean m_colour;
public final ITurtleUpgrade m_leftUpgrade;
public final ITurtleUpgrade m_rightUpgrade;
public final ResourceLocation m_overlay;
public final boolean m_christmas;
public final boolean m_flip;
public TurtleModelCombination( ComputerFamily family, Colour colour, ITurtleUpgrade leftUpgrade, ITurtleUpgrade rightUpgrade, ResourceLocation overlay, boolean christmas )
public TurtleModelCombination( ComputerFamily family, boolean colour, ITurtleUpgrade leftUpgrade, ITurtleUpgrade rightUpgrade, ResourceLocation overlay, boolean christmas, boolean flip )
{
m_family = family;
m_colour = colour;
@@ -54,22 +66,26 @@ public class TurtleSmartItemModel implements IBakedModel, IResourceManagerReload
m_rightUpgrade = rightUpgrade;
m_overlay = overlay;
m_christmas = christmas;
m_flip = flip;
}
@Override
public boolean equals( Object other )
{
if( other == this ) {
if( other == this )
{
return true;
}
if( other instanceof TurtleModelCombination ) {
TurtleModelCombination otherCombo = (TurtleModelCombination)other;
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_christmas == m_christmas &&
otherCombo.m_flip == m_flip )
{
return true;
}
@@ -83,36 +99,40 @@ public class TurtleSmartItemModel implements IBakedModel, IResourceManagerReload
final int prime = 31;
int result = 1;
result = prime * result + m_family.hashCode();
result = prime * result + (m_colour != null ? m_colour.hashCode() : 0);
result = prime * result + (m_colour ? 1 : 0);
result = prime * result + (m_leftUpgrade != null ? m_leftUpgrade.hashCode() : 0);
result = prime * result + (m_rightUpgrade != null ? m_rightUpgrade.hashCode() : 0);
result = prime * result + (m_overlay != null ? m_overlay.hashCode() : 0);
result = prime * result + (m_christmas ? 1 : 0);
result = prime * result + (m_flip ? 1 : 0);
return result;
}
}
private ItemStack m_defaultItem;
private HashMap<TurtleModelCombination, IBakedModel> m_cachedModels;
private ItemOverrideList m_overrides;
private final TurtleModelCombination m_defaultCombination;
public TurtleSmartItemModel()
{
m_defaultItem = TurtleItemFactory.create( -1, null, null, ComputerFamily.Normal, null, null, 0, null );
m_cachedModels = new HashMap<TurtleModelCombination, IBakedModel>();
m_overrides = new ItemOverrideList( new ArrayList<ItemOverride>() )
m_cachedModels = new HashMap<>();
m_defaultCombination = new TurtleModelCombination( ComputerFamily.Normal, false, null, null, null, false, false );
m_overrides = new ItemOverrideList( new ArrayList<>() )
{
@Nonnull
@Override
public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity)
public IBakedModel handleItemState( @Nonnull IBakedModel originalModel, @Nonnull ItemStack stack, @Nullable World world, @Nullable EntityLivingBase entity )
{
ItemTurtleBase turtle = (ItemTurtleBase) stack.getItem();
ComputerFamily family = turtle.getFamily( stack );
Colour colour = turtle.getColour( stack );
int colour = turtle.getColour( stack );
ITurtleUpgrade leftUpgrade = turtle.getUpgrade( stack, TurtleSide.Left );
ITurtleUpgrade rightUpgrade = turtle.getUpgrade( stack, TurtleSide.Right );
ResourceLocation overlay = turtle.getOverlay( stack );
boolean christmas = HolidayUtil.getCurrentHoliday() == Holiday.Christmas;
TurtleModelCombination combo = new TurtleModelCombination( family, colour, leftUpgrade, rightUpgrade, overlay, christmas );
String label = turtle.getLabel( stack );
boolean flip = label != null && (label.equals( "Dinnerbone" ) || label.equals( "Grumm" ));
TurtleModelCombination combo = new TurtleModelCombination( family, colour != -1, leftUpgrade, rightUpgrade, overlay, christmas, flip );
if( m_cachedModels.containsKey( combo ) )
{
return m_cachedModels.get( combo );
@@ -127,6 +147,7 @@ public class TurtleSmartItemModel implements IBakedModel, IResourceManagerReload
};
}
@Nonnull
@Override
public ItemOverrideList getOverrides()
{
@@ -134,7 +155,7 @@ public class TurtleSmartItemModel implements IBakedModel, IResourceManagerReload
}
@Override
public void onResourceManagerReload( IResourceManager resourceManager )
public void onResourceManagerReload( @Nonnull IResourceManager resourceManager )
{
m_cachedModels.clear();
}
@@ -146,33 +167,31 @@ public class TurtleSmartItemModel implements IBakedModel, IResourceManagerReload
ModelResourceLocation baseModelLocation = TileEntityTurtleRenderer.getTurtleModel( combo.m_family, combo.m_colour );
ModelResourceLocation overlayModelLocation = TileEntityTurtleRenderer.getTurtleOverlayModel( combo.m_family, combo.m_overlay, combo.m_christmas );
IBakedModel baseModel = modelManager.getModel( baseModelLocation );
IBakedModel overlayModel = (overlayModelLocation != null) ? modelManager.getModel( baseModelLocation ) : null;
IBakedModel overlayModel = (overlayModelLocation != null) ? modelManager.getModel( overlayModelLocation ) : null;
Matrix4f transform = combo.m_flip ? s_flip : s_identity;
Pair<IBakedModel, Matrix4f> leftModel = (combo.m_leftUpgrade != null) ? combo.m_leftUpgrade.getModel( null, TurtleSide.Left ) : null;
Pair<IBakedModel, Matrix4f> rightModel = (combo.m_rightUpgrade != null) ? combo.m_rightUpgrade.getModel( null, TurtleSide.Right ) : null;
if( leftModel != null && rightModel != null )
{
return new TurtleMultiModel( baseModel, overlayModel, leftModel.getLeft(), leftModel.getRight(), rightModel.getLeft(), rightModel.getRight() );
return new TurtleMultiModel( baseModel, overlayModel, transform, leftModel.getLeft(), leftModel.getRight(), rightModel.getLeft(), rightModel.getRight() );
}
else if( leftModel != null )
{
return new TurtleMultiModel( baseModel, overlayModel, leftModel.getLeft(), leftModel.getRight(), null, null );
return new TurtleMultiModel( baseModel, overlayModel, transform, leftModel.getLeft(), leftModel.getRight(), null, null );
}
else if( rightModel != null )
{
return new TurtleMultiModel( baseModel, overlayModel, null, null, rightModel.getLeft(), rightModel.getRight() );
}
else if( overlayModel != null )
{
return new TurtleMultiModel( baseModel, overlayModel, null, null, null, null );
return new TurtleMultiModel( baseModel, overlayModel, transform, null, null, rightModel.getLeft(), rightModel.getRight() );
}
else
{
return baseModel;
return new TurtleMultiModel( baseModel, overlayModel, transform, null, null, null, null );
}
}
// These should not be called:
@Nonnull
@Override
public List<BakedQuad> getQuads( IBlockState state, EnumFacing facing, long rand )
{
@@ -197,13 +216,16 @@ public class TurtleSmartItemModel implements IBakedModel, IResourceManagerReload
return getDefaultModel().isBuiltInRenderer();
}
@Nonnull
@Override
public TextureAtlasSprite getParticleTexture()
{
return getDefaultModel().getParticleTexture();
}
@Nonnull
@Override
@Deprecated
public ItemCameraTransforms getItemCameraTransforms()
{
return getDefaultModel().getItemCameraTransforms();
@@ -211,6 +233,13 @@ public class TurtleSmartItemModel implements IBakedModel, IResourceManagerReload
private IBakedModel getDefaultModel()
{
return m_overrides.handleItemState( this, m_defaultItem, null, null );
IBakedModel model = m_cachedModels.get( m_defaultCombination );
if( model == null )
{
model = buildModel( m_defaultCombination );
m_cachedModels.put( m_defaultCombination, model );
}
return model;
}
}

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