From e2822d3938694ebe37794c4dfd1567c376340a60 Mon Sep 17 00:00:00 2001 From: Algent Date: Fri, 28 Aug 2026 16:16:31 +0300 Subject: [PATCH] refactor: port redstone tile trait to java --- JAVA_MIGRATION.md | 55 ++++--- JAVA_MIGRATION_CONSUMER_AUDIT.md | 7 +- JAVA_MIGRATION_DIVERGENCES.md | 50 ++++++ JAVA_MIGRATION_HANDOFF.md | 48 +++--- JAVA_MIGRATION_PROFILE.md | 25 ++- .../multipart/scalatraits/TRedstoneTile.java | 149 ++++++++++++++++++ .../multipart/scalatraits/TRedstoneTile.scala | 86 ---------- 7 files changed, 289 insertions(+), 131 deletions(-) create mode 100644 src/main/scala/codechicken/multipart/scalatraits/TRedstoneTile.java delete mode 100644 src/main/scala/codechicken/multipart/scalatraits/TRedstoneTile.scala diff --git a/JAVA_MIGRATION.md b/JAVA_MIGRATION.md index 31fb55b..1004758 100644 --- a/JAVA_MIGRATION.md +++ b/JAVA_MIGRATION.md @@ -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. diff --git a/JAVA_MIGRATION_CONSUMER_AUDIT.md b/JAVA_MIGRATION_CONSUMER_AUDIT.md index 9e686c4..9e2b5aa 100644 --- a/JAVA_MIGRATION_CONSUMER_AUDIT.md +++ b/JAVA_MIGRATION_CONSUMER_AUDIT.md @@ -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. diff --git a/JAVA_MIGRATION_DIVERGENCES.md b/JAVA_MIGRATION_DIVERGENCES.md index b172b71..c47bb3f 100644 --- a/JAVA_MIGRATION_DIVERGENCES.md +++ b/JAVA_MIGRATION_DIVERGENCES.md @@ -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. diff --git a/JAVA_MIGRATION_HANDOFF.md b/JAVA_MIGRATION_HANDOFF.md index 3c9a765..1a13588 100644 --- a/JAVA_MIGRATION_HANDOFF.md +++ b/JAVA_MIGRATION_HANDOFF.md @@ -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'"' '/ current = TRedstoneTileAccess.partList(this); + if (!(current instanceof scala.collection.immutable.List)) { + Iterator 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 parts = (scala.collection.immutable.List) current; + while (!parts.isEmpty()) { + TMultiPart part = parts.head(); + parts = (scala.collection.immutable.List) 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 current = TRedstoneTileAccess.partList(this); + if (!(current instanceof scala.collection.immutable.List)) { + Iterator iterator = current.iterator(); + while (iterator.hasNext()) { + result |= RedstoneInteractions.connectionMask(iterator.next(), side) & openMask; + } + return result; + } + + scala.collection.immutable.List parts = (scala.collection.immutable.List) current; + while (!parts.isEmpty()) { + TMultiPart part = parts.head(); + parts = (scala.collection.immutable.List) 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 current = TRedstoneTileAccess.partList(this); + if (!(current instanceof scala.collection.immutable.List)) { + Iterator 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 parts = (scala.collection.immutable.List) current; + while (!parts.isEmpty()) { + TMultiPart part = parts.head(); + parts = (scala.collection.immutable.List) 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 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); + } +} diff --git a/src/main/scala/codechicken/multipart/scalatraits/TRedstoneTile.scala b/src/main/scala/codechicken/multipart/scalatraits/TRedstoneTile.scala deleted file mode 100644 index 32eff13..0000000 --- a/src/main/scala/codechicken/multipart/scalatraits/TRedstoneTile.scala +++ /dev/null @@ -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 - } -}