refactor: port redstone tile trait to java

This commit is contained in:
Algent committed 2026-08-28 16:16:31 +03:00
1 parent eff7509585
commit e2822d3938
7 files changed
+289 -131

No files matched your search

+34 -21
View File
@@ -24,10 +24,10 @@ 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,
focused profile, first traversal optimization, complete redstone interaction helper unit, `MicroRecipe` port, and both
Java-trait checkpoints are complete. `TPartialOcclusionTile` proved the no-field path; `TSlottedTile` now proves field
accessors, per-instance initialization, rebinding/copying, callbacks, super bridges, and class caching. The next
measured target is `TRedstoneTile`; see `JAVA_MIGRATION_PROFILE.md`.
focused profile, first traversal optimization, complete redstone interaction helper unit, `MicroRecipe` port, and the
first three Java-trait ports are complete. `TPartialOcclusionTile` proved the no-field path, `TSlottedTile` proved state
and lifecycle rewriting, and `TRedstoneTile` removed the measured redstone allocation while retaining its exact runtime
interface. 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
@@ -123,21 +123,21 @@ Exception-table metadata does not impose a meaningful steady-state cost merely b
### More credible performance risks
The source and bytecode audit identified allocation patterns that are more plausible performance targets:
The source and bytecode audit identified these allocation patterns; the named ports have now resolved them:
- The Java port's `TileMultipart.updateEntity()` still traverses through `operate(Function1)`, whose current
`parts()` helper materializes an `ArrayList`, backing array, Scala iterator and Java-conversion wrappers per call.
- `TRedstoneTile` power and connection queries create closures and `scala.runtime.IntRef` boxes in frequently queried
code.
- The earlier Java `TileMultipart.updateEntity()` traversed through `operate(Function1)`, whose `parts()` helper
materialized an `ArrayList`, backing array, Scala iterator and Java-conversion wrappers per call.
- The former Scala `TRedstoneTile` queries created closures and `scala.runtime.IntRef` boxes; the Java trait now walks
the normal immutable list without allocation while preserving an arbitrary-`Seq` fallback.
- Several Scala 2.11 collection, range, and `JavaConversions` paths create closure objects, boxed primitives, iterators, or temporary collections.
- `TSlottedTile.canAddPart` still uses an exception-based non-local return. `MicroRecipe`'s equivalent scans are now
- The former `TSlottedTile.canAddPart` and `MicroRecipe` scans used exception-based non-local returns; both are now
ordinary Java loops.
- Rendering code in `TileMultipart` already uses cached arrays and `while` loops in important paths. It should be preserved as evidence of deliberate optimization, not mechanically rewritten into streams or higher-level collection pipelines.
The focused Forge/JFR baseline confirms both risks. With eight parts, `updateEntity` and `operate` allocate about 184
bytes per call, while a three-query redstone iteration allocates 80.5 bytes. CPU samples identify the same collection,
boxing and closure paths. These are focused measurements, not whole-pack TPS; retain the workload and re-profile after
each relevant migration phase. See `JAVA_MIGRATION_PROFILE.md`.
The focused Forge/JFR baseline confirmed both risks. With eight parts, `updateEntity` and `operate` allocated about 184
bytes per call, while a three-query redstone iteration allocated 80.5 bytes. The completed ports reduce the normal
paths to effectively zero measured allocation; these remain focused measurements, not whole-pack TPS. See
`JAVA_MIGRATION_PROFILE.md`.
### Runtime code generation is architectural, not incidental
@@ -333,14 +333,16 @@ and the already-ported registry again supports Schematica.
- [x] Keep fastutil out of these paths because profiling did not justify another dependency or data structure.
- [x] Re-profile the same scenarios and record both improvements and regressions.
Status: active. `operate` now preserves its captured-sequence mutation semantics without collection materialization,
Status: complete for the measured targets. `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.
The comparison proved its allocation was owned by the generated `TRedstoneTile`, which is now Java and allocation-free
on the normal immutable-list path.
`MicroRecipe` is also Java: all five recipe forms and precedence are characterized, its published Scala façade remains,
and its closure-backed scans and non-local returns are gone. `TPartialOcclusionTile` completed the simple no-field
Java-trait pilot, and `TSlottedTile` completed the stateful field/lifecycle checkpoint while removing the remaining
slot-scan closures and exception-backed return. The remaining measured item is `TRedstoneTile`; characterize its exact
generated surface and real consumers, then re-profile immediately before and after its Java port.
slot-scan closures and exception-backed return. The paired `TRedstoneTile` run removed 80.5 B per three-query iteration
and improved throughput by 20.3% with an identical checksum.
Exit condition: identified steady-state Scala allocation sites are removed with compatible results.
@@ -351,12 +353,13 @@ Exit condition: identified steady-state Scala allocation sites are removed with
- [x] Port one simple built-in trait as a pilot using `registerJavaTrait`.
- [x] Verify generated field accessors, initialization, copying, lifecycle callbacks, super bridges, and class caching
on the stateful `TSlottedTile` checkpoint.
- [x] Characterize ProjectRed/Extra Utilities redstone calls and port `TRedstoneTile` with an immediate paired profile.
- [ ] Convert remaining traits in small related groups.
- [ ] Document or deliberately relax the Java trait restrictions only when a real trait requires it.
- [ ] Preserve pass-through interface behavior.
- [ ] Keep the completed OpenComputers `TSlottedTile.v_partMap` mutation/rebinding case green; explicitly cover AE2's
`TIInventoryTile.rebuildSlotMap` before the inventory trait and ProjectRed/Extra Utilities behavior before
`TRedstoneTile`.
- [x] Keep the completed OpenComputers `TSlottedTile.v_partMap` mutation/rebinding case green and cover ProjectRed/
Extra Utilities behavior before `TRedstoneTile`.
- [ ] Explicitly cover AE2's `TIInventoryTile.rebuildSlotMap` before the inventory trait.
Exit condition: built-in behavior is implemented in Java while the established runtime composition mechanism remains stable.
@@ -692,3 +695,13 @@ generated-trait compatibility work. Scala-runtime removal remains a later projec
recompiled directly against the untransformed dev jar sees the Java mixin input as a class. Consumers that name a
generated trait therefore need a transformed compile stub or must avoid direct trait invocations; record this before
claiming source-compatible downstream rebuilds.
- Characterized `TRedstoneTile` against untouched Scala with three Forge cases covering its exact eight-method runtime
interface, class caching, face/edge conduction, strong and weak maxima, mask filtering, arbitrary `Seq` input,
neighbor masks, and vanilla-side translation. This directly covers ProjectRed's `openConnections` and Extra
Utilities' one-argument `weakPowerLevel` calls.
- Ported `TRedstoneTile` to Java with allocation-free immutable-list traversal and an iterator fallback for other
published `Seq` values. A package-private shim isolates inherited `TileMultipart` methods and Minecraft coordinate
fields from known Java-trait transformer limitations; no public redstone or generated-interface member changed.
- The paired 50,000,000-iteration run fell from 4,023,855,000 bytes / 80.5 B per three-query iteration to zero measured
allocation, while throughput rose 20.3% from 6,636,424 to 7,986,213 iterations/s. The checksum remained
`3315999992`, and all 145 plain-JVM plus 46 Forge tests pass.
+4 -3
View File
@@ -504,9 +504,10 @@ behavior:
Current-branch generator verification: `ForgeEnvironmentSmokeTest` pins exact direct-Java-source `TSlottedTile`
interface/field generation, initialization, rebinding and caching, an external Scala microblock trait registered by
name like ProjectRed's `LightMicroblock`, direct-Java-source `TPartialOcclusionTile` rewriting and override dispatch,
and server-only pass-through forwarding, overloading,
single-implementor selection, copying/rebinding, and removal cleanup. Full downstream mixed tiles and client-side
selection remain Phase 7 integration cases.
direct-Java-source `TRedstoneTile`'s exact eight-method interface and class caching, and server-only pass-through
forwarding, overloading, single-implementor selection, copying/rebinding, and removal cleanup.
`TRedstoneTileFunctionalTest` additionally pins the ProjectRed/Extra Utilities query surface, masks, conduction, and
world-side routing. Full downstream mixed tiles and client-side selection remain Phase 7 integration cases.
With these gates, the source audit is actionable: the port can simplify internals freely where no listed observation
changes, while each externally observed behavior has a named consumer and a focused way to prove compatibility.
+50
View File
@@ -1459,3 +1459,53 @@ a numeric performance claim. No new dependency or generator change was needed.
- Existing live-world lifecycle tests continue to cover add/remove slot caches and relocation of the generated tile.
- Complete plain-JVM suite: 145 tests, 0 failures, 0 errors.
- Java 8 Forge dedicated-server suite: 43 tests, 0 failures, 0 errors.
## 2026-08-28 — TRedstoneTile Java-trait port
ProjectRed directly casts a generated tile to `TRedstoneTile` and calls `openConnections(int)`. Extra Utilities casts
the same type and calls the inherited one-argument `weakPowerLevel(int)`. Neither shipping consumer references
`TRedstoneTile$class`; UtilitiesInExcess has no direct reference in its current source.
### Observable behavior
No known runtime divergence. Strong power still scans only `IRedstonePart` instances, ignores connection masks, and
returns the greatest positive level from a zero baseline. Face and edge parts retain the same center/rotation
conduction rules. Connection masks are still intersected with the open face/edge mask before being combined, while
weak power calls only connected redstone parts and takes their maximum from zero.
The one-argument weak-power method still intersects the tile's mask with the adjacent connector's power mask.
`canConnectRedstone` still applies the legacy vanilla-to-multipart side mapping and uses the neighbor's non-power mask.
Normal immutable Scala `List` storage is traversed without allocation; an arbitrary `Seq` supplied through the public
setter retains an iterator fallback.
### Generated ABI and raw input divergence
At Forge runtime `TRedstoneTile` remains a public interface extending exactly `IRedstoneTile`, with no fields and the
same eight abstract methods: `strongPowerLevel(int)`, both `weakPowerLevel` overloads, `canConnectRedstone(int)`,
`openConnections(int)`, `getConnectionMask(int)`, `redstoneConductionF(int)`, and `redstoneConductionE(int)`.
Generated composites still implement that interface, and equal trait sets still reuse the same generated class.
The untransformed artifact changes from the Scala interface, `$class` helper, and four `$$anonfun$` classes to a
concrete Java `TileMultipart` subclass plus package-private `TRedstoneTileAccess`. The shim is required because the
current Java-trait transformer treats direct inherited field reads as trait fields and emits an invalid cast for
inherited virtual calls. It performs coordinate, `partList`, and virtual `partMap` access outside the transformed
class. It adds no public member and does not change the generator.
As with `TSlottedTile`, this preserves existing consumer binaries but not recompilation directly against the raw dev
jar: Java source presents the mixin input as a class, while Forge rewrites it to an interface at runtime. A transformed
compile stub or downstream source guidance is still required before claiming source-compatible rebuilds.
### Performance result
The paired 50,000,000-iteration Forge/JFR run fell from 4,023,855,000 allocated bytes / 80.5 B per three-query
iteration to zero measured bytes / 0.0 B. Elapsed time fell from 7.534 s to 6.261 s, raising throughput from 6,636,424
to 7,986,213 iterations/s (20.3%). Both runs produced checksum `3315999992`.
### Validation
- `TRedstoneTileFunctionalTest`: 3 Forge tests covering the exact eight-method interface and class cache, face/edge
conduction, strong and weak maxima, mask filtering, non-redstone parts, arbitrary `Seq` input, neighbor masks, and
vanilla-side translation.
- Complete plain-JVM suite: 145 tests, 0 failures, 0 errors.
- Java 8 Forge dedicated-server suite: 46 tests, 0 failures, 0 errors.
- Clean formatting, checkstyle, build, generated runtime reflection, and paired profile checksum.
+29 -19
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`. 72 commits including both `TSlottedTile` commits.
Branch: `algent/java`. Base: `master`. 74 commits including the separate `TRedstoneTile` characterization and port.
## 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: **145 plain-JVM tests, 43 Forge server tests, all passing at their last completed runs.**
Current baseline: **145 plain-JVM tests, 46 Forge server tests, all passing at their last completed runs.**
### ABI diff against the reference
@@ -182,6 +182,11 @@ silently, but expect it in every remaining renderer conversion.
**Two test classes sharing global registry state** must guard their registrations, and the registries' error paths call
a logger that is null until `preInit`, so they cannot run headless at all.
**Java traits cannot directly touch inherited members with the current transformer.** An inherited field read is
mistaken for trait-owned state, and an inherited virtual call takes a broken cast-rewrite path. `TRedstoneTile` keeps
coordinate, `partList`, and virtual `partMap` access in package-private `TRedstoneTileAccess`; use that pattern or fix
and characterize the generator before converting another trait with the same bytecode shape.
## What is done
All eight load-bearing `$class` helpers from the inventory, both registries, and the two central types:
@@ -189,15 +194,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`, the complete
`IRedstonePart`/`RedstoneInteractions` unit, `MicroRecipe`, and the `TPartialOcclusionTile` and `TSlottedTile`
Java-trait checkpoints.
`IRedstonePart`/`RedstoneInteractions` unit, `MicroRecipe`, and the `TPartialOcclusionTile`, `TSlottedTile`, and
`TRedstoneTile` Java-trait ports.
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.
84 Java files, 44 Scala files, ~5,806 Scala lines left (non-blank; that is the metric this figure has always used).
85 Java files, 43 Scala files, ~5,730 Scala lines left (non-blank; that is the metric this figure has always used).
## What is left, and in what order
@@ -231,8 +236,12 @@ parts, and its normal immutable-`List` path now traverses the captured list dire
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.
redstone-tile selection are characterized.
`TRedstoneTile` has now completed that Phase 5 path. ProjectRed's direct `openConnections` call and Extra Utilities'
one-argument `weakPowerLevel` call are covered, the runtime interface remains field-free with the exact same eight
methods, and the paired workload fell from 80.5 B to 0.0 B per three-query iteration with 20.3% higher throughput and
the same checksum. Its package-private access shim is required by current inherited-member transformer limitations.
`MicroRecipe` is now Java. The complete 17-method static/companion surface, immutable Scala split map, exact material
and tag matching, all five recipe forms, class-specific gluing, saw position, and hollow-over-gluing precedence are
@@ -253,12 +262,12 @@ occupied-slot rejection, value equality, actual add/remove/move lifecycle, and g
`MicroblockPlacement`, `PlacementGrids`, `BlockMicroMaterial`, `MissingMicroMaterial`, `ConfigContent`,
`DefaultContent`.
**Phase 5, needs the `registerJavaTrait` path.** `TileMultipartClient` and everything in `multipart/scalatraits/`.
These are registered with the ASM generator; converting them is a different mechanism with documented restrictions.
The no-field and stateful checkpoints are complete without a generator change. Next characterize `TRedstoneTile`'s
exact generated interface and every ProjectRed/Extra Utilities call, capture a fresh allocation baseline, port its
queries with ordinary loops, and immediately rerun the same profile. Keep `TIInventoryTile` separate until AE2's
`rebuildSlotMap` and inventory-field behavior are frozen.
**Phase 5, needs the `registerJavaTrait` path.** `TileMultipartClient` and the remaining Scala files in
`multipart/scalatraits/`. The no-field, stateful, and measured hot-query cases are complete without a generator change.
Next characterize `TTileChangeTile`: it is server-side, has one copied/rebuilt field, lifecycle super calls, coordinate
filtering, and callback dispatch, making it the smallest useful follow-up for the inherited-member shim. Keep
`TIInventoryTile` separate until AE2's `rebuildSlotMap` and inventory-field behavior are frozen; keep
`TRandomDisplayTickTile` with the client-side test work.
**Phase 6/7, last.** `Microblock` and the microblock shape hierarchy, `MicroblockGenerator`, `MultipartGenerator`, and
all of `multipart/asm/`. The ASM subsystem should be last; freeze generated-class fixtures before touching it.
@@ -272,16 +281,17 @@ all of `multipart/asm/`. The ASM subsystem should be last; freeze generated-clas
work and is required before release claims about real TPS.
- The server side of flag-sensitive pass-through registration is automated; client-side exclusion still belongs to
the packaged-client/manual compatibility run.
- A shipping consumer compiled against the old `TSlottedTile` interface remains binary-compatible because Forge still
exposes that exact interface at runtime. A consumer recompiled against the untransformed dev jar instead sees the
concrete Java mixin input and can emit class/field opcodes that are invalid after Forge rewrites it to an interface.
Provide a transformed compile stub or downstream source guidance before claiming source-compatible rebuilds.
- Shipping consumers compiled against the old `TSlottedTile` and `TRedstoneTile` interfaces remain binary-compatible
because Forge still exposes those exact interfaces at runtime. A consumer recompiled against the untransformed dev
jar instead sees concrete Java mixin inputs and can emit class/field opcodes that are invalid after Forge rewrites
them to interfaces. Provide a transformed compile stub or downstream source guidance before claiming
source-compatible rebuilds.
- Microblock-specific NBT and packet payloads still need characterization immediately before that subsystem changes;
the compact core tile/part fixture is complete.
- `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`; it is now the next measured target.
- The focused synthetic redstone allocation is resolved (80.5 B to 0.0 B per three-query iteration). A representative
full-pack profile remains the authority for choosing any further optimization target.
- 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.
+23 -2
View File
@@ -127,5 +127,26 @@ field/accessor generation, initialization, copying, lifecycle behavior, and cach
Scala range closures and the exception-backed slot-scan return structurally, but the focused workload has no slotted
placement phase, so no numeric performance claim is made for that port.
The remaining measured redstone allocation lives in `TRedstoneTile`. Capture a fresh baseline with this exact workload,
characterize ProjectRed and Extra Utilities behavior, port the queries, and rerun immediately afterward.
## TRedstoneTile result captured 2026-08-28
The port was measured immediately before and after with the same JVM, eight-part generated tile, warm-up, and
50,000,000-iteration workload. Both runs produced checksum `3315999992`.
| Implementation | Elapsed | Operations/s | Allocated bytes | Bytes/operation |
| --- | ---: | ---: | ---: | ---: |
| Scala trait | 7.534 s | 6,636,424 | 4,023,855,000 | 80.5 |
| Java trait | 6.261 s | 7,986,213 | 0 | 0.0 |
The Java trait removes all measured allocation from the three-query iteration and improves throughput by 20.3% in
this paired run. The checksum and all characterization tests are unchanged. Normal immutable Scala `List` part
storage is traversed through its existing head/tail chain; the published `partList` setter still accepts any `Seq`,
so non-`List` implementations retain an iterator fallback.
The existing Java-trait transformer cannot safely rewrite bytecode that directly reads inherited Minecraft fields or
calls inherited `TileMultipart` methods. A package-private `TRedstoneTileAccess` shim keeps coordinate, `partList`, and
virtual `partMap` access outside the transformed class. This changes no public facade or generated-trait member and
required no generator change.
The two focused steady-state allocation targets identified by this workload are now resolved: `TileMultipart.operate`
and generated redstone queries are effectively allocation-free on their normal immutable-list paths. Further
optimization should follow a new representative profile rather than extending this synthetic workload speculatively.
@@ -0,0 +1,149 @@
package codechicken.multipart.scalatraits;
import codechicken.lib.vec.Rotation;
import codechicken.multipart.IRedstonePart;
import codechicken.multipart.IRedstoneTile;
import codechicken.multipart.PartMap;
import codechicken.multipart.RedstoneInteractions;
import codechicken.multipart.TEdgePart;
import codechicken.multipart.TFacePart;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
import scala.collection.Iterator;
import scala.collection.Seq;
/** Mixin implementation for multipart redstone queries. */
public class TRedstoneTile extends TileMultipart implements IRedstoneTile {
@Override
@SuppressWarnings("unchecked")
public int strongPowerLevel(int side) {
int max = 0;
Seq<TMultiPart> current = TRedstoneTileAccess.partList(this);
if (!(current instanceof scala.collection.immutable.List)) {
Iterator<TMultiPart> iterator = current.iterator();
while (iterator.hasNext()) {
TMultiPart part = iterator.next();
if (part instanceof IRedstonePart) {
max = Math.max(max, ((IRedstonePart) part).strongPowerLevel(side));
}
}
return max;
}
scala.collection.immutable.List<TMultiPart> parts = (scala.collection.immutable.List<TMultiPart>) current;
while (!parts.isEmpty()) {
TMultiPart part = parts.head();
parts = (scala.collection.immutable.List<TMultiPart>) parts.tail();
if (part instanceof IRedstonePart) {
max = Math.max(max, ((IRedstonePart) part).strongPowerLevel(side));
}
}
return max;
}
@Override
public int openConnections(int side) {
int mask = 0x10;
for (int rotation = 0; rotation < 4; rotation++) {
int edge = PartMap.edgeBetween(side, Rotation.rotateSide(side & 6, rotation));
if (redstoneConductionE(edge)) {
mask |= 1 << rotation;
}
}
return mask & redstoneConductionF(side);
}
public int redstoneConductionF(int slot) {
TMultiPart part = TRedstoneTileAccess.partMap(this, slot);
return part == null ? 0x1F : ((TFacePart) part).redstoneConductionMap();
}
public boolean redstoneConductionE(int slot) {
TMultiPart part = TRedstoneTileAccess.partMap(this, slot);
return part == null || ((TEdgePart) part).conductsRedstone();
}
@Override
public int weakPowerLevel(int side) {
return weakPowerLevel(side, TRedstoneTileAccess.otherConnectionMask(this, side, true));
}
@Override
public boolean canConnectRedstone(int side) {
int multipartSide = RedstoneInteractions.vanillaToSide(side);
return (getConnectionMask(multipartSide) & TRedstoneTileAccess.otherConnectionMask(this, multipartSide, false))
> 0;
}
@Override
@SuppressWarnings("unchecked")
public int getConnectionMask(int side) {
int openMask = openConnections(side);
int result = 0;
Seq<TMultiPart> current = TRedstoneTileAccess.partList(this);
if (!(current instanceof scala.collection.immutable.List)) {
Iterator<TMultiPart> iterator = current.iterator();
while (iterator.hasNext()) {
result |= RedstoneInteractions.connectionMask(iterator.next(), side) & openMask;
}
return result;
}
scala.collection.immutable.List<TMultiPart> parts = (scala.collection.immutable.List<TMultiPart>) current;
while (!parts.isEmpty()) {
TMultiPart part = parts.head();
parts = (scala.collection.immutable.List<TMultiPart>) parts.tail();
result |= RedstoneInteractions.connectionMask(part, side) & openMask;
}
return result;
}
@Override
@SuppressWarnings("unchecked")
public int weakPowerLevel(int side, int mask) {
int connectedMask = openConnections(side) & mask;
int max = 0;
Seq<TMultiPart> current = TRedstoneTileAccess.partList(this);
if (!(current instanceof scala.collection.immutable.List)) {
Iterator<TMultiPart> iterator = current.iterator();
while (iterator.hasNext()) {
TMultiPart part = iterator.next();
if ((RedstoneInteractions.connectionMask(part, side) & connectedMask) > 0) {
max = Math.max(max, ((IRedstonePart) part).weakPowerLevel(side));
}
}
return max;
}
scala.collection.immutable.List<TMultiPart> parts = (scala.collection.immutable.List<TMultiPart>) current;
while (!parts.isEmpty()) {
TMultiPart part = parts.head();
parts = (scala.collection.immutable.List<TMultiPart>) parts.tail();
if ((RedstoneInteractions.connectionMask(part, side) & connectedMask) > 0) {
max = Math.max(max, ((IRedstonePart) part).weakPowerLevel(side));
}
}
return max;
}
}
/** Keeps inherited Minecraft field reads outside the generated trait transformer. */
final class TRedstoneTileAccess {
private TRedstoneTileAccess() {}
static Seq<TMultiPart> partList(IRedstoneTile redstone) {
return ((TileMultipart) redstone).partList();
}
static TMultiPart partMap(IRedstoneTile redstone, int slot) {
return ((TileMultipart) redstone).partMap(slot);
}
static int otherConnectionMask(IRedstoneTile redstone, int side, boolean power) {
TileMultipart tile = (TileMultipart) redstone;
return RedstoneInteractions
.otherConnectionMask(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, side, power);
}
}
@@ -1,86 +0,0 @@
package codechicken.multipart.scalatraits
import codechicken.multipart.TileMultipart
import codechicken.multipart.IRedstonePart
import codechicken.multipart.RedstoneInteractions._
import codechicken.multipart.PartMap._
import codechicken.lib.vec.Rotation._
import codechicken.multipart.IRedstoneTile
import codechicken.multipart.TFacePart
import codechicken.multipart.TEdgePart
/** Mixin trait implementation for IRedstonePart Provides and overrides various
* redstone functions.
*/
trait TRedstoneTile extends TileMultipart with IRedstoneTile {
/** Returns the strong (indirect) power being emitted fr
*/
override def strongPowerLevel(side: Int): Int = {
var max = 0
for (p @ (_p: IRedstonePart) <- partList.iterator) {
val l = p.strongPowerLevel(side)
if (l > max) max = l
}
return max
}
def openConnections(side: Int): Int = {
var m = 0x10
var i = 0
while (i < 4) {
if (redstoneConductionE(edgeBetween(side, rotateSide(side & 6, i))))
m |= 1 << i
i += 1
}
m &= redstoneConductionF(side)
return m
}
def redstoneConductionF(i: Int) = partMap(i) match {
case null => 0x1f
case p => p.asInstanceOf[TFacePart].redstoneConductionMap
}
def redstoneConductionE(i: Int) = partMap(i) match {
case null => true
case p => p.asInstanceOf[TEdgePart].conductsRedstone
}
override def weakPowerLevel(side: Int): Int =
weakPowerLevel(
side,
otherConnectionMask(getWorldObj, xCoord, yCoord, zCoord, side, true)
)
override def canConnectRedstone(side: Int): Boolean = {
val vside = vanillaToSide(side)
return (getConnectionMask(vside) & otherConnectionMask(
getWorldObj,
xCoord,
yCoord,
zCoord,
vside,
false
)) > 0
}
def getConnectionMask(side: Int): Int = {
val mask = openConnections(side)
var res = 0
partList.foreach(p => res |= connectionMask(p, side) & mask)
return res
}
def weakPowerLevel(side: Int, mask: Int): Int = {
val tmask = openConnections(side) & mask
var max = 0
partList.foreach(p =>
if ((connectionMask(p, side) & tmask) > 0) {
val l = p.asInstanceOf[IRedstonePart].weakPowerLevel(side)
if (l > max) max = l
}
)
return max
}
}