From e1f58936071cbe25e9ac0d8ab9a6f9f3dab8472d Mon Sep 17 00:00:00 2001 From: Algent Date: Sat, 5 Sep 2026 00:21:08 +0200 Subject: [PATCH] feat: add Java tile loading APIs --- JAVA_MIGRATION.md | 12 ++- JAVA_MIGRATION_ABI_INVENTORY.md | 7 +- JAVA_MIGRATION_CONSUMER_AUDIT.md | 18 +++- JAVA_MIGRATION_HANDOFF.md | 43 ++++---- README.md | 6 +- docs/API.md | 62 ++++++++++++ docs/api/MATERIAL_ENUMERATION.md | 2 + docs/api/PART_LOADING.md | 99 +++++++++++++++++++ docs/api/PART_TRAVERSAL.md | 6 +- docs/migration/HISTORY.md | 21 ++++ .../TileMultipartClientFunctionalTest.java | 17 ++++ .../TileMultipartLifecycleFunctionalTest.java | 13 +++ .../codechicken/multipart/TileMultipart.java | 50 ++++++++++ .../multipart/TileMultipartLoadingTest.java | 90 +++++++++++++++++ .../examples/PartLoadingExample.java | 26 +++++ 15 files changed, 435 insertions(+), 37 deletions(-) create mode 100644 docs/API.md create mode 100644 docs/api/PART_LOADING.md create mode 100644 src/test/java/codechicken/multipart/examples/PartLoadingExample.java diff --git a/JAVA_MIGRATION.md b/JAVA_MIGRATION.md index f37e53a..adfcead 100644 --- a/JAVA_MIGRATION.md +++ b/JAVA_MIGRATION.md @@ -527,13 +527,13 @@ Each row keeps its existing descriptor for binary compatibility and gains a Java | Deprecate | Java-shaped replacement | Notes | | --- | --- | --- | -| `TileMultipart.partList(): scala.collection.Seq` | `jPartList(): java.util.List` | Getter deprecated; captured-sequence view documented in the [guide and compiling example](docs/api/PART_TRAVERSAL.md). Setter/loading migrations remain separate | +| `TileMultipart.partList(): scala.collection.Seq` | `jPartList(): java.util.List` | Getter deprecated; captured-sequence view documented in the [guide and compiling example](docs/api/PART_TRAVERSAL.md) | | `MultiPartRegistry.registerParts(IPartFactory2, scala.collection.Seq)` | `registerParts(IPartFactory2, String...)` | Sibling already exists | | `MicroMaterialRegistry.getIdMap(): scala.Tuple2[]` | `materialCount(): int` plus existing `materialName(int)` and `getMaterial(int)` | Implemented with static/companion deprecation; [guide and compiling example](docs/api/MATERIAL_ENUMERATION.md). Consumer release/adoption remains pending | | `TileMultipart.operate(scala.Function1)` | `forEachPart(java.util.function.Consumer)` | Implemented through the legacy virtual hook; preserves captured traversal, detached-part filtering and callback failures. Lifecycle still calls `operate` | | `TileMultipart.occlusionTest(scala.collection.Seq, TMultiPart)` | `occlusionTest(Collection, TMultiPart)` | | -| `TileMultipart.loadParts(scala.collection.Iterable)` | `loadParts(Collection)` | Schematica and GuideNH reflect the Scala descriptor; see Phase 10 | -| `TileMultipart.partList_$eq(scala.collection.Seq)` | `setPartList(List)` | GuideNH reflects the `_$eq` name; see Phase 10 | +| `TileMultipart.loadParts(scala.collection.Iterable)` | `loadPartList(Collection)` | Implemented through the legacy virtual hook; binding, world notifications, input iteration and partial failure retained. [Loading guide](docs/api/PART_LOADING.md) | +| `TileMultipart.partList_$eq(scala.collection.Seq)` | `setPartList(List)` | Implemented through the legacy setter; Java list copied without binding, null sentinel supported. GuideNH's old reflective name remains supported | | `TileMultipart.renderID()` / `renderID_$eq(int)` | `getRenderID()` / `setRenderID(int)` | | | `TileMultipart.getOrConvertTile2(): scala.Tuple2` | Small immutable result type with named accessors | No consumer in the audited set calls this | @@ -547,6 +547,12 @@ same-name overload there invites a silent wrong-overload bind. - [x] Add and document `materialCount()` with existing indexed lookups; retain and deprecate both `getIdMap()` entries. - [x] Document `jPartList()` and add `forEachPart(Consumer)`; deprecate the legacy getter/callback entries while retaining their override dispatch. JVM and generated-tile Forge cases cover the [documented contract](docs/api/PART_TRAVERSAL.md). +- [x] Add Java loading and storage assignment, with legacy override/reflection coverage, explicit ownership and + lifecycle contracts, and generated server/client tile checks; [guide](docs/api/PART_LOADING.md), [API index](docs/API.md). +- [ ] For remaining siblings, compile external Java examples with Scala excluded from the compile classpath before + finalizing names. The proposed `loadParts(Collection)` overload required `scala.collection.Iterable` during javac + overload resolution; the implemented `loadPartList(Collection)` avoids that dependency. Apply this gate to the + remaining occlusion and registration overloads as well as checking the emitted consumer bytecode. - [ ] Mark all nine rows `@Deprecated` with javadoc naming the replacement. - [ ] Confirm every original descriptor still exists in the ABI fixture after the change. - [ ] Document the supported API with compiling usage examples and an old-to-new migration guide. Validate Java diff --git a/JAVA_MIGRATION_ABI_INVENTORY.md b/JAVA_MIGRATION_ABI_INVENTORY.md index bcf61ff..a4c5dcc 100644 --- a/JAVA_MIGRATION_ABI_INVENTORY.md +++ b/JAVA_MIGRATION_ABI_INVENTORY.md @@ -199,9 +199,10 @@ Types used only for `isInstanceOf`: `BlockMultipart`, `TileMultipart`, `TileMult companion and pins `MicroblockClass`'s fully qualified name. Widening a parameter or renaming the class breaks the lookup even though every call site still links. -3. **`TileMultipart.partList_$eq(scala.collection.Seq)` is reflectively load-bearing.** It is a Scala `var` setter with - no Java-facing equivalent, so a Java-first port that drops it in favour of a list mutator would break guidenh - invisibly. The current port keeps it, verified by `javap`. `resolvePartList` also falls back to a public *field* +3. **`TileMultipart.partList_$eq(scala.collection.Seq)` is reflectively load-bearing.** The branch now supplies + `setPartList(java.util.List)` and `loadPartList(java.util.Collection)`, while retaining the exact legacy setter and + loader descriptors and override dispatch. Dropping the old setter in favor of the Java method would still break + guidenh invisibly. Exact and assignability-based reflective tests cover both legacy contracts. `resolvePartList` also falls back to a public *field* named `partList`, which never existed — Scala emits the field private — so that path is dead in the reference too. `MultipartHelper$` is retained on the strength of the fallback path alone: the static is found first today, so the diff --git a/JAVA_MIGRATION_CONSUMER_AUDIT.md b/JAVA_MIGRATION_CONSUMER_AUDIT.md index 2f17c1c..9324d8a 100644 --- a/JAVA_MIGRATION_CONSUMER_AUDIT.md +++ b/JAVA_MIGRATION_CONSUMER_AUDIT.md @@ -491,10 +491,9 @@ behavior: ## Java API adoption ledger This ledger tracks migration of a specific legacy contract, not completion of an entire consumer's migration. -Material enumeration and tile collection/traversal access are implemented on `algent/java`, with -[material](docs/api/MATERIAL_ENUMERATION.md) and [part traversal](docs/api/PART_TRAVERSAL.md) guides and compiling Java -examples. Neither addition is yet tied to a released minimum dependency version. Unlisted contracts remain governed -by the inventories above. +Material enumeration, tile collection/traversal access and tile loading/storage assignment are implemented on +`algent/java`. The [API index](docs/API.md) links the guides and compiling Java examples. These additions are not yet +tied to a released minimum dependency version. Unlisted contracts remain governed by the inventories above. | Legacy contract | Consumer and inspected source | Supported replacement | Consumer migration/release | Target-pack adoption and removal gate | | --- | --- | --- | --- | --- | @@ -504,7 +503,8 @@ by the inventories above. | `TileMultipart.partList(): scala.collection.Seq` | OpenComputers `2c00f79be24b`: cable/print/network searches and aggregation | `jPartList()` with the same search/aggregation semantics | Source patch and release pending | No migrated pack version verified; retain the getter | | `TileMultipart.partList(): scala.collection.Seq` | AE2 `87f2b3817c2a`: `FMPPlacementHelper.getPart` and `removePart` | Iterate `jPartList()`; retain last-match lookup and removal/break behavior | Source patch and release pending | No migrated pack version verified; retain the getter | | `TileMultipart.partList(): scala.collection.Seq` | Extra Utilities 1.2.12: multipart renderer iterators | Iterate `jPartList()` without adding detached-part filtering | Retirement/replacement pending | Confirm absence or migration in the target pack before retiring the getter | -| `TileMultipart.partList(): scala.collection.Seq` plus reflective getter/setter/loading | GuideNH `7d8fb44e77b9`: `Ae2ForgeMultipartBridge`, `ForgeMultipartHelpers` | `jPartList()` for reads; Java setter/loading replacements still pending | Read migration alone does not migrate client-tile reconstruction | Retain `partList`, `partList_$eq` and `loadParts` until their separate gates pass | +| `TileMultipart.partList(): scala.collection.Seq` plus reflective getter/setter/loading | GuideNH `7d8fb44e77b9`: `Ae2ForgeMultipartBridge`, `ForgeMultipartHelpers` | `jPartList()` for reads, `setPartList(List)` for staging, `loadPartList(Collection)` for binding/cache reconstruction | Source patch and release pending; preserve world/position setup and following tile/render notifications | Retain the legacy getter/setter/loader until adoption; companion-only generator migration is separate | +| `TileMultipart.loadParts(scala.collection.Iterable)` exact reflection | Schematica `3b03ee937953`: `nbt.ForgeMultipart` | Reflect `loadPartList(Collection.class)` and pass its existing Java part list directly | Source patch and release pending; registry map and generator reflection remain separate contracts | No migrated pack version verified; retain the Scala loader descriptor | Evidence for the FMP addition is under ignored `run/migration-material-enumeration-reference/`. The original reference-compiled Scala consumer still exercises the companion and tuple-array descriptor. The new compiling Java @@ -531,6 +531,14 @@ reference the exact same 35 inherited types, 255 members, 76 other types and 20 `+678` inventory, compared by full row rather than counts alone. The report is archived with the traversal evidence; source revisions above remain the inspected checkout revisions, not a claim of source parity with every newer jar. +Loading/storage evidence is under ignored `run/migration-part-loading-reference/`. The supplied source search found +no FMP loader/setter overrides or `setPartList`/`loadPartList` name collisions; GuideNH's assignability-based selection and Schematica's +exact Scala-parameter lookup remain pinned. The Java setter copies non-null list storage while the old setter retains +its exact sequence; neither binds parts. The loader retains callback order, client/server branching and partial +failure behavior. All 546 pre-change compiled JVM tests pass with their recorded version; generated tile checks cover +server slot rebuilding/notifications and client storage/loading/render-cache queries. Actual client preview rendering, +consumer release and pack adoption are still separate gates. + ## Practical priority for the current branch 1. Keep the existing `+678` ABI fixture as the exact binary floor and correct failures before source cleanup. diff --git a/JAVA_MIGRATION_HANDOFF.md b/JAVA_MIGRATION_HANDOFF.md index 79f5543..ff590ef 100644 --- a/JAVA_MIGRATION_HANDOFF.md +++ b/JAVA_MIGRATION_HANDOFF.md @@ -7,6 +7,7 @@ migration checkout; `codex/tile-compatibility-fixes` was deleted after its fixes | Document | Purpose | | --- | --- | | [Plan](JAVA_MIGRATION.md) | Phase gates, API policy and upstream cleanup | +| [Java API index](docs/API.md) | Consumer entry points, guides, compiling examples and remaining API gaps | | [ABI inventory](JAVA_MIGRATION_ABI_INVENTORY.md) | Shipping binary names/descriptors and reflective constraints | | [Consumer audit](JAVA_MIGRATION_CONSUMER_AUDIT.md) | Runtime behavior, data/lifecycle contracts and consumer source | | [Divergences](JAVA_MIGRATION_DIVERGENCES.md) | Intentional effective compatibility differences | @@ -16,7 +17,7 @@ migration checkout; `codex/tile-compatibility-fixes` was deleted after its fixes ## Current state and next target -**542 plain-JVM tests and 239 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **224 Java +**549 plain-JVM tests and 242 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **224 Java files and 9 Scala files / 747 nonblank Scala lines**. The packaged inventory has 443 classes. Review follow-up: restored packet-scheduler callback mutation behavior with the original Scala hash-map traversal, @@ -31,32 +32,34 @@ use, but no override triggering these three regressions was found. All 443 class payloads and 116 generated dumps are retained. The agreed next milestone is the documented consumer-facing Java API, followed by consumer release/adoption and final Scala removal; see the plan's API migration design and Phases 8–10. -Latest API addition: `TileMultipart.forEachPart(Consumer)` reuses the existing adapter and virtual `operate` hook. -`jPartList()` now documents its captured-sequence view. Both legacy getter/callback entries are deprecated while -retaining their descriptors and bodies. Three baseline tests were committed first as `5c1e760`; four further JVM cases, -a compiling Java example and one Forge generated-tile case cover the new API. All 538 pre-change compiled tests pass -with their recorded version. The 443 class APIs retain all existing members, with one method added; 17 ScalaSignature -payloads, 3,747 existing method bodies and 116 generated dumps are unchanged apart from expected deprecation metadata -and build-version literals. Evidence: `run/migration-part-traversal-reference/`. +Latest API addition: `TileMultipart.setPartList(List)` copies Java list storage through the legacy setter, and +`loadPartList(Collection)` delegates through the legacy Scala loader. Storage assignment and binding/cache rebuilding +have separate documented contracts. Both old entries are deprecated while retaining their descriptors and bodies. +Four JVM and one Forge baseline cases were committed first as `92273bd`; three further JVM cases, a Java example +and two Forge cases cover the new methods on generated server/client tiles. All 546 pre-change compiled JVM tests +pass with their recorded version. The 443 class APIs retain all existing members, with two methods added; 17 +ScalaSignature payloads, 3,748 existing method bodies and 116 generated dumps are unchanged apart from expected +deprecation metadata and build-version literals. Evidence: `run/migration-part-loading-reference/`. -The [part traversal guide](docs/api/PART_TRAVERSAL.md) covers ownership, callback mutation/reentrancy, failure timing, -detached/rebound parts and override dispatch. Lifecycle still uses `operate`; overriding `forEachPart` alone does not -intercept lifecycle callbacks. The adoption ledger names five legacy-getter consumers and the remaining GuideNH -setter/loading gap. The installed `+719` pack rescan matches every member/type/reflection row in the `+678` floor: -27 consumers, 35 inherited types, 255 members, 76 other types and 20 strings. Consumer releases/adoption remain pending. +Naming correction: the planned `loadParts(Collection)` overload made javac require `scala.collection.Iterable` even +for Java arguments. The distinct `loadPartList` name allows compilation without Scala on the example's classpath. +Keep this compilation gate for remaining occlusion/registration APIs; checking only imports or bytecode is insufficient. +Internal storage writes and reconstruction still dispatch through the old setter/loader hooks, not the Java siblings. -`MicroMaterialRegistry.materialCount()` and its indexed lookups are also complete, with both `getIdMap()` entries -deprecated; see the [material enumeration guide](docs/api/MATERIAL_ENUMERATION.md) and previous history entry. -The supplied consumer checkouts remain reference-only. +The [API index](docs/API.md) now orients consumers to entry points, compiling examples and migration status. Material +enumeration and tile read/traversal access are also complete; use their guides rather than treating them as missing +APIs. GuideNH and Schematica have Java loading replacements, but their source changes, other reflection/extension +contracts, releases and pack adoption remain pending. The supplied checkouts remain reference-only. The installed +`+719` pack scan retains the `+678` floor: 27 consumers, 35 inherited types, 255 members, 76 other types and 20 strings. **Next priority: close the Java API gaps in Phases 2 and 9 and map consumer migrations in Phase 10.** Reuse the existing Java surface; supply missing capabilities, precise contracts, migration guidance and compiling examples. Cover subclass/override behavior and generated extensions as well as ordinary calls. ProjectRed's illuminated microblocks are the representative external extension case. Consumer mods may remain Scala internally while adopting this API. -The next bounded API candidate is Java tile loading/state access: `loadParts(Collection)` and -`setPartList(List)`, with distinct binding/lifecycle contracts and preserved legacy setter/loading dispatch. -GuideNH's client-tile reconstruction makes the old descriptors load-bearing. Do not repeat material enumeration or -tile read/traversal access as unimplemented gaps, or treat FMP-side completion as consumer adoption. +The next bounded API candidate is Java collection-based occlusion testing. Verify legacy override dispatch, both +directions of occlusion checks, ordering/failures, and compilation without Scala before choosing the Java entry name. +The tentative same-name overload may have the same compiler constraint as loading. Registry registration guidance +and bridges remain another pending API slice. FMP-side completion does not establish consumer adoption. Pause mechanical extraction of retained Scala shells unless it enables that API, fixes a demonstrated issue or has a measured benefit. `ScalaSignature.ClassSymbolRef.info` remains an optional bounded extraction, not the default next diff --git a/README.md b/README.md index dda12df..12aaa8b 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,5 @@ If you only want to use the API and not modify it: Implementation of all parts of the API should be clean and easy in Java. The minecraft multipart mod is implemented in java as a test case. -Java API migration guides: - -* [Enumerating microblock materials](docs/api/MATERIAL_ENUMERATION.md), including a compiling example and legacy API replacements. -* [Reading and visiting multipart parts](docs/api/PART_TRAVERSAL.md), including collection ownership, callback behavior and legacy overrides. +See the [Java API index](docs/API.md) for supported entry points, compiling examples, ownership/lifecycle contracts +and migration status. It links to the material enumeration, part traversal and tile loading guides. diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..eaaa485 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,62 @@ +# ForgeMultipart Java API + +Start here when integrating with ForgeMultipart for **Minecraft 1.7.10 / Forge**. This describes the `algent/java` +migration branch. Its new APIs are implemented and tested but do not yet have a minimum published dependency version. +Use a dev artifact containing the methods you need; source Javadocs are packaged with the sources artifact. + +Consumers can use the Java surface without importing Scala types. FMP still retains Scala storage, runtime and +compatibility bridges, and some extension contracts still need migration. A Scala-authored mod can adopt the Java API +without converting the rest of its code to Java. + +## Choose a guide + +| Task | API and guide | +| --- | --- | +| Enumerate microblock materials by numeric ID | `materialCount()`, `materialName(int)`, `getMaterial(int)` — [material enumeration](api/MATERIAL_ENUMERATION.md) | +| Read/index/search a tile's parts | `jPartList()` — [part collection ownership and order](api/PART_TRAVERSAL.md#collection-ownership-and-ordering) | +| Run callbacks while skipping detached parts | `forEachPart(Consumer)` — [callback and override behavior](api/PART_TRAVERSAL.md#callback-behavior) | +| Rebuild parts on an already prepared composite tile | `loadPartList(Collection)` — [part loading](api/PART_LOADING.md) | +| Assign stored parts during reconstruction, without binding or notifications | `setPartList(List)` — [storage assignment](api/PART_LOADING.md#storage-assignment) | + +Each guide explains ownership, lifecycle, legacy replacements and limitations, and links to a compiling Java example +exercised by the test suite. The loading/setter APIs are advanced reconstruction operations; ordinary placement and +removal should use the existing world APIs below. + +## Existing Java entry points + +These entry points already exist. The links lead to their source/Javadocs; detailed migration guides and checks for +compilation without Scala are still pending in these areas. A Java-typed overload can still require Scala on the +compile classpath for overload resolution, as the [loading guide](api/PART_LOADING.md#overrides-and-reflection) explains. + +| Area | Starting points | +| --- | --- | +| Define a custom part | Extend [TMultiPart](../src/main/scala/codechicken/multipart/TMultiPart.java); implement the required capability interfaces. The [built-in parts](../src/main/scala/codechicken/multipart/minecraft) show Java implementations | +| Register part factories and block converters | [MultiPartRegistry](../src/main/scala/codechicken/multipart/MultiPartRegistry.java): `registerParts(IPartFactory, String...)`, `registerParts(IPartFactory2, String...)`, `registerConverter(IPartConverter)` | +| Find, place and remove parts | [TileMultipart](../src/main/scala/codechicken/multipart/TileMultipart.java): `getTile`, `canPlacePart`, `addPart`, `remPart`. Retain the tile returned by changes because generated capabilities can replace the instance | +| Construct a server composite tile from parts, or restore saved multipart NBT | [MultipartHelper](../src/main/scala/codechicken/multipart/MultipartHelper.java): `createTileFromParts(Iterable)`, `createTileFromNBT(World, NBTTagCompound)` | +| Register microblock materials | [MicroMaterialRegistry](../src/main/scala/codechicken/microblock/MicroMaterialRegistry.java) and [BlockMicroMaterial](../src/main/scala/codechicken/microblock/BlockMicroMaterial.java) | +| Register generated tile traits or pass-through interfaces | [MultipartGenerator](../src/main/scala/codechicken/multipart/MultipartGenerator.java); see the [extension constraints](../JAVA_MIGRATION_HANDOFF.md#retained-compiler-constraints) before migrating custom traits | + +New API examples use Java 8 language/library features. The source path `src/main/scala` also contains Java classes +because of the current joint-compilation layout; it does not imply that those APIs require Scala source in a consumer. + +## Compatibility and remaining work + +Deprecated Scala-facing entry points remain callable, with their descriptors and supported override dispatch retained. +Follow the method-specific guide: a Java sibling is not automatically a replacement override hook, and reflection +must select the intended parameter types when a method is overloaded. + +Java collection occlusion access, remaining registry bridges/documentation, generator/reflection replacements and +complete external microblock extension guidance are still pending. In particular, ProjectRed's Scala microblock traits +remain a supported dependency; registration signatures alone do not prove a complete Java replacement. + +FMP-side implementation is separate from consumer releases and target-pack adoption. Retiring legacy bridges or the +Scala dependency requires those gates and removal of FMP's remaining internal Scala users. + +| Need | Document | +| --- | --- | +| What is complete and what comes next? | [Working handoff](../JAVA_MIGRATION_HANDOFF.md), [migration plan](../JAVA_MIGRATION.md) | +| Which consumers need changes, releases and pack adoption? | [Consumer adoption ledger](../JAVA_MIGRATION_CONSUMER_AUDIT.md#java-api-adoption-ledger) | +| Which binary names, reflective lookups and runtime contracts must survive? | [ABI inventory](../JAVA_MIGRATION_ABI_INVENTORY.md), [source consumer audit](../JAVA_MIGRATION_CONSUMER_AUDIT.md) | +| What has been tested and what still needs a client/pack run? | [Migration history](migration/HISTORY.md), [manual release checks](../JAVA_MIGRATION_MANUAL_CHECKS.md) | +| Why is some Scala or older Java syntax retained? | [Modern Java policy](../JAVA_MIGRATION.md#modern-java-readability-policy), [compiler/toolchain handoff](../JVM_DOWNGRADER_HANDOFF.md) | diff --git a/docs/api/MATERIAL_ENUMERATION.md b/docs/api/MATERIAL_ENUMERATION.md index 431f6c6..3dd315e 100644 --- a/docs/api/MATERIAL_ENUMERATION.md +++ b/docs/api/MATERIAL_ENUMERATION.md @@ -1,5 +1,7 @@ # Enumerating microblock materials from Java +[API index](../API.md) + The `algent/java` branch adds `MicroMaterialRegistry.materialCount()`. Use it with the existing `materialName(int)` and `getMaterial(int)` methods to enumerate materials without importing Scala types. This API is not yet tied to a published release; consumers must require an FMP version containing the addition. diff --git a/docs/api/PART_LOADING.md b/docs/api/PART_LOADING.md new file mode 100644 index 0000000..54a0909 --- /dev/null +++ b/docs/api/PART_LOADING.md @@ -0,0 +1,99 @@ +# Loading and assigning multipart parts from Java + +[API index](../API.md) + +The `algent/java` branch adds `TileMultipart.loadPartList(Collection)` and `setPartList(List)`. +They adapt to the existing virtual Scala-parameter hooks. Both legacy entries are deprecated for callers and remain +supported for existing binaries, subclasses and reflection. No minimum released dependency version is established yet. + +These are reconstruction operations, not normal placement/removal. Use `TileMultipart.addPart` / `remPart` for world +changes. Use `MultipartHelper.createTileFromParts(Iterable)` to construct a new server composite tile; the +loader itself does not choose traits, promote a tile or install it in the world. + +## Loading a prepared tile + +To rebuild a tile using its existing parts, capture them before the loader clears the tile: + +```java +public static void reloadParts(TileMultipart tile) { + List parts = new ArrayList<>(tile.jPartList()); + tile.loadPartList(parts); +} +``` + +For a supplied collection, call `preparedTile.loadPartList(parts)`. The tile must already have all capabilities required +by those parts. An arbitrary `new TileMultipart()` does not acquire slot, inventory or other generated traits by loading. + +The default implementation: + +1. Calls the virtual `clearParts()` hook to clear stored parts and trait caches that implement that hook. +2. Reads the supplied collection in its iteration order. For each part, appends it to stored state, calls `bindPart`, + then `part.bind(tile)`, and enables ticking if needed. It retains the existing 250-part limit. +3. With a client world, visits bound parts through the legacy `operate` hook to call `onWorldJoin`. +4. With either kind of world, calls `notifyPartChange(null)`, which notifies parts, marks the block for update, + notifies neighboring blocks and recalculates lighting. Without a world, neither world step runs. + +Loading does not call `onAdded`, call old parts' removal/separation callbacks, unbind old parts, reset an already-set +ticking flag, check occlusion/duplicates, or send a complete multipart description packet. It is not a general live-tile +replacement transaction. Reconstruction callers remain responsible for their world/position setup, render updates, +tile notifications and any full description synchronization required by their existing flow. + +The Java collection is viewed during the call, not copied first. Its iterator determines the order and mutation +behavior; do not structurally modify it from callbacks. Replacing a pending list entry during a binding callback can +change which part is loaded next. After successful loading, normal stored sequence snapshots no longer track later +edits to the input collection. Part objects remain shared. + +Call on the game thread. Failures propagate without rollback: clearing happens before iteration, and each part is +published before binding. A null collection fails after clearing; a null part can remain in partially loaded storage +before binding fails. A callback exception likewise leaves changes already performed. Supply valid parts rather than +using these failures to validate a proposed live-world change. + +## Storage assignment + +`preparedTile.setPartList(parts)` takes a shallow immutable copy of a non-null Java list, then passes that sequence to +the virtual legacy setter. It preserves order, duplicates, null entries and object identities. Editing the original +list later does not alter the stored sequence; parts themselves are not copied. + +The setter performs storage assignment only. It does not bind parts, rebuild slot/inventory/render caches, update +ticking, validate parts or notify anything. Existing legacy setter overrides can customize that behavior. Use it only +where a reconstruction flow specifically needs to stage stored state before its separate loading/binding step. + +A null list preserves the legacy unset-state sentinel. The generated client render-cache code handles that sentinel; +most ordinary part queries do not. Use an empty list for ordinary empty storage. The old Scala setter still retains +the exact supplied sequence, including mutable aliasing; the new Java setter deliberately copies a non-null list. + +Both operations appear in the [compiling Java example](../../src/test/java/codechicken/multipart/examples/PartLoadingExample.java). +The example runs in the normal test suite and uses no Scala imports. Its staging method illustrates assignment only, +not a complete tile-promotion procedure. + +## Overrides and reflection + +Dispatch is `setPartList(List)` → virtual `partList_$eq(Seq)` and `loadPartList(Collection)` → virtual +`loadParts(scala.collection.Iterable)`. Internal reconstruction and storage writes continue using the legacy hooks. +Keep existing overrides there; overriding just the new Java sibling does not intercept all internal calls. + +GuideNH's existing assignability-based reflection still selects the Scala loader for a Scala sequence. Schematica's +exact `loadParts(scala.collection.Iterable)` lookup also remains valid. Java reflection can now request +`getMethod("setPartList", List.class)` or `getMethod("loadPartList", Collection.class)`. Select by parameter type, not +by the first method with the right name. + +The Java loader has a distinct name deliberately: the initially planned `loadParts(Collection)` overload made +`javac --release 8` require `scala.collection.Iterable` during overload resolution even with a Java list argument. +`loadPartList` lets the example compile without Scala on the consumer compile classpath, while retaining the legacy +hook and its name. This changes the planned Java name, not any existing entry point. + +For GuideNH's migration, use a Java list of the promoted client parts, retain its existing world/position setup, +replace the raw setter with `setPartList`, and call the Collection loader. Preserve its following `notifyTileChange` +and `markRender` steps. This does not replace its companion-only generator or other reflective dependencies. +Schematica can select the Collection loader and pass its existing Java list directly; its Scala map and generator +reflection need separate migration. + +## Validation and release gates + +JVM tests pin storage ownership, old and new override dispatch, exact/assignable reflection, ordered non-list inputs, +callback input mutation and partial-failure behavior. Forge tests cover slot-cache rebuilding and server notifications, +plus Java assignment/loading on a generated client tile and explicit render-cache rebuilding. The latter does not run +a real client world or GPU rendering; GuideNH/Schematica previews and full-pack adoption remain manual release gates. + +The [consumer ledger](../../JAVA_MIGRATION_CONSUMER_AUDIT.md#java-api-adoption-ledger) records the inspected source +revisions and pending consumer changes/releases. The supplied reference checkouts are unchanged. diff --git a/docs/api/PART_TRAVERSAL.md b/docs/api/PART_TRAVERSAL.md index 2f72e1c..fa1b9dc 100644 --- a/docs/api/PART_TRAVERSAL.md +++ b/docs/api/PART_TRAVERSAL.md @@ -1,5 +1,7 @@ # Reading and visiting multipart parts from Java +[API index](../API.md) + Use `TileMultipart.jPartList()` for ordered collection access. The `algent/java` branch also adds `forEachPart(Consumer)` for callbacks that skip detached parts. Consumers using the new method must require an FMP release containing it; no minimum released version is established yet. Both methods work on generated tiles. @@ -92,8 +94,8 @@ must retain their original order, filters and aggregation. Those mods can remain collection methods. Existing Java consumers already using `jPartList()` need no rename. GuideNH also reflects `partList`, `partList_$eq` and `loadParts` while reconstructing client tiles. Moving read-only -uses to the Java getter does not migrate its setter/loading contracts. Their Java replacements and the consumer patch, -release and pack adoption remain separate work. No reference checkout was edited. +uses to the Java getter does not migrate its setter/loading contracts. Their [Java replacements](PART_LOADING.md) +are implemented; the consumer patch, release and pack adoption remain separate work. No reference checkout was edited. The [adoption ledger](../../JAVA_MIGRATION_CONSUMER_AUDIT.md#java-api-adoption-ledger) records inspected revisions and the remaining release gates. JVM checks cover both getter forms, mutable storage, callback mutation/reentrancy, diff --git a/docs/migration/HISTORY.md b/docs/migration/HISTORY.md index 4e59669..19d51ff 100644 --- a/docs/migration/HISTORY.md +++ b/docs/migration/HISTORY.md @@ -1763,3 +1763,24 @@ differences belong in the [divergence ledger](../../JAVA_MIGRATION_DIVERGENCES.m - Rescanned the installed GTNH daily `2026-09-04+719`: 241 jars scanned, one FMP jar excluded, 27 consumers. All 386 member/type/reflection rows match the frozen `+678` inventory; consumer version changes do not permit bridge removal. Reference checkouts were not modified. Evidence: `run/migration-part-traversal-reference/`. + +### 2026-09-05 — Java tile loading/state API and documentation index + +- Committed four JVM and one Forge baseline cases first as `92273bd`. They pin storage aliasing/null state, binding + and cache-hook order, stale ticking/old bindings, partial failures, exact/assignable reflection and generated slots. + Saved the pre-API jar, source, reports, 116 generated dumps and all 546 compiled JVM tests before implementation. +- Added `setPartList(List)` through the old setter and `loadPartList(Collection)` through + the old loader. The Java setter copies non-null list storage and retains the null sentinel; loading retains the + input's iteration behavior, callback order and partial failures. Old hooks/descriptors remain supported and deprecated. +- Changed the planned loader name after the `loadParts(Collection)` trial made javac require Scala's `Iterable` + during overload resolution with a Java list. The distinct `loadPartList` entry lets the example compile without + Scala on its classpath. Added this compile check to the remaining API gates; no existing method was renamed. +- Added three JVM cases, a compiling Java example and two Forge cases for server slots/notifications and generated + client storage/loading/render-cache queries. Normal/clean build/style checks pass with 549 JVM and 242 Java 8 Forge + tests; all 546 frozen pre-change JVM tests also pass. Real client-world/GPU preview checks remain manual. +- All 443 class APIs retain their existing members, with exactly two new public instance methods and two deprecations. + All 17 ScalaSignature payloads, 3,748 existing method bodies and 116 generated dumps remain unchanged, allowing only + the expected deprecation metadata and build-version literals. No production class or dependency is added. +- Added `docs/API.md` as the consumer entry point, a loading/storage guide, compiling examples, and reciprocal guide + links. Updated the plan, ABI notes and GuideNH/Schematica adoption ledger; reference checkouts remain unchanged and + consumer releases/pack adoption are pending. Evidence: `run/migration-part-loading-reference/`. diff --git a/src/functionalTest/java/codechicken/multipart/test/TileMultipartClientFunctionalTest.java b/src/functionalTest/java/codechicken/multipart/test/TileMultipartClientFunctionalTest.java index bb4cd05..2132aff 100644 --- a/src/functionalTest/java/codechicken/multipart/test/TileMultipartClientFunctionalTest.java +++ b/src/functionalTest/java/codechicken/multipart/test/TileMultipartClientFunctionalTest.java @@ -76,6 +76,23 @@ class TileMultipartClientFunctionalTest { assertBounds(cachedBounds(client), -3.0, 7.0, 11.0, -2.0, 8.0, 12.0); } + @Test + void javaStorageAndLoadingWorkOnTheGeneratedClientTile() throws Exception { + TileMultipart tile = newClientTile(); + TileMultipartClient client = (TileMultipartClient) tile; + tile.setPartList(null); + invokeUpdateRenderCache(client); + assertEquals(0, staticCache(client).length); + RenderPart part = new RenderPart("loaded", false, false, Cuboid6.full); + tile.setPartList(Arrays.asList(part)); + assertNull(part.tile(), "Storage assignment does not bind client parts"); + tile.loadPartList(tile.jPartList()); + assertSame(tile, part.tile()); + invokeUpdateRenderCache(client); + assertArrayEquals(new TMultiPart[] { part }, staticCache(client)); + assertEquals(0, dynamicCache(client).length); + } + @Test void emptyPartsUseFullLocalBoundsAndLazyQueriesPopulateBothCaches() throws Exception { TileMultipart tile = newClientTile(); diff --git a/src/functionalTest/java/codechicken/multipart/test/TileMultipartLifecycleFunctionalTest.java b/src/functionalTest/java/codechicken/multipart/test/TileMultipartLifecycleFunctionalTest.java index bb51636..7ee61f8 100644 --- a/src/functionalTest/java/codechicken/multipart/test/TileMultipartLifecycleFunctionalTest.java +++ b/src/functionalTest/java/codechicken/multipart/test/TileMultipartLifecycleFunctionalTest.java @@ -165,6 +165,19 @@ class TileMultipartLifecycleFunctionalTest { checkLoading((tile, parts) -> tile.loadParts(JavaConversions.asScalaBuffer(parts).toList())); } + @Test + void javaLoadingRebuildsGeneratedSlotsAfterStorageOnlyAssignment() { + checkLoading((tile, parts) -> { + TMultiPart old = tile.partMap(2); + tile.setPartList(parts); + assertSame(old, tile.partMap(2), "The setter must not rebuild trait caches"); + assertNull(tile.partMap(7)); + assertNull(parts.get(0).tile()); + assertEquals(parts, tile.jPartList()); + tile.loadPartList(tile.jPartList()); + }); + } + private static void checkLoading(BiConsumer> load) { World world = world(); clear(world, LOADING_POS); diff --git a/src/main/scala/codechicken/multipart/TileMultipart.java b/src/main/scala/codechicken/multipart/TileMultipart.java index 2bfe869..b65500b 100644 --- a/src/main/scala/codechicken/multipart/TileMultipart.java +++ b/src/main/scala/codechicken/multipart/TileMultipart.java @@ -53,10 +53,31 @@ public class TileMultipart extends TileEntity implements IChunkLoadTile { return partList; } + /** + * @deprecated Use {@link #setPartList(List)} for Java storage assignment. This legacy hook retains the exact + * supplied sequence, including mutable storage or null; existing overrides remain supported. + */ + @Deprecated public void partList_$eq(Seq parts) { partList = parts; } + /** + * Assigns a shallow, immutable copy of the supplied list through the legacy {@link #partList_$eq(Seq)} hook. + * Preserves order, duplicate entries and part identities. Later list edits do not affect the stored sequence. + * + *

+ * This is low-level storage assignment for reconstruction. It does not bind parts, rebuild trait caches, change + * ticking or send notifications. Use {@link #loadPartList(Collection)} to load a correctly prepared composite tile; + * use {@link #addPart(World, BlockCoord, TMultiPart)} / {@link #remPart(TMultiPart)} for normal world changes. + * Existing setter overrides can customize storage. Internal writes still call the legacy hook directly. + * + * @param parts list to copy; null preserves the legacy unset-state sentinel, and null entries are not validated + */ + public void setPartList(List parts) { + partList_$eq(parts == null ? null : toSeq(parts)); + } + public void from(TileMultipart that) { copyFrom(that); loadFrom(that); @@ -520,6 +541,35 @@ public class TileMultipart extends TileEntity implements IChunkLoadTile { /** Remove this part from internal cache. Provided for trait overrides, do not call externally. */ public void partRemoved(TMultiPart part, int p) {} + /** + * Loads parts into an already prepared composite tile through the legacy + * {@link #loadParts(scala.collection.Iterable)} hook. Clears trait caches, then stores and binds each input part in + * collection iteration order. The collection is viewed during the call, not copied in advance; do not structurally + * modify it from callbacks. + * + *

+ * With a world, the default hook calls {@code onWorldJoin} on the client and then + * {@link #notifyPartChange(TMultiPart)} with null on either side. Without a world it only loads/binds. It does not + * generate capabilities, remove/unbind old parts, call {@code onAdded}, reset the existing ticking flag or send a + * complete description packet. Use {@link MultipartHelper#createTileFromParts(Iterable)} when constructing a new + * server tile from parts. + * + *

+ * Call on the game thread. Loading is not atomic: failures propagate with cleared or partially loaded state. The + * default hook clears before reading the collection, so a null collection also fails after clearing. Existing + * legacy overrides still control loading; internal reconstruction continues to call that hook directly. + * + * @param parts parts to load; iteration order, duplicates and callback failure behavior are retained + */ + public void loadPartList(Collection parts) { + loadParts(JavaConversions.iterableAsScalaIterable(parts)); + } + + /** + * @deprecated Call {@link #loadPartList(Collection)} from Java. Retained for legacy overrides, compiled callers and + * exact Scala-parameter reflection; behavior is unchanged. + */ + @Deprecated public void loadParts(scala.collection.Iterable parts) { clearParts(); for (TMultiPart p : JavaConversions.asJavaIterable(parts)) { diff --git a/src/test/java/codechicken/multipart/TileMultipartLoadingTest.java b/src/test/java/codechicken/multipart/TileMultipartLoadingTest.java index edc234c..e9394bb 100644 --- a/src/test/java/codechicken/multipart/TileMultipartLoadingTest.java +++ b/src/test/java/codechicken/multipart/TileMultipartLoadingTest.java @@ -10,10 +10,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; import java.util.List; import org.junit.jupiter.api.Test; +import codechicken.multipart.examples.PartLoadingExample; import scala.collection.JavaConversions; import scala.collection.Seq; @@ -101,6 +105,92 @@ class TileMultipartLoadingTest { assertEquals(Arrays.asList(part), tile.jPartList()); } + @Test + void javaSetterCopiesInOrderAndRetainsTheLegacyOverrideAndNullState() { + List> writes = new ArrayList<>(); + TileMultipart tile = new TileMultipart() { + + @Override + public void partList_$eq(Seq parts) { + writes.add(parts); + super.partList_$eq(parts); + } + }; + Part part = new Part("part", new ArrayList<>()); + List input = new ArrayList<>(Arrays.asList(part, part, null)); + PartLoadingExample.stageParts(tile, input); + assertEquals(1, writes.size()); + assertSame(writes.get(0), tile.partList()); + assertEquals(input, tile.jPartList()); + input.clear(); + assertEquals(Arrays.asList(part, part, null), tile.jPartList()); + assertThrows(UnsupportedOperationException.class, () -> tile.jPartList().clear()); + assertNull(part.tile()); + assertFalse(tile.canUpdate()); + tile.setPartList(null); + assertNull(writes.get(1)); + assertNull(tile.partList()); + tile.setPartList(Collections.emptyList()); + assertEquals(3, writes.size()); + assertTrue(tile.jPartList().isEmpty()); + } + + @Test + void javaLoaderUsesTheLegacyOverrideWithAnOrderedNonListCollection() { + List> calls = new ArrayList<>(); + TileMultipart tile = new TileMultipart() { + + @Override + public void loadParts(scala.collection.Iterable parts) { + calls.add(parts); + super.loadParts(parts); + } + }; + List events = new ArrayList<>(); + Part first = new Part("first", events); + Part second = new Part("second", events); + Collection input = new LinkedHashSet<>(Arrays.asList(first, second)); + tile.loadPartList(input); + assertEquals(1, calls.size()); + assertEquals(Arrays.asList("bind:first", "bind:second"), events); + input.clear(); + assertEquals(Arrays.asList(first, second), tile.jPartList()); + assertSame(tile, first.tile()); + assertSame(tile, second.tile()); + PartLoadingExample.reloadParts(tile); + assertEquals(2, calls.size()); + assertEquals(Arrays.asList(first, second), tile.jPartList()); + } + + @Test + void javaLoaderReadsTheLiveInputAndKeepsFailureOrdering() { + TileMultipart tile = new TileMultipart(); + List input = new ArrayList<>(); + List events = new ArrayList<>(); + Part replaced = new Part("replaced", events); + Part replacement = new Part("replacement", events); + Part first = new Part("first", events) { + + @Override + public void bind(TileMultipart host) { + super.bind(host); + input.set(1, replacement); + } + }; + input.add(first); + input.add(replaced); + tile.loadPartList(input); + assertEquals(Arrays.asList(first, replacement), tile.jPartList()); + assertNull(replaced.tile()); + assertSame(tile, replacement.tile()); + assertThrows(NullPointerException.class, () -> tile.loadPartList((Collection) null)); + assertTrue(tile.jPartList().isEmpty()); + assertSame(tile, first.tile()); + assertThrows(NullPointerException.class, () -> tile.loadPartList(Arrays.asList(replacement, null, replaced))); + assertEquals(Arrays.asList(replacement, null), tile.jPartList()); + assertNull(replaced.tile()); + } + private static Seq seq(TMultiPart... parts) { return JavaConversions.asScalaBuffer(Arrays.asList(parts)).toList(); } diff --git a/src/test/java/codechicken/multipart/examples/PartLoadingExample.java b/src/test/java/codechicken/multipart/examples/PartLoadingExample.java new file mode 100644 index 0000000..339999e --- /dev/null +++ b/src/test/java/codechicken/multipart/examples/PartLoadingExample.java @@ -0,0 +1,26 @@ +package codechicken.multipart.examples; + +import java.util.ArrayList; +import java.util.List; + +import codechicken.multipart.TMultiPart; +import codechicken.multipart.TileMultipart; + +/** Compiling examples for docs/api/PART_LOADING.md; these are reconstruction operations, not placement/removal. */ +public final class PartLoadingExample { + + private PartLoadingExample() {} + + /** Captures the existing parts before clearing/rebuilding the prepared tile's caches and bindings. */ + public static void reloadParts(TileMultipart tile) { + List parts = new ArrayList<>(tile.jPartList()); + tile.loadPartList(parts); + } + + /** + * Stages a copy of the list only; bindings, ticking, caches and notifications remain the caller's responsibility. + */ + public static void stageParts(TileMultipart tile, List parts) { + tile.setPartList(parts); + } +}