diff --git a/JAVA_MIGRATION.md b/JAVA_MIGRATION.md index ee523f4..c4b7553 100644 --- a/JAVA_MIGRATION.md +++ b/JAVA_MIGRATION.md @@ -64,7 +64,7 @@ The phase checklists include recurring verification rules, historical work and c | Workstream | Remaining deliverables | Gate | | --- | --- | --- | -| Complete the supported Java surface | Physical-client validation of the documented illuminated microblock example; converter and broader extension/lifecycle guidance; safe Java compilation guidance for transformed traits; supported orientation customization for Et Futurum and saw-strength customization for Iguana; finish the audited reflection/legacy-use map | Next FMP milestone; direct typed calls and documented override behavior, without requiring consumer reflection | +| Complete the supported Java surface | Physical-client validation of the documented illuminated microblock example; broader extension/lifecycle guidance; safe Java compilation guidance for transformed traits; supported orientation customization for Et Futurum and saw-strength customization for Iguana; finish the audited reflection/legacy-use map | Next FMP milestone; direct typed calls and documented override behavior, without requiring consumer reflection | | Migrate consumers and adopt releases | Patch GuideNH/Schematica to their documented APIs; migrate ProjectRed's external trait and other Scala/helper users, including OpenComputers, ProjectBlue and ForgeRelocationFMP; direct Galacticraft integration; Et Futurum/Iguana migrations; UtilitiesInExcess enumeration and `mat`/`material` fix; complete the full adoption ledger beyond these hotspots | Source patches, released versions and actual target-pack jars must all be recorded; reference checkouts are not migrated | | Measure and improve performance | Fresh realistic profiles, ranked candidates, bounded improvements and repeated paired measurements; distinguish FMP implementation gains from migrated-consumer gains and report variability/regressions | Phase 4b starts when API/extension workloads are stable; it can overlap consumer adoption | | Validate releases | Complete client rendering/particles/lighting/interaction and integration checklist; old-world, multiplayer, movement and preview checks; packaged/obfuscated artifacts on supported runtimes; optional-mod absent/present loading; actual patched-world MCPC hook where supported | Automated Forge tests do not replace physical-client/full-pack evidence; repeat affected checks after consumer migration and Scala removal | @@ -648,6 +648,8 @@ same-name overload there invites a silent wrong-overload bind. `scala.collection.Seq` and `scala.Function2`; `registerPartFactory` passes this gate. - [x] Mark the legacy table entries above `@Deprecated` with javadoc naming a working replacement. - [x] Confirm every original descriptor still exists in the ABI fixture after these table changes. +- [x] Document converter registration, candidate ownership and committed lifecycle with a compiling Java example + and registry/Forge characterization; [guide](docs/api/BLOCK_CONVERTERS.md). - [ ] Document the supported API with compiling usage examples and an old-to-new migration guide. Validate Java subclasses and generated extensions on the actual Forge path, including both sides where relevant. diff --git a/JAVA_MIGRATION_ABI_INVENTORY.md b/JAVA_MIGRATION_ABI_INVENTORY.md index 434603c..2ce4aea 100644 --- a/JAVA_MIGRATION_ABI_INVENTORY.md +++ b/JAVA_MIGRATION_ABI_INVENTORY.md @@ -256,3 +256,10 @@ The [three-file example](docs/api/MICROBLOCK_EXTENSIONS.md) uses typed FMP entry to the production API. ProjectRed still ships its external Scala trait; the Java example does not authorize retiring its old class/helper contracts or signature ingestion. Consumer release, pack adoption and internal dependency gates remain in force. The example itself lives only in the functional-test source set. + +### Java block converter guidance + +`IPartConverter`, `registerConverter`, `convertBlock`, `invalidateConvertedTile` and `onConverted` now document their +existing ownership and lifecycle behavior; [guide](docs/api/BLOCK_CONVERTERS.md). All static/companion descriptors, +production method bodies and ScalaSignature payloads remain unchanged. The compiling example is functional-test +content only. Existing converter consumers need no API rename; their factory migration and adoption gates remain. diff --git a/JAVA_MIGRATION_CONSUMER_AUDIT.md b/JAVA_MIGRATION_CONSUMER_AUDIT.md index f75505e..826d30a 100644 --- a/JAVA_MIGRATION_CONSUMER_AUDIT.md +++ b/JAVA_MIGRATION_CONSUMER_AUDIT.md @@ -738,3 +738,18 @@ Full downstream mixed tiles and client-side selection remain Phase 7 integration 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. + +## Java block converter guidance + +The existing `IPartConverter` and static `registerConverter` now have a [Java guide and compiling example](docs/api/BLOCK_CONVERTERS.md). +No production descriptor or method body changed. Reference calls confirm Chisel's block/metadata selection, +ForgeRelocationFMP's frame construction, OpenComputers' original cable/print tile lookup and AE2's cable-bus state copy. +Their converter registrations need no replacement API; companion users can select the existing static entry. +Keep separate factory registrations and published IDs, and preserve consumer-specific state-transfer/cleanup rules. +Extra Utilities remains an active supported converter consumer. Reference checkouts were neither changed nor adopted. + +Two new JVM tests characterize registration snapshots/duplicates and exception propagation. A Forge baseline pins +fresh candidates, rejected probes, original-tile ownership and invalidate/replace/onConverted/onAdded ordering. +The example adds initialized converter/factory registration and NBT/packet/placement coverage, compiled without Scala. +Evidence: `run/migration-converter-reference/`; physical-client conversion and real inventory/network transfers still +require integration validation. This is FMP API coverage, not a released consumer migration. diff --git a/JAVA_MIGRATION_HANDOFF.md b/JAVA_MIGRATION_HANDOFF.md index bdf7d7c..80d9eb4 100644 --- a/JAVA_MIGRATION_HANDOFF.md +++ b/JAVA_MIGRATION_HANDOFF.md @@ -17,7 +17,7 @@ migration checkout; `codex/tile-compatibility-fixes` was deleted after its fixes ## Current state and next target -**571 plain-JVM tests and 278 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **225 Java +**573 plain-JVM tests and 280 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **225 Java files and 9 Scala files / 747 nonblank Scala lines**. The packaged inventory has 444 classes. Review follow-up: restored packet-scheduler callback mutation behavior with the original Scala hash-map traversal, @@ -32,18 +32,15 @@ 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 work adds a ProjectRed-style Java illuminated microblock example. Existing `registerTrait(String)` selects -Java input without loading it first; `IGeneratedMaterial` adds the extension for all shapes/sides. Thin trait methods -pass Object to an ordinary helper, which uses typed Java traversal and geometry. Registration, metadata/cutter -semantics, shape/persistence, light aggregation and ordinary/hollow halo bounds are documented and tested. One Forge -baseline was committed first as `c41ed8d`, covering external Scala composition across all five shapes. Four Java -example cases bring the suite to 571 JVM / 278 Forge tests. The three example files compile without Scala. -All 571 archived JVM and 274 archived Forge tests pass; the archived Forge mod is unchanged. Production APIs/bodies -remain unchanged (444 classes, 17 ScalaSignature payloads, 3,761 methods). The 120 baseline dump bodies are -retained after mapping only allocation-order microblock self-names; ten additional dumps cover the Java trait, five shapes and retained client-body compiler probe. -That probe is headless, not a physical-client render check. ProjectRed's config/halo wiring, released migration and -pack adoption remain pending. Evidence: `run/migration-illuminated-extension-reference/`; -[extension guide](docs/api/MICROBLOCK_EXTENSIONS.md). +Latest API work documents existing block converter registration and the committed conversion lifecycle, with a +[compiling Java example](docs/api/BLOCK_CONVERTERS.md). Two JVM tests and one Forge baseline were committed first as +`a56f90c`, covering registration ownership/duplicates, failure propagation, rejected probes and callback ordering. +One further Forge case exercises the initialized example, fresh conversion, NBT/packet state and normal installation. +All 573 JVM / 280 Forge tests pass; 573 archived JVM / 279 archived Forge tests pass without rebuilding their callers. +Production APIs and all 3,761 method bodies remain unchanged (444 classes, 17 ScalaSignature payloads), as do all 130 +generated dumps. The example compiles as Java 8 without Scala. Evidence: `run/migration-converter-reference/`. +Consumer state-transfer rules, physical-client validation and release/adoption remain separate gates. The previous +[illuminated extension](docs/api/MICROBLOCK_EXTENSIONS.md) likewise still needs physical-client/ProjectRed adoption. Direct typed calls are the intended end state for supported integrations. Optional dependencies should isolate typed compatibility code behind presence/version checks; reflection snippets in earlier guides are temporary legacy @@ -67,15 +64,16 @@ adoption remain pending. Checkouts remain reference-only. The installed `+719` p 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 candidate is converter registration and lifecycle guidance: trace `IPartConverter` callers, -conversion selection and ownership, then add a compiling Java example with focused characterization. The broader -source-compilation story for transformed tile traits and other audited reflection use cases remain separate work. +The next bounded candidate is Java source-compilation guidance for transformed tile traits: characterize consumer +calls against the published dev artifact, document safe stable-base/capability access, and determine whether any +remaining trait-only calls need a supported Java entry or transformed compile stubs. Other audited reflection use +cases remain separate work. Converter registration and lifecycle guidance are complete. The illuminated microblock example supplies the representative Java extension, but physical-client construction, connector-dependent halos, lighting and consumer adoption still need their recorded checks. Progress: all ten Phase 9.1 table rows and Phase 9.2's internal markers are complete, plus Schematica registry lookup, staged Java tile generation, microblock creation, typed material access and the Java illuminated extension example. -Remaining work includes converter/broader extension guidance and other audited reflection use cases. Consumer patches, +Remaining work includes broader extension/compilation guidance and other audited reflection use cases. Consumer patches, releases and pack adoption still precede final Scala removal and client/pack release validation. Extra Utilities remains an active supported consumer. UtilitiesInExcess is the intended replacement, but the support diff --git a/JAVA_MIGRATION_MANUAL_CHECKS.md b/JAVA_MIGRATION_MANUAL_CHECKS.md index ea9db73..962f1f1 100644 --- a/JAVA_MIGRATION_MANUAL_CHECKS.md +++ b/JAVA_MIGRATION_MANUAL_CHECKS.md @@ -109,3 +109,15 @@ translation keys; these are examples for running the checks, not claims that the | AE2 | `assets/appliedenergistics2/lang/en_US.lang`: `item.appliedenergistics2.ItemPart.CableGlass`, `CableCovered`, `CableDense`; `appeng/fmp/CableBusPart.getHollowSize` supplies connected cable bounds | | ForgeRelocation / MatterManipulator | `assets/mcframes/lang/en_US.lang`: `tile.mcframes.frame`; `assets/matter-manipulator/lang/en_US.lang`: `item.itemMatterManipulator3`; the MKIII tier permits moving | | FMP shapes and saws | This repository's `src/main/resources/assets/multipart/lang/en_US.lang`: `mcr_face`, `mcr_hllw`, `mcr_edge`, `mcr_cnr`, and `item.microblock:sawStone/sawIron/sawDiamond` | + +## Converter integration follow-up + +The [converter guide](docs/api/BLOCK_CONVERTERS.md) and Forge fixtures establish registration, discarded probes, +committed callback order and example state round trips. Before adopting consumer changes: + +- [ ] On a physical client/server, preview and cancel conversion of Chisel torches, OpenComputers cables/prints, + AE2 cable buses and supported converter blocks; the source state/network must remain intact. +- [ ] Commit conversion, reconnect/reload, and confirm metadata, inventory and network state survive exactly once, + without duplicate drops, lost contents or ghost connections. Exercise rejection as well as successful placement. +- [ ] Recheck consumer side-specific constructors and descriptions; the headless example packet test does not cover + physical-client class selection or rendering. Record consumer release and actual pack adoption separately. diff --git a/docs/API.md b/docs/API.md index 95447d2..2be0edd 100644 --- a/docs/API.md +++ b/docs/API.md @@ -20,6 +20,7 @@ Existing reflective binaries remain supported until consumer release and pack ad | Task | API and guide | | --- | --- | +| Register block converters | `registerConverter(IPartConverter)` — [registration, state ownership and committed lifecycle](api/BLOCK_CONVERTERS.md) | | Register part factories during mod initialization | `registerPartFactory(IPartFactory2, String...)` — [factory timing, payload ownership and migration](api/PART_REGISTRATION.md) | | Find the factory registered for a part type | `getPartFactory(String)` — [lookup ownership and Schematica reflection migration](api/FACTORY_LOOKUP.md) | | Enumerate microblock materials by numeric ID | `materialCount()`, `materialName(int)`, `getMaterial(int)` — [material enumeration](api/MATERIAL_ENUMERATION.md) | @@ -49,7 +50,6 @@ compile classpath for overload resolution, as the [loading guide](api/PART_LOADI | 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 block converters | [MultiPartRegistry](../src/main/scala/codechicken/multipart/MultiPartRegistry.java): `registerConverter(IPartConverter)`; part factories have a [separate Java guide](api/PART_REGISTRATION.md) | | 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) | @@ -105,8 +105,8 @@ must select the intended parameter types when a method is overloaded. An [illuminated Java microblock extension](api/MICROBLOCK_EXTENSIONS.md) now covers registration, material traits, light aggregation and halo geometry, with compiling examples and Forge coverage. Its physical-client rendering and -ProjectRed adoption remain open. Converter documentation, broader extension/compilation guidance and the remaining -audited reflection replacements are still pending. ProjectRed's existing Scala traits remain supported until adoption. +ProjectRed adoption remain open. [Converter registration and lifecycle](api/BLOCK_CONVERTERS.md) are documented and +tested; broader extension/compilation guidance and the remaining audited reflection replacements are still pending. ProjectRed's existing Scala traits remain supported until adoption. All ten entries in the plan's Phase 9.1 API table have Java replacements. That table is a bounded list of signatures; the broader API, extension and consumer adoption work above remains open. diff --git a/docs/api/BLOCK_CONVERTERS.md b/docs/api/BLOCK_CONVERTERS.md new file mode 100644 index 0000000..9f2587e --- /dev/null +++ b/docs/api/BLOCK_CONVERTERS.md @@ -0,0 +1,84 @@ +# Registering block converters from Java + +[API index](../API.md) · [Factory registration](PART_REGISTRATION.md) · [Conversion results](TILE_CONVERSION.md) + +Use the existing `MultiPartRegistry.registerConverter(IPartConverter)` on both sides during common mod initialization, +after registering the source blocks. It already accepts ordinary Java types; no new wrapper, reflection or Scala +companion lookup is needed. Register the converted part's persistent factory separately with `registerPartFactory`. +The latter is a migration-branch addition with no minimum published dependency version yet. + +## Compiling example + +[BlockConversionExample.java](../../src/functionalTest/java/codechicken/multipart/examples/BlockConversionExample.java) +registers one converter and its NBT/packet factory: + +```java +BlockConversionExample.register(yourSourceBlock); +``` + +Replace `yourmod:converted` and the sample part with your own stable type and implementation. The example copies +block metadata into a fresh part, preserves it through NBT and description packets, and leaves the source untouched. +It intentionally covers registration and state only: it supplies no custom geometry, rendering, drops or gameplay. +Existing published IDs, field names and packet formats must remain unchanged when migrating real parts. + +`blockTypes()` returns a Java `Iterable`; `Collections.singletonList` or `Arrays.asList` covers ordinary cases. +These are block instances, not numeric IDs or metadata values. `convert(world, pos)` checks metadata or tile type as +needed and returns null to decline. The example checks the source block explicitly because it can also be called +directly. Read the source before returning: the registry does not subsequently call `load` or `readDesc` on this part. +The independent factory creates blank instances; normal reconstruction supplies their payload afterward. + +## Registration and dispatch + +- Register once on the initialization thread. FMP retains the converter, enumerates its block iterable immediately, + and appends it to each block's list. Mutating the iterable afterward does not change existing entries. +- Order matters: the first non-null result wins. Returning null continues; throwing stops dispatch and propagates. + There is no priority field, fallback after an exception, result validation, or rollback. +- Duplicate blocks and repeated registration produce duplicate entries. There is no unregister operation. Avoid + registration on world/server load, which can repeat within the same process. +- Unlike factory registration, converter registration does not enforce a mod-container or postInit state gate. + Common preInit/init is the supported integration timing, not a promise of a runtime registration error afterward. + Supply valid non-null blocks and a non-null iterable. An iterator failure leaves earlier registrations present. +- `convertBlock(world, pos, block)` selects by its explicit block argument, passes the same world/position references + to callbacks and returns the result unchanged. It does not check the world's block, call a factory, bind a part, + replace the block or invoke lifecycle hooks. Treat the position as borrowed and do not mutate it. + +## Probes and committed conversion + +Conversion can run repeatedly: a preview, `getOrConvertTileResult`, a rejected or accepted `canPlacePart`, then +`addPart` may each create a different part. Return a fresh, unbound instance each time. Do not drain inventories, +disconnect networks, remove the source block or transfer ownership inside `convert`. A rejected candidate receives +no compensating cleanup callback. Copy state without changing the original; use `world.isRemote` if construction +needs different client/server classes. The sample uses the same class on both paths. + +An accepted lookup creates a bound, uninstalled placeholder. Normal server placement performs conversion again and +then follows this sequence: + +1. The converted part is bound to a placeholder with world and position, while the original block/tile still exists. +2. `invalidateConvertedTile()` runs before replacement. Clear resources already copied into the part here when + necessary to prevent the old block's removal from dropping them again. The base implementation does nothing. +3. FMP replaces the block, installs the placeholder, sends the block-change notification, then calls `onConverted()`. + The base implementation calls `onAdded()`. Preserve that lifecycle if overriding, unless deliberately replacing it. +4. FMP writes the converted part's add-part description, promotes the tile if the requested new part needs more + capabilities, then adds that new part through its normal placement lifecycle. + +Keep the tile returned by `TileMultipart.addPart`; even the tile observed inside `onConverted()` may later be replaced +by capability promotion. A callback failure propagates at its current stage; committed conversion is not transactional. +These hooks run on the server placement path, not on probes. Clients reconstruct from packets instead. For ordinary +placement, check `canPlacePart` first and call `addPart` only on the server. Neither a successful check nor a saved +placeholder reserves the location. See [conversion results](TILE_CONVERSION.md) for lookup ownership. + +## Consumer migration and validation + +Chisel copies torch variant/orientation, ForgeRelocationFMP constructs a frame, OpenComputers inspects cable/print +tiles, and AE2 copies cable-bus state from the original tile. Preserve each consumer's eligibility, state-copy and +cleanup rules. Existing Java converter registrations need no rename; Scala consumers can retain Scala implementation +code while returning Java collections and calling the static entry. Their separate factory migration still uses +`registerPartFactory`. Extra Utilities remains an active supported converter consumer. + +The [registry tests](../../src/test/java/codechicken/multipart/MultiPartRegistryCharacterizationTest.java) cover block +selection, first acceptance, captured lists, duplicates and exception propagation. The +[Forge tests](../../src/functionalTest/java/codechicken/multipart/test/PartConverterFunctionalTest.java) cover rejected +probes, original-tile ownership, callback order, repeated conversion, initialized example registration, NBT/packet +state and normal installation. The example compiles as Java 8 without Scala on its compile classpath. FMP still uses +Scala internally. Physical-client construction/rendering and real consumer inventory/network conversion remain +[manual integration checks](../../JAVA_MIGRATION_MANUAL_CHECKS.md); the example does not establish consumer adoption. diff --git a/docs/api/PART_REGISTRATION.md b/docs/api/PART_REGISTRATION.md index a78fd03..8caf638 100644 --- a/docs/api/PART_REGISTRATION.md +++ b/docs/api/PART_REGISTRATION.md @@ -68,7 +68,7 @@ factory results or promise that a later NBT/packet will be accepted. - `IPartFactory` or Scala `(String, Boolean) => TMultiPart` callers: implement `IPartFactory2`; route the NBT method to the old constructor with `false` and the packet method with `true`. Keep any side-specific class selection. A factory that ignores the old Boolean, such as ForgeRelocationFMP's frame factory, can construct the same part class in both. -- Keep converter registration and trait registration separate. This change neither replaces `registerConverter` nor +- Keep [converter registration](BLOCK_CONVERTERS.md) and trait registration separate. This change neither replaces `registerConverter` nor completes ProjectRed's external microblock trait migration or Schematica's private registry-map migration. All eight old static/companion registration descriptors remain. Both `IPartFactory2` sequence entries are now diff --git a/docs/api/TILE_CONVERSION.md b/docs/api/TILE_CONVERSION.md index bdf2259..fed8baa 100644 --- a/docs/api/TILE_CONVERSION.md +++ b/docs/api/TILE_CONVERSION.md @@ -29,6 +29,8 @@ dispatch and uses the world's client/server side when generating the tile. The result is an immutable record of one lookup; the referenced tile and its parts remain mutable. There is no snapshot of tile contents, ownership transfer, synchronization or automatic update when the world later changes. +To implement conversion, see [block converter registration and lifecycle](BLOCK_CONVERTERS.md). + ## Placeholder lifecycle A converted placeholder has world and position assigned and its converted part bound. FMP has not replaced the diff --git a/docs/migration/HISTORY.md b/docs/migration/HISTORY.md index 5c3ba1e..59027da 100644 --- a/docs/migration/HISTORY.md +++ b/docs/migration/HISTORY.md @@ -2075,3 +2075,34 @@ differences belong in the [divergence ledger](../../JAVA_MIGRATION_DIVERGENCES.m - Updated the API index, plan, adoption ledger and manual checklist. Next bounded task: converter registration and lifecycle guidance; broader transformed-tile compilation guidance and remaining audited reflection replacements remain separate. The performance pass, consumer release/adoption and final Scala removal gates are unchanged. + +### 2026-09-05 — Java block converter registration and lifecycle + +- Reused existing `IPartConverter` / `registerConverter` / `convertBlock`; no API addition, descriptor change or + production method-body change. Javadocs now describe block iterable ownership, ordered/duplicate registration, + borrowed inputs, fresh candidates, failure propagation and server conversion hooks. Fixed the old Boolean/blockID + description on `blockTypes`, whose actual result is `Iterable`. +- Committed the untouched-implementation baseline as `a56f90c`: two JVM tests cover captured block lists, duplicate + entries and exception propagation; one Forge test covers direct unbound conversion, rejected and accepted probes, + original tile ownership, fresh placement conversion, hook order and existing-tile short-circuiting. +- Added the [Java converter guide](../api/BLOCK_CONVERTERS.md) and `BlockConversionExample` in the functional-test + source set. It registers a separate persistent factory, copies source metadata without mutation and preserves it + through NBT/descriptions. One Forge example test covers registration, rejection, fresh candidates, both payload + paths and normal installation. The test reuses the existing fixture lamp; no extra block/world mapping is added. + Real geometry/gameplay, consumer inventory/network transfers and physical-client behavior are explicitly outside + this state/registration sample. +- Confirmed consumer patterns in reference-only Chisel, ForgeRelocationFMP, OpenComputers and AE2 checkouts. + Converter registration already has a usable static Java entry. Preserve eligibility, state-copy and cleanup rules, + with factory migration separate. Extra Utilities remains supported; no consumer source/release/adoption changed. +- Validation: normal and clean formatting/checkstyle/build/Forge runs pass, with **573 JVM / 280 Forge** tests and + zero failures/errors/skips. The **573 archived JVM / 279 archived Forge** callers pass without recompilation, + using their recorded build version for embedded version assertions; the archived Forge jar is byte-identical. + Initial frozen execution at the new version failed only the two expected literal-version comparisons; rerunning + with the recorded version passes without exclusions or fixture edits. +- All **444** production class APIs, **17** ScalaSignature payloads, **3,761** method bodies and **130** generated + dumps are unchanged. The example compiles with `javac --release 8` without Scala and has no Scala/reflection + bytecode references. Production jars exclude it. Packaged classes remain Java 8; both jar variants' five `@Mod` + annotations are checked against the final clean filename version after committing. +- Evidence: `run/migration-converter-reference/`. Updated the API index, plan, audits, handoff and manual integration + checks. Next: source-compilation guidance and safe public access for transformed tile traits. Remaining reflection + capabilities, client validation, downstream releases/adoption and final Scala removal stay open. diff --git a/src/functionalTest/java/codechicken/multipart/examples/BlockConversionExample.java b/src/functionalTest/java/codechicken/multipart/examples/BlockConversionExample.java new file mode 100644 index 0000000..c69e519 --- /dev/null +++ b/src/functionalTest/java/codechicken/multipart/examples/BlockConversionExample.java @@ -0,0 +1,86 @@ +package codechicken.multipart.examples; + +import java.util.Collections; + +import net.minecraft.block.Block; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; + +import codechicken.lib.data.MCDataInput; +import codechicken.lib.data.MCDataOutput; +import codechicken.lib.vec.BlockCoord; +import codechicken.multipart.MultiPartRegistry; +import codechicken.multipart.MultiPartRegistry.IPartConverter; +import codechicken.multipart.MultiPartRegistry.IPartFactory2; +import codechicken.multipart.TMultiPart; + +/** Compiling registration/state example; add the real part's geometry, rendering and gameplay behavior. */ +public final class BlockConversionExample implements IPartConverter, IPartFactory2 { + + public static final String PART_TYPE = "yourmod:converted"; + private final Block sourceBlock; + + public BlockConversionExample(Block sourceBlock) { + this.sourceBlock = sourceBlock; + } + + /** Call once from common preInit/init, after registering the source block, on both sides. */ + public static void register(Block sourceBlock) { + BlockConversionExample example = new BlockConversionExample(sourceBlock); + MultiPartRegistry.registerPartFactory(example, PART_TYPE); + MultiPartRegistry.registerConverter(example); + } + + @Override + public Iterable blockTypes() { + return Collections.singletonList(sourceBlock); + } + + @Override + public TMultiPart convert(World world, BlockCoord pos) { + if (world.getBlock(pos.x, pos.y, pos.z) != sourceBlock) return null; + ConvertedPart part = new ConvertedPart(); + part.metadata = world.getBlockMetadata(pos.x, pos.y, pos.z); + return part; + } + + @Override + public TMultiPart createPart(String name, NBTTagCompound nbt) { + return new ConvertedPart(); + } + + @Override + public TMultiPart createPart(String name, MCDataInput packet) { + return new ConvertedPart(); + } + + public static final class ConvertedPart extends TMultiPart { + + private int metadata; + + @Override + public String getType() { + return PART_TYPE; + } + + @Override + public void save(NBTTagCompound tag) { + tag.setInteger("metadata", metadata); + } + + @Override + public void load(NBTTagCompound tag) { + metadata = tag.getInteger("metadata"); + } + + @Override + public void writeDesc(MCDataOutput packet) { + packet.writeInt(metadata); + } + + @Override + public void readDesc(MCDataInput packet) { + metadata = packet.readInt(); + } + } +} diff --git a/src/functionalTest/java/codechicken/multipart/test/ForgeMultipartFunctionalTestMod.java b/src/functionalTest/java/codechicken/multipart/test/ForgeMultipartFunctionalTestMod.java index 0f88c76..85e561c 100644 --- a/src/functionalTest/java/codechicken/multipart/test/ForgeMultipartFunctionalTestMod.java +++ b/src/functionalTest/java/codechicken/multipart/test/ForgeMultipartFunctionalTestMod.java @@ -23,6 +23,7 @@ import org.junit.platform.reporting.legacy.xml.LegacyXmlReportGeneratingListener import codechicken.microblock.MicroblockGenerator; import codechicken.multipart.MultipartGenerator; +import codechicken.multipart.examples.BlockConversionExample; import codechicken.multipart.examples.IlluminatedMicroblockExample; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLInitializationEvent; @@ -62,6 +63,7 @@ public final class ForgeMultipartFunctionalTestMod { externalScalaMicroblockTraitId = MicroblockGenerator .registerTrait("codechicken.multipart.test.ExternalScalaMicroblockFixture"); IlluminatedMicroblockExample.registerMaterials(illuminatedLamp); + BlockConversionExample.register(illuminatedLamp); initialized = true; } diff --git a/src/functionalTest/java/codechicken/multipart/test/PartConverterFunctionalTest.java b/src/functionalTest/java/codechicken/multipart/test/PartConverterFunctionalTest.java index ef6bb65..a0afba7 100644 --- a/src/functionalTest/java/codechicken/multipart/test/PartConverterFunctionalTest.java +++ b/src/functionalTest/java/codechicken/multipart/test/PartConverterFunctionalTest.java @@ -14,20 +14,83 @@ import java.util.List; import net.minecraft.block.Block; import net.minecraft.init.Blocks; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import org.junit.jupiter.api.Test; +import codechicken.lib.packet.PacketCustom; import codechicken.lib.vec.BlockCoord; import codechicken.multipart.MultiPartRegistry; import codechicken.multipart.MultiPartRegistry.IPartConverter; import codechicken.multipart.TMultiPart; import codechicken.multipart.TileMultipart; +import codechicken.multipart.examples.BlockConversionExample; class PartConverterFunctionalTest { + @Test + void javaExampleRegistersConvertsAndPreservesStateThroughNbtAndPackets() { + World world = MinecraftServer.getServer().worldServers[0]; + BlockCoord pos = new BlockCoord(60, 200, 48); + Block source = ForgeMultipartFunctionalTestMod.illuminatedLamp; + world.getChunkFromBlockCoords(pos.x, pos.z); + BlockConversionExample converter = (BlockConversionExample) MultiPartRegistry + .getPartFactory(BlockConversionExample.PART_TYPE); + assertEquals(Collections.singletonList(source), converter.blockTypes()); + try { + world.setBlock(pos.x, pos.y, pos.z, Blocks.stone, 0, 0); + assertNull(converter.convert(world, pos)); + world.setBlock(pos.x, pos.y, pos.z, source, 11, 0); + TMultiPart converted = MultiPartRegistry.convertBlock(world, pos, source); + assertTrue(converted instanceof BlockConversionExample.ConvertedPart); + assertNull(converted.tile()); + assertNotSame(converted, MultiPartRegistry.convertBlock(world, pos, source)); + assertSame(source, world.getBlock(pos.x, pos.y, pos.z)); + NBTTagCompound saved = new NBTTagCompound(); + converted.save(saved); + assertEquals(11, saved.getInteger("metadata")); + + TMultiPart restored = MultiPartRegistry.loadPart(converted.getType(), saved); + assertNotSame(converted, restored); + assertNull(restored.tile()); + restored.load(saved); + NBTTagCompound copy = new NBTTagCompound(); + restored.save(copy); + assertEquals(saved, copy); + + PacketCustom outgoing = new PacketCustom("test", 1); + MultiPartRegistry.writePartID(outgoing, converted); + converted.writeDesc(outgoing); + outgoing.writeByte(37); + PacketCustom incoming = new PacketCustom(outgoing.getByteBuf().copy()); + TMultiPart client = MultiPartRegistry.readPart(incoming); + assertNotSame(converted, client); + assertNull(client.tile()); + client.readDesc(incoming); + copy = new NBTTagCompound(); + client.save(copy); + assertEquals(saved, copy); + assertEquals(37, incoming.readUByte()); + + TMultiPart added = new MultipartGeneratorFunctionalTest.PlainPart(); + assertTrue(TileMultipart.canPlacePart(world, pos, added)); + TileMultipart installed = TileMultipart.addPart(world, pos, added); + TMultiPart committed = installed.jPartList().get(0); + assertEquals(converted.getType(), committed.getType()); + assertNotSame(converted, committed); + copy = new NBTTagCompound(); + committed.save(copy); + assertEquals(saved, copy); + assertSame(installed, committed.tile()); + assertSame(installed, world.getTileEntity(pos.x, pos.y, pos.z)); + } finally { + world.setBlockToAir(pos.x, pos.y, pos.z); + } + } + @Test void probesLeaveOriginalTileIntactAndCommitRunsConversionHooksInOrder() { World world = MinecraftServer.getServer().worldServers[0]; diff --git a/src/main/scala/codechicken/multipart/MultiPartRegistry.java b/src/main/scala/codechicken/multipart/MultiPartRegistry.java index bc8f72f..921ac0c 100644 --- a/src/main/scala/codechicken/multipart/MultiPartRegistry.java +++ b/src/main/scala/codechicken/multipart/MultiPartRegistry.java @@ -71,15 +71,29 @@ public final class MultiPartRegistry { TMultiPart createPart(String name, MCDataInput packet); } - /** An interface for converting existing blocks/tile entities to multipart versions. */ + /** + * Converts an existing block/tile into a fresh, unbound part. Register once during common mod initialization on + * both sides with {@link MultiPartRegistry#registerConverter(IPartConverter)}, separately from its persistent part + * factory. Conversion may run repeatedly for inspection, placement checks and eventual placement; do not remove the + * source block or transfer live resources here. See {@link TMultiPart#invalidateConvertedTile()} and + * {@link TMultiPart#onConverted()} for the committed conversion lifecycle. + */ public interface IPartConverter { /** - * Return true if this converter can handle the specific blockID (may or may not actually convert the block). + * Returns the block instances this converter may handle. Enumerated immediately during registration; the + * iterable is not retained. Return non-null blocks without duplicates. Metadata/tile eligibility is checked by + * convert, not by registration. */ Iterable blockTypes(); - /** Return a multipart version of the block at pos in world. Return null if no conversion is possible. */ + /** + * Inspect the source at pos and return a fresh, unbound part, or null to let the next converter try. World and + * position are borrowed, unchanged references; do not mutate the position. Use world.isRemote for side-specific + * construction. Copy required state without consuming it: the candidate may be discarded and this callback may + * run again. FMP does not invoke load/readDesc on this result or validate its registered type. Exceptions + * propagate and stop dispatch; they do not mean "try the next converter". + */ TMultiPart convert(World world, BlockCoord pos); } @@ -198,7 +212,16 @@ public final class MultiPartRegistry { registerParts(partFactory, types); } - /** Register a part converter instance. */ + /** + * Registers a converter for each block returned by blockTypes, in iteration order. Retains the converter object and + * appends to each block's ordered list; duplicate blocks or calls create duplicate entries. Registration does not + * call convert, register a part factory or copy the iterable. Iterator failures leave earlier entries present. + * + *

+ * Call once from common preInit/init after source blocks exist, on both sides. Unlike part-factory registration, + * this legacy entry does not enforce an active mod container or a registry-state gate. It provides no unregister, + * deduplication or synchronization; do not use world-load callbacks to repeatedly register converters. + */ public static void registerConverter(IPartConverter c) { for (Block block : c.blockTypes()) { converters.put(block, c); @@ -320,7 +343,14 @@ public final class MultiPartRegistry { return client ? factory.createPart(name, (MCDataInput) null) : factory.createPart(name, (NBTTagCompound) null); } - /** Calls converters to create a multipart version of the block at pos. */ + /** + * Tries converters registered for the supplied block, in registration order, and returns the first non-null result + * unchanged. The block argument selects the list; this method does not read or verify the world's block. Callbacks + * receive the original world/pos references. Returns null when all decline or none are registered; failures + * propagate. Does not load, bind, install or invoke conversion lifecycle hooks on the result. Ordinary callers + * should use {@link TileMultipart#getOrConvertTileResult(World, BlockCoord)} for a bound placeholder, or the + * placement APIs. + */ public static TMultiPart convertBlock(World world, BlockCoord pos, Block block) { for (IPartConverter c : converters.get(block)) { TMultiPart ret = c.convert(world, pos); diff --git a/src/main/scala/codechicken/multipart/TMultiPart.java b/src/main/scala/codechicken/multipart/TMultiPart.java index d88202c..017aa36 100644 --- a/src/main/scala/codechicken/multipart/TMultiPart.java +++ b/src/main/scala/codechicken/multipart/TMultiPart.java @@ -320,14 +320,22 @@ public abstract class TMultiPart { */ public void onWorldJoin() {} - /** Called when this part is converted from a normal block/tile (only applicable if a converter is registered). */ + /** + * Called on committed server conversion after FMP replaces the source block and installs this part's tile, before + * writing its add-part description and adding the requested new part. Not called for conversion probes. The default + * delegates to onAdded; preserve that lifecycle when overriding unless the part intentionally replaces it. A later + * capability promotion may replace the tile again, so do not retain this tile as a permanent owner. + */ public void onConverted() { onAdded(); } /** - * Called when this part is converted from a normal block/tile (only applicable if a converter has been registered) - * before the original tile has been replaced. Use this to clear out things like inventory from the old tile. + * Called on committed server conversion immediately before the source block/tile is replaced. This part is already + * bound to a placeholder, while the world still contains the original tile. Use this to clear resources copied from + * the old tile so its removal does not drop them again. Never perform that destructive transfer in the converter, + * which also runs for discarded probes. The default is a no-op. Failures propagate; conversion is not + * transactional. */ public void invalidateConvertedTile() {}