refactor: port redstone interaction unit to java

This commit is contained in:
Algent committed 2026-08-28 10:48:19 +03:00
1 parent 28c90189a6
commit 1cb2cc4cc6
13 files changed
+366 -335

No files matched your search

+25 -11
View File
@@ -24,8 +24,8 @@ No trustworthy tool will produce a maintainable Java port automatically. A decom
## Current status
The binary and source-level consumer audits, low-coupling Phase 3 queue, audit-derived immediate compatibility gate,
and focused pre-optimization profile are complete. Phase 4 can now begin with the measured `TileMultipart` traversal
path; see `JAVA_MIGRATION_PROFILE.md`.
focused profile, first traversal optimization, and complete redstone interaction helper unit are complete. Phase 4
continues with `MicroRecipe`'s non-local-return category; see `JAVA_MIGRATION_PROFILE.md`.
That audit found and this branch has now repaired one existing regression: Schematica 1.12.6 reflects the original private
`MultiPartRegistry$` field `codechicken$multipart$MultiPartRegistry$$typeMap` and casts it to a Scala mutable map. The
@@ -322,18 +322,18 @@ and the already-ported registry again supports Schematica.
### Phase 4 — Convert measured hot paths
- [ ] Characterize result ordering, callback timing, early exits, and edge cases before changing traversal code.
- [ ] Rewrite `TileMultipart.updateEntity()` as allocation-free indexed or array traversal.
- [x] Characterize result ordering, callback timing, early exits, and edge cases before changing traversal code.
- [x] Rewrite `TileMultipart` update/operate traversal without per-call collection allocation.
- [ ] Rewrite redstone queries without closure allocation or `IntRef` boxing.
- [ ] Replace non-local returns in slot/recipe scans with ordinary Java control flow.
- [ ] Use fastutil only where profiling and data shape justify it.
- [ ] Re-profile the same scenarios and record both improvements and regressions.
- [x] Re-profile the same scenarios and record both improvements and regressions.
Status: ready to start. The compatibility gate and initial profile are complete. First freeze `operate` behavior when
callbacks add or remove parts, then remove the measured per-traversal `ArrayList`/array/wrapper materialization while
retaining the public Scala `Seq` and `operate(Function1)` ABI. Re-run the focused profile immediately. The next broader
unit is the whole `IRedstonePart.scala` file: its six related traits and load-bearing `RedstoneInteractions$` must be
characterized and ported together.
Status: active. `operate` now preserves its captured-sequence mutation semantics without collection materialization,
and the six-interface `IRedstonePart`/`RedstoneInteractions$` unit is ported with its class list and descriptors intact.
The comparison proves its allocation is owned by `scalatraits/TRedstoneTile.scala`, so that part waits for Phase 5.
Next characterize and port `MicroRecipe.scala`, replacing its closure-backed scans and non-local returns with ordinary
Java loops.
Exit condition: identified steady-state Scala allocation sites are removed with compatible results.
@@ -402,7 +402,7 @@ The work should move from low to high risk while keeping a buildable mixed-langu
Extensive tests are both possible and recommended here. Their purpose is not to prove that the current Scala behavior is ideal; it is to make its observable behavior explicit before translation, so every later difference is intentional.
The repository now has a Java-8-compatible JUnit Jupiter suite and a small Forge integration runner. The current
baseline is 130 plain-JVM tests and 28 Forge server tests. Minecraft 1.7.10 does not provide the modern GameTest
baseline is 139 plain-JVM tests and 31 Forge server tests. Minecraft 1.7.10 does not provide the modern GameTest
framework, so game-dependent coverage continues through the existing narrow Forge harness rather than a second test
framework.
@@ -643,3 +643,17 @@ generated-trait compatibility work. Scala-runtime removal remains a later projec
allocates 80.5 bytes. CPU and allocation sites point to `TileMultipart.parts()` collection copies and Scala
redstone `IntRef`/closure traversal. Full methodology and rerun commands are in `JAVA_MIGRATION_PROFILE.md`.
- The expanded baseline is 130 plain-JVM tests and 28 Forge server tests, all passing.
### 2026-08-28
- Ported all six interfaces and `RedstoneInteractions` from `IRedstonePart.scala` as one unit. The emitted class list is
unchanged, every public descriptor is unchanged, and `RedstoneInteractions$.MODULE$` remains the implementation
singleton behind the static façade.
- Added six plain-JVM tests for interface shape, façade/companion members, maps, part-mask precedence, connector routing,
and neighbor coordinate transforms, plus three Forge tests for initialized vanilla blocks, world power routing, the
redstone-wire metadata fallback, and generated `IRedstoneTile` selection.
- Re-profiled immediately before and after the port. Allocation stayed at roughly 4.02 GB / 80.5 B per generated
three-query iteration, and JFR retained the same `TRedstoneTile` Scala closure/iterator sites. That cost belongs to
the Phase 5 generated-trait conversion, not this helper unit.
- Chose `MicroRecipe.scala` as the next independent Phase 4 unit because its nested collection scans compile early
exits into `NonLocalReturnControl`; characterize all five recipe paths and precedence before porting it.
+45
View File
@@ -1266,3 +1266,48 @@ failure rather than a silent one, but it will recur in every remaining renderer
- What stays manual, and it is everything this class actually does: static block rendering, dynamic part rendering,
the breaking overlay on the struck part, inventory rendering, and the render id being claimed exactly once. None of
it can run without a client, so all of it is on the checklist.
## 2026-08-28 — IRedstonePart and RedstoneInteractions Java port
The complete source unit: six abstract interfaces plus the routing singleton. ProjectRed, ProjectBlue, WR-CBE,
Extra Utilities, OpenComputers and AE2 consume this surface; ProjectRed also reads `RedstoneInteractions$.MODULE$`
directly, so the companion cannot be collapsed into a static utility class.
### Observable behavior
No known divergence. Plain, face, and custom-mask parts retain the same precedence and bit masks. Connector tiles
still win over connector blocks, which still win over vanilla handling. Neighbor lookups retain the same coordinate
offset and opposite-side transform. Full-connect blocks, wire/comparator visual masks, repeater orientation, the
redstone-wire metadata fallback, and `Block.canConnectRedstone` retain their existing branches. Java uses
`Objects.equals` where Scala used null-safe `==`.
`vanillaSideMap`, `sideVanillaMap`, and `fullVanillaBlocks` remain singleton-owned objects returned by identity from
both published classes. `fullVanillaBlocks` deliberately remains a `scala.collection.immutable.Set<Block>` so its
descriptor and existing Scala consumers do not change.
### Supported JVM API
The emitted class list is unchanged: the six interface classes, `RedstoneInteractions`, and
`RedstoneInteractions$`. Every public member and descriptor is unchanged. `RedstoneInteractions` remains the static
façade and `RedstoneInteractions$.MODULE$` remains the implementation instance. The Java façade necessarily has a
private constructor where Scala's static-forwarder class emitted none; no consumer references constructors on either
class.
The six Scala traits contained only abstract members, so they emitted no `$class` helpers and need no compatibility
bridges. Their Scala signatures disappear, but inheritance and JVM method descriptors are identical.
### Performance boundary
The fresh Scala baseline measured 80.4 B per generated redstone three-query iteration; the Java result measured
80.5 B. Post-port JFR still attributes the work to Scala `List.foreach`, `Iterator.foreach`, `PartMap.edgeBetween`, and
the generated strong-power closure in `scalatraits/TRedstoneTile.scala`. This port therefore claims no performance
gain. Removing that allocation requires the later `registerJavaTrait` conversion and is explicitly deferred.
### Validation
- `RedstoneInteractionsCharacterizationTest`: 6 tests, covering every interface shape and pure routing branch.
- Complete plain-JVM suite: 139 tests, 0 failures, 0 errors.
- Java 8 Forge dedicated-server suite: 31 tests, 0 failures, 0 errors; three tests cover initialized vanilla state,
actual world routing, and a generated redstone tile.
- Clean `spotlessApply checkstyleTest build`: passing.
- Class list and public members diffed against the pre-port build; no characterization assertion changed.
+16 -11
View File
@@ -12,7 +12,7 @@ what breaks, and what is left. The other documents hold the reasoning.
| `JAVA_MIGRATION_MANUAL_CHECKS.md` | What no automated test can cover, and must be checked by hand in a client |
| `JAVA_MIGRATION_PROFILE.md` | The focused baseline, first measured result, findings, and exact rerun command |
Branch: `algent/java`. Base: `master`. 64 commits including the first profiled optimization.
Branch: `algent/java`. Base: `master`. 66 commits including the redstone interaction unit.
## The one rule that matters
@@ -66,7 +66,7 @@ awk -F'"' '/<testsuite /{t+=$4;f+=$8;e+=$10} END{print "tests="t" failures="f" e
grep -o 'tests="[0-9]*" skipped="[0-9]*" failures="[0-9]*" errors="[0-9]*"' run/server/junit-out/TEST-*.xml
```
Current baseline: **130 plain-JVM tests, 28 Forge server tests, all passing at their last completed runs.**
Current baseline: **139 plain-JVM tests, 31 Forge server tests, all passing at their last completed runs.**
### ABI diff against the reference
@@ -188,14 +188,15 @@ All eight load-bearing `$class` helpers from the inventory, both registries, and
`IDWriter`, `PartialOcclusionTest`/`JPartialOcclusion`, `TCuboidPart`/`JCuboidPart`, the `TNormalOcclusion` unit,
`TFacePart`, the `TIconHitEffects` unit, `TItemMultiPart`/`JItemMultiPart`, `TEdgePart`, `Saw`, `MicroMaterialRegistry`,
`MultiPartRegistry`, `TileMultipart`, `TMultiPart`, `TickScheduler`, `BlockMultipart`.
`MultiPartRegistry`, `TileMultipart`, `TMultiPart`, `TickScheduler`, `BlockMultipart`, and the complete
`IRedstonePart`/`RedstoneInteractions` unit.
Plus the six marker interfaces: `TSlottedPart`, `IRandomDisplayTick`, `INeighborTileChange`, `TRandomUpdateTick`,
`ISidedHollowConnect`, `IMicroMaterialRender`, plus `MultipartHelper`, `TileCache`, `PacketScheduler` and the `ControlKeyModifer` pair.
Both `package.scala` objects are gone, removed rather than ported. `MultipartRenderer` is done.
72 Java files, 48 Scala files, ~6,376 Scala lines left (non-blank; that is the metric this figure has always used).
80 Java files, 47 Scala files, ~6,103 Scala lines left (non-blank; that is the metric this figure has always used).
## What is left, and in what order
@@ -226,15 +227,17 @@ parts, and its normal immutable-`List` path now traverses the captured list dire
`operate`, with roughly 4.3x higher throughput. Full results and rerun commands are in
`JAVA_MIGRATION_PROFILE.md`.
Next characterize and port the complete `IRedstonePart.scala` unit. Re-baseline that phase immediately before the
implementation comparison, then remove its measured Scala iteration, `IntRef`, and generated-closure costs without
splitting `RedstoneInteractions$`.
The complete `IRedstonePart.scala` unit is now Java. All six interfaces retain their exact inheritance and descriptors;
`RedstoneInteractions` retains every static forwarder, while `RedstoneInteractions$.MODULE$` remains the load-bearing
implementation singleton. Pure masks, vanilla special cases, routing precedence, real-world power, and generated
redstone-tile selection are characterized. The comparison correctly found no allocation reduction: the measured
closures and `IntRef` boxes belong to `scalatraits/TRedstoneTile.scala`, which requires the Phase 5 Java-trait path.
`IRedstonePart.scala` is misleadingly named and is **not** a marker-trait file. It holds six traits plus
`RedstoneInteractions`, whose `MODULE$` is load-bearing. After the compatibility gate and an initial profile, port the
whole file as one medium-risk unit; do not split its mutually dependent behavior into smaller commits.
Next characterize and port `MicroRecipe.scala`. It is an independent medium-risk unit and contains the recipe/slot
scan non-local returns still open in Phase 4; freeze all five recipe forms and their precedence before replacing them
with ordinary Java loops.
**Medium.** The `handler` packages on both sides, `MultipartRenderer`, `MicroRecipe`, `ItemMicroPart`,
**Medium.** The `handler` packages on both sides, `MicroRecipe`, `ItemMicroPart`,
`MicroblockPlacement`, `PlacementGrids`, `BlockMicroMaterial`, `MissingMicroMaterial`, `ConfigContent`,
`DefaultContent`.
@@ -259,5 +262,7 @@ all of `multipart/asm/`. The ASM subsystem should be last; freeze generated-clas
- `TileMultipart`'s `partList` still republishes an immutable Scala `Seq` on every mutation. `operate` no longer calls
the Java port's copying `parts()` helper, but less frequent read and mutation paths still do. Optimize those only if
a representative profile identifies them; their mutable snapshots are intentional at mutation sites.
- The focused redstone allocation remains 80.5 B per three-query iteration. It is generated by
`scalatraits/TRedstoneTile.scala`, not `RedstoneInteractions`; remove it only with the Phase 5 Java-trait pilot.
- Phase 1 never properly started. GTNHLib is currently commented out in `dependencies.gradle`; it had been added at
`api` scope to satisfy a test compile rather than because a migration change needed it.
+19 -3
View File
@@ -1,4 +1,4 @@
# Java migration — focused performance baseline and first result
# Java migration — focused performance baseline and results
This is the reproducible pre-optimization baseline for Phase 4. It runs inside the real deobfuscated Forge dedicated
server, using the same generated tiles as the functional suite. It is intentionally focused rather than a claim about
@@ -102,5 +102,21 @@ but its code did not change and it now starts several seconds earlier because th
not attribute that timing difference to this traversal change. Re-baseline the redstone unit immediately before its
own implementation comparison.
Next characterize and port the complete `IRedstonePart.scala` unit and eliminate the measured redstone
`IntRef`/closure paths without splitting its load-bearing `RedstoneInteractions$` singleton.
## Redstone helper-unit comparison captured 2026-08-28
Immediately before converting `IRedstonePart.scala`, the same workload measured `redstoneQueries` at 7.603 s,
6,575,956 iterations/s, 4,022,151,064 allocated bytes, and 80.4 B/iteration. After its six interfaces and
`RedstoneInteractions` were converted together, the retained report measured 3.880 s, 12,884,996 iterations/s,
4,023,003,032 allocated bytes, and 80.5 B/iteration. Both runs produced checksum `3315999992`.
The allocation result is unchanged. The elapsed-time difference is not treated as a port win: earlier unchanged
Scala runs ranged from 3.689 to 7.603 s on this machine. More importantly, the post-port JFR has the same dominant
sites: Scala `List.foreach`, `Iterator.foreach`, `PartMap.edgeBetween`, and
`TRedstoneTile$$anonfun$strongPowerLevel$1`.
That evidence corrects the earlier plan. `IRedstonePart.scala` owned the public interfaces and routing helpers, but the
measured `IntRef`, iterator, and closure allocations are emitted by `scalatraits/TRedstoneTile.scala`. Removing them
requires the Phase 5 `registerJavaTrait` path and must not be smuggled into this otherwise descriptor-identical port.
The next independent Phase 4 unit is `MicroRecipe.scala`: characterize every recipe shape and precedence rule, then
replace its closure-backed scans and non-local returns with ordinary Java loops.
@@ -0,0 +1,7 @@
package codechicken.multipart;
/** A face-attached redstone part whose connections reduce to the edge between two faces. */
public interface IFaceRedstonePart extends IRedstonePart {
int getFace();
}
@@ -0,0 +1,7 @@
package codechicken.multipart;
/** A redstone part that supplies its own side connection masks. */
public interface IMaskedRedstonePart extends IRedstonePart {
int getConnectionMask(int side);
}
@@ -0,0 +1,9 @@
package codechicken.multipart;
/** A tile whose redstone connections are split into an edge-and-center mask for each side. */
public interface IRedstoneConnector {
int getConnectionMask(int side);
int weakPowerLevel(int side, int mask);
}
@@ -0,0 +1,11 @@
package codechicken.multipart;
import net.minecraft.world.IBlockAccess;
/** Block counterpart to {@link IRedstoneConnector}. */
public interface IRedstoneConnectorBlock {
int getConnectionMask(IBlockAccess world, int x, int y, int z, int side);
int weakPowerLevel(IBlockAccess world, int x, int y, int z, int side, int mask);
}
@@ -0,0 +1,11 @@
package codechicken.multipart;
/** A part with redstone interaction. Its presence selects the generated redstone tile trait. */
public interface IRedstonePart {
int strongPowerLevel(int side);
int weakPowerLevel(int side);
boolean canConnectRedstone(int side);
}
@@ -1,310 +0,0 @@
package codechicken.multipart
import net.minecraft.world.World
import net.minecraft.block.Block
import net.minecraft.world.IBlockAccess
import net.minecraft.util.Direction
import codechicken.lib.vec.Rotation._
import net.minecraft.init.Blocks
/** Interface for parts with redstone interaction
*
* Marker interface for TRedstoneTile. This means that if a part is an instance
* of IRedstonePart, the container tile may be cast to TRedstoneTile
*/
trait IRedstonePart {
/** Returns the strong (indirect, through blocks) signal being emitted by this
* part to the specified side
*/
def strongPowerLevel(side: Int): Int
/** Returns the weak (direct) signal being emitted by this part to the
* specified side
*/
def weakPowerLevel(side: Int): Int
/** Returns true if this part can connect to redstone on the specified side.
* Blocking parts like covers will be handled by RedstoneInteractions
*/
def canConnectRedstone(side: Int): Boolean
}
/** For parts like wires that adhere to a specific face, reduces redstone
* connections to the specific edge between two faces. Should be implemented on
* parts implementing TFacePart
*/
trait IFaceRedstonePart extends IRedstonePart {
/** Return the face to which this redstone part is attached
*/
def getFace: Int
}
/** For parts that want to define their own connection masks (like center-center
* parts)
*/
trait IMaskedRedstonePart extends IRedstonePart {
/** Returns the redstone connection mask for this part on side. See
* IRedstoneConnector for mask definition
*/
def getConnectionMask(side: Int): Int
}
/** Interface for tile entities which split their redstone connections into a
* mask for each side (edges and center)
*
* All connection masks are a 5 bit map. The lowest 4 bits correspond to the
* connection toward the face specified Rotation.rotateSide(side&6, b) where b
* is the bit index from lowest to highest. Bit 5 corresponds to a connection
* opposite side.
*/
trait IRedstoneConnector {
/** Returns the redstone connection mask for this tile on side.
*/
def getConnectionMask(side: Int): Int
/** Returns the weak power level provided by this tile on side through mask
*/
def weakPowerLevel(side: Int, mask: Int): Int
}
/** Internal interface for TileMultipart instances hosting IRedstonePart
*/
trait IRedstoneTile extends IRedstoneConnector {
/** Returns a mask of spaces through which a wire could connect on side
*/
def openConnections(side: Int): Int
}
/** Block version of IRedstoneConnector Due to the inadequate
* Block.canConnectRedstone not handling the bottom side (nor the top
* particularly well)
*/
trait IRedstoneConnectorBlock {
def getConnectionMask(
world: IBlockAccess,
x: Int,
y: Int,
z: Int,
side: Int
): Int
def weakPowerLevel(
world: IBlockAccess,
x: Int,
y: Int,
z: Int,
side: Int,
mask: Int
): Int
}
/** static helper class for calculating various things about redstone. Indirect
* power (also known as strong power) is not handled here, just use
* world.getIndirectPowerTo Masks are defined in IRedstoneConnector
*/
object RedstoneInteractions {
import net.minecraft.util.Facing._
val vanillaSideMap = Array(-2, -1, 0, 2, 3, 1)
val sideVanillaMap = Array(1, 2, 5, 3, 4)
/** Hardcoded vanilla overrides for Block.canConnectRedstone (see
* \@IRedstoneConnectorBlock)
*/
val fullVanillaBlocks = Set(
Blocks.redstone_torch,
Blocks.unlit_redstone_torch,
Blocks.lever,
Blocks.stone_button,
Blocks.wooden_button,
Blocks.redstone_block
)
/** Get the direct power to p on side
*/
def getPowerTo(p: TMultiPart, side: Int): Int = {
val tile = p.tile
return getPowerTo(
tile.getWorldObj,
tile.xCoord,
tile.yCoord,
tile.zCoord,
side,
tile.asInstanceOf[IRedstoneTile].openConnections(side) & connectionMask(
p,
side
)
)
}
/** Get the direct power level to space (x, y, z) on side with mask
*/
def getPowerTo(
world: World,
x: Int,
y: Int,
z: Int,
side: Int,
mask: Int
): Int =
getPower(
world,
x + offsetsXForSide(side),
y + offsetsYForSide(side),
z + offsetsZForSide(side),
side ^ 1,
mask
)
/** Get the direct power level provided by space (x, y, z) on side with mask
*/
def getPower(
world: World,
x: Int,
y: Int,
z: Int,
side: Int,
mask: Int
): Int = {
val tile = world.getTileEntity(x, y, z)
if (tile.isInstanceOf[IRedstoneConnector])
return tile.asInstanceOf[IRedstoneConnector].weakPowerLevel(side, mask)
val block = world.getBlock(x, y, z)
if (block.isInstanceOf[IRedstoneConnectorBlock])
return block
.asInstanceOf[IRedstoneConnectorBlock]
.weakPowerLevel(world, x, y, z, side, mask)
val vmask = vanillaConnectionMask(block, world, x, y, z, side, true)
if ((vmask & mask) > 0) {
var m = world.getIndirectPowerLevelTo(x, y, z, side ^ 1)
if (m < 15 && block == Blocks.redstone_wire)
m =
Math.max(m, world.getBlockMetadata(x, y, z)) // painful vanilla kludge
return m
}
return 0
}
def vanillaToSide(vside: Int) = sideVanillaMap(vside + 1)
/** Get the connection mask of the block on side of (x, y, z).
* @param power,
* whether the connection mask is for signal transfer or visual connection.
* (some blocks accept power without visual connection)
*/
def otherConnectionMask(
world: IBlockAccess,
x: Int,
y: Int,
z: Int,
side: Int,
power: Boolean
): Int =
getConnectionMask(
world,
x + offsetsXForSide(side),
y + offsetsYForSide(side),
z + offsetsZForSide(side),
side ^ 1,
power
)
/** Get the connection mask of part on side
*/
def connectionMask(p: TMultiPart, side: Int): Int = {
if (
p.isInstanceOf[IRedstonePart] && p
.asInstanceOf[IRedstonePart]
.canConnectRedstone(side)
) {
if (p.isInstanceOf[IFaceRedstonePart]) {
val fside = p.asInstanceOf[IFaceRedstonePart].getFace
if ((side & 6) == (fside & 6))
return 0x10
return 1 << rotationTo(side & 6, fside)
} else if (p.isInstanceOf[IMaskedRedstonePart]) {
return p.asInstanceOf[IMaskedRedstonePart].getConnectionMask(side)
}
return 0x1f
}
return 0
}
/** @param power
* If true, don't test canConnectRedstone on blocks, just get a power
* transmission mask rather than a visual connection
*/
def getConnectionMask(
world: IBlockAccess,
x: Int,
y: Int,
z: Int,
side: Int,
power: Boolean
): Int = {
val tile = world.getTileEntity(x, y, z)
if (tile.isInstanceOf[IRedstoneConnector])
return tile.asInstanceOf[IRedstoneConnector].getConnectionMask(side)
val block = world.getBlock(x, y, z)
if (block.isInstanceOf[IRedstoneConnectorBlock])
return block
.asInstanceOf[IRedstoneConnectorBlock]
.getConnectionMask(world, x, y, z, side)
return vanillaConnectionMask(block, world, x, y, z, side, power)
}
/** Returns the connection mask for a vanilla block
*/
def vanillaConnectionMask(
block: Block,
world: IBlockAccess,
x: Int,
y: Int,
z: Int,
side: Int,
power: Boolean
): Int = {
if (fullVanillaBlocks(block))
return 0x1f
/** so that these can be conducted to from face parts on the other side of
* the block. Due to vanilla's in adequecy with redstone/logic on walls
*/
if (
block == Blocks.redstone_wire || block == Blocks.powered_comparator || block == Blocks.unpowered_comparator
) {
if (side != 0)
return if (power) 0x1f else 4
return 0
}
val vside = vanillaSideMap(side)
if (
block == Blocks.powered_repeater || block == Blocks.unpowered_repeater
) // stupid minecraft hardcodes
{
val meta = world.getBlockMetadata(x, y, z)
if (vside == (meta & 3) || vside == Direction.rotateOpposite(meta & 3))
return if (power) 0x1f else 4
return 0
}
if (
power || block.canConnectRedstone(world, x, y, z, vside)
) // some blocks accept power without visualising connections
return 0x1f
return 0
}
}
@@ -0,0 +1,7 @@
package codechicken.multipart;
/** Internal interface for multipart tiles hosting {@link IRedstonePart}. */
public interface IRedstoneTile extends IRedstoneConnector {
int openConnections(int side);
}
@@ -0,0 +1,151 @@
package codechicken.multipart;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import codechicken.lib.vec.Rotation;
import scala.collection.JavaConversions;
import scala.collection.immutable.Set;
/** Scala-compatible singleton carrying the redstone interaction implementation. */
public final class RedstoneInteractions$ {
public static final RedstoneInteractions$ MODULE$ = new RedstoneInteractions$();
private final int[] vanillaSideMap = { -2, -1, 0, 2, 3, 1 };
private final int[] sideVanillaMap = { 1, 2, 5, 3, 4 };
private final Set<Block> fullVanillaBlocks = JavaConversions.asScalaSet(
new HashSet<>(
Arrays.asList(
Blocks.redstone_torch,
Blocks.unlit_redstone_torch,
Blocks.lever,
Blocks.stone_button,
Blocks.wooden_button,
Blocks.redstone_block)))
.toSet();
private RedstoneInteractions$() {}
public int[] vanillaSideMap() {
return vanillaSideMap;
}
public int[] sideVanillaMap() {
return sideVanillaMap;
}
public Set<Block> fullVanillaBlocks() {
return fullVanillaBlocks;
}
public int getPowerTo(TMultiPart part, int side) {
TileMultipart tile = part.tile();
return getPowerTo(
tile.getWorldObj(),
tile.xCoord,
tile.yCoord,
tile.zCoord,
side,
((IRedstoneTile) tile).openConnections(side) & connectionMask(part, side));
}
public int getPowerTo(World world, int x, int y, int z, int side, int mask) {
return getPower(
world,
x + net.minecraft.util.Facing.offsetsXForSide[side],
y + net.minecraft.util.Facing.offsetsYForSide[side],
z + net.minecraft.util.Facing.offsetsZForSide[side],
side ^ 1,
mask);
}
public int getPower(World world, int x, int y, int z, int side, int mask) {
TileEntity tile = world.getTileEntity(x, y, z);
if (tile instanceof IRedstoneConnector) {
return ((IRedstoneConnector) tile).weakPowerLevel(side, mask);
}
Block block = world.getBlock(x, y, z);
if (block instanceof IRedstoneConnectorBlock) {
return ((IRedstoneConnectorBlock) block).weakPowerLevel(world, x, y, z, side, mask);
}
if ((vanillaConnectionMask(block, world, x, y, z, side, true) & mask) > 0) {
int power = world.getIndirectPowerLevelTo(x, y, z, side ^ 1);
if (power < 15 && Objects.equals(block, Blocks.redstone_wire)) {
power = Math.max(power, world.getBlockMetadata(x, y, z));
}
return power;
}
return 0;
}
public int vanillaToSide(int vanillaSide) {
return sideVanillaMap[vanillaSide + 1];
}
public int otherConnectionMask(IBlockAccess world, int x, int y, int z, int side, boolean power) {
return getConnectionMask(
world,
x + net.minecraft.util.Facing.offsetsXForSide[side],
y + net.minecraft.util.Facing.offsetsYForSide[side],
z + net.minecraft.util.Facing.offsetsZForSide[side],
side ^ 1,
power);
}
public int connectionMask(TMultiPart part, int side) {
if (!(part instanceof IRedstonePart) || !((IRedstonePart) part).canConnectRedstone(side)) {
return 0;
}
if (part instanceof IFaceRedstonePart) {
int face = ((IFaceRedstonePart) part).getFace();
return (side & 6) == (face & 6) ? 0x10 : 1 << Rotation.rotationTo(side & 6, face);
}
if (part instanceof IMaskedRedstonePart) {
return ((IMaskedRedstonePart) part).getConnectionMask(side);
}
return 0x1F;
}
public int getConnectionMask(IBlockAccess world, int x, int y, int z, int side, boolean power) {
TileEntity tile = world.getTileEntity(x, y, z);
if (tile instanceof IRedstoneConnector) {
return ((IRedstoneConnector) tile).getConnectionMask(side);
}
Block block = world.getBlock(x, y, z);
if (block instanceof IRedstoneConnectorBlock) {
return ((IRedstoneConnectorBlock) block).getConnectionMask(world, x, y, z, side);
}
return vanillaConnectionMask(block, world, x, y, z, side, power);
}
public int vanillaConnectionMask(Block block, IBlockAccess world, int x, int y, int z, int side, boolean power) {
if (fullVanillaBlocks.contains(block)) {
return 0x1F;
}
if (Objects.equals(block, Blocks.redstone_wire) || Objects.equals(block, Blocks.powered_comparator)
|| Objects.equals(block, Blocks.unpowered_comparator)) {
return side == 0 ? 0 : power ? 0x1F : 4;
}
int vanillaSide = vanillaSideMap[side];
if (Objects.equals(block, Blocks.powered_repeater) || Objects.equals(block, Blocks.unpowered_repeater)) {
int metadata = world.getBlockMetadata(x, y, z) & 3;
return vanillaSide == metadata || vanillaSide == Direction.rotateOpposite[metadata] ? power ? 0x1F : 4 : 0;
}
return power || block.canConnectRedstone(world, x, y, z, vanillaSide) ? 0x1F : 0;
}
}
@@ -0,0 +1,58 @@
package codechicken.multipart;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import scala.collection.immutable.Set;
/** Static forwarders for Java and existing bytecode; implementation remains on {@link RedstoneInteractions$}. */
public final class RedstoneInteractions {
private RedstoneInteractions() {}
public static int[] vanillaSideMap() {
return RedstoneInteractions$.MODULE$.vanillaSideMap();
}
public static int[] sideVanillaMap() {
return RedstoneInteractions$.MODULE$.sideVanillaMap();
}
public static Set<Block> fullVanillaBlocks() {
return RedstoneInteractions$.MODULE$.fullVanillaBlocks();
}
public static int getPowerTo(TMultiPart part, int side) {
return RedstoneInteractions$.MODULE$.getPowerTo(part, side);
}
public static int getPowerTo(World world, int x, int y, int z, int side, int mask) {
return RedstoneInteractions$.MODULE$.getPowerTo(world, x, y, z, side, mask);
}
public static int getPower(World world, int x, int y, int z, int side, int mask) {
return RedstoneInteractions$.MODULE$.getPower(world, x, y, z, side, mask);
}
public static int vanillaToSide(int vanillaSide) {
return RedstoneInteractions$.MODULE$.vanillaToSide(vanillaSide);
}
public static int otherConnectionMask(IBlockAccess world, int x, int y, int z, int side, boolean power) {
return RedstoneInteractions$.MODULE$.otherConnectionMask(world, x, y, z, side, power);
}
public static int connectionMask(TMultiPart part, int side) {
return RedstoneInteractions$.MODULE$.connectionMask(part, side);
}
public static int getConnectionMask(IBlockAccess world, int x, int y, int z, int side, boolean power) {
return RedstoneInteractions$.MODULE$.getConnectionMask(world, x, y, z, side, power);
}
public static int vanillaConnectionMask(Block block, IBlockAccess world, int x, int y, int z, int side,
boolean power) {
return RedstoneInteractions$.MODULE$.vanillaConnectionMask(block, world, x, y, z, side, power);
}
}