From b7d28fb794860861528b3baf7483762db1f87e72 Mon Sep 17 00:00:00 2001 From: Algent Date: Sat, 5 Sep 2026 14:28:06 +0200 Subject: [PATCH] docs: define Java microblock creation contract --- JAVA_MIGRATION.md | 8 +- JAVA_MIGRATION_ABI_INVENTORY.md | 7 +- JAVA_MIGRATION_CONSUMER_AUDIT.md | 20 ++++- JAVA_MIGRATION_HANDOFF.md | 34 ++++--- docs/API.md | 1 + docs/api/COMPOSITE_GENERATION.md | 3 +- docs/api/FACTORY_LOOKUP.md | 2 + docs/api/MICROBLOCK_CREATION.md | 90 +++++++++++++++++++ docs/migration/HISTORY.md | 24 +++++ .../examples/MicroblockCreationExample.java | 21 +++++ .../MicroblockGeneratorFunctionalTest.java | 44 +++++++++ .../microblock/MicroblockGenerator$.java | 4 + .../microblock/MicroblockGenerator.java | 31 +++++++ 13 files changed, 266 insertions(+), 23 deletions(-) create mode 100644 docs/api/MICROBLOCK_CREATION.md create mode 100644 src/functionalTest/java/codechicken/multipart/examples/MicroblockCreationExample.java diff --git a/JAVA_MIGRATION.md b/JAVA_MIGRATION.md index fb5bd80..ba5d4b4 100644 --- a/JAVA_MIGRATION.md +++ b/JAVA_MIGRATION.md @@ -684,7 +684,7 @@ does not close a row, and scans must distinguish a consumer's own Scala code fro | --- | --- | --- | --- | | ProjectRed | Runtime Scala-signature decoding and external trait registration, reached through `MicroblockGenerator.registerTrait(classOf[LightMicroblock])` | Rewrite the ~60-line `LightMicroblock` trait as a Java mixin registered through the `registerJavaTrait` path | FMP compiler prerequisites complete; consumer rewrite and release remain | | Schematica | Private Scala-mangled field `codechicken$multipart$MultiPartRegistry$$typeMap`, cast to `scala.collection.mutable.Map` | `MultiPartRegistry.getPartFactory(String)` is implemented; [guide and example](docs/api/FACTORY_LOOKUP.md). Schematica replaces map/Option lookup with the public method and retains its microblock creation/rejection policy | FMP lookup ready; consumer patch/release/adoption pending | -| GuideNH | Companion `MultipartGenerator$.MODULE$.generateCompositeTile` and `MicroblockGenerator$.create`; `partList_$eq(scala.collection.Seq)`; mixin into private `BlockMicroMaterial.block` and `.meta` | Static Java tile generation and `setPartList(List)` are implemented; [generation guide](docs/api/COMPOSITE_GENERATION.md). Validate/document the existing Java microblock creation entry and public material accessors next | Tile generation/loading ready; remaining reflection contracts and consumer adoption pending | +| GuideNH | Companion `MultipartGenerator$.MODULE$.generateCompositeTile` and `MicroblockGenerator$.create`; `partList_$eq(scala.collection.Seq)`; mixin into private `BlockMicroMaterial.block` and `.meta` | Static Java tile generation/loading and existing microblock creation are documented/tested; [microblock guide](docs/api/MICROBLOCK_CREATION.md). Validate public material accessors next | Creation/loading ready; private material access and consumer adoption pending | | Et Futurum Requiem | Mutable static `int[] ButtonPart.metaSideMap` and `sideMetaMap` must stay public and mutable | FMP exposes a supported orientation-override API; Et Futurum uses it | After step 1 | | IguanaTweaksTConstruct | Private `ItemSaw.harvestLevel` field name and type | FMP exposes a supported harvest-level setter; Iguana uses it | After step 1 | | Galacticraft | Selects the first public method named `registerMaterial` without checking its signature, so FMP cannot add any overload of that name | Make the reflection check the parameter types | Immediately; independent of the port | @@ -738,7 +738,11 @@ UtilitiesInExcess's `extrautils:*` aliases; there is no legacy-conversion risk i This does not complete Schematica's consumer migration. - [x] Provide static Java client/server composite generation for Schematica and GuideNH, preserving exact reuse, staged loading, input traversal/failure behavior and the old companion reflection path; [guide](docs/api/COMPOSITE_GENERATION.md). - GuideNH's separate microblock creation/material reflection and both consumers' release/adoption remain pending. + Both consumers' release/adoption remain pending. +- [x] Document and validate the existing Java microblock creation entry for GuideNH, including exact companion/static + reflection, material trait callbacks, fresh-part/shape ownership and a compiling example. Keep physical-client + validation and public-setter versus private-field override behavior explicit; [guide](docs/api/MICROBLOCK_CREATION.md). + GuideNH's private material access and the representative external Java extension remain separate work. - [ ] Patch those four consumers and record the released versions that no longer need the private shapes. - [ ] Track all legacy FMP dependencies in the adoption ledger, including trait helper/companion calls and reflection outside the cleanup table; verify the released jars actually selected for the target pack. diff --git a/JAVA_MIGRATION_ABI_INVENTORY.md b/JAVA_MIGRATION_ABI_INVENTORY.md index d93e528..367e9d7 100644 --- a/JAVA_MIGRATION_ABI_INVENTORY.md +++ b/JAVA_MIGRATION_ABI_INVENTORY.md @@ -193,7 +193,7 @@ method on it. So for most entries the companion is a fallback. The exceptions be | `MultipartGenerator` | `generateCompositeTile(TileEntity, scala.collection.Iterable, boolean)` | **companion only for the Scala descriptor**; new static Java-Iterable entry is additive | | `BlockMicroMaterial` | `register(material)`, plus a constructor of arity 2 `(Block, int)` or 1 `(Block)` | static; companion is fallback | | `MicroMaterialRegistry` | `getMaterial(int)` | static; companion is fallback | -| `MicroblockGenerator$` | `create(MicroblockClass, int, boolean)` | **companion only**, matched by exact parameter types | +| `MicroblockGenerator$` | `create(MicroblockClass, int, boolean)` | GuideNH explicitly selects the companion, matched by exact parameter types; static Java replacement exists | | `TileMultipart` | `partList()`, `partList_$eq(scala.collection.Seq)`, `loadParts(...)`, `notifyTileChange()`, `markRender()` | instance | | `Microblock` | `microClass()`, `material()`, `shape()` | instance | | `TMultiPart` | `getDrops()` | instance | @@ -219,6 +219,11 @@ 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. + The existing static `MicroblockGenerator.create(MicroblockClass, int, boolean)` now has a + [guide and compiling example](docs/api/MICROBLOCK_CREATION.md). Both exact reflective entries are tested; no API + shape or production method body changes were needed. GuideNH must change its explicitly selected owner and receiver + before it stops using the companion. Release/adoption, shape-setter override checks and client previews remain gates. + 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 diff --git a/JAVA_MIGRATION_CONSUMER_AUDIT.md b/JAVA_MIGRATION_CONSUMER_AUDIT.md index d68c322..96bbe2e 100644 --- a/JAVA_MIGRATION_CONSUMER_AUDIT.md +++ b/JAVA_MIGRATION_CONSUMER_AUDIT.md @@ -322,7 +322,7 @@ reflective to keep the integration optional. microblock properties, and part drops. - `MultipartGenerator$.MODULE$.generateCompositeTile(TileEntity, scala.collection.Iterable, boolean)` remains companion-only for that descriptor; a static Java-Iterable entry is now available. -- `MicroblockGenerator$.create(MicroblockClass, int, boolean)` is companion-only and matched by exact parameter +- `MicroblockGenerator$.create(MicroblockClass, int, boolean)` is explicitly selected on the companion and matched by exact parameter classes. - Client preview promotion replaces parts with client microblock instances, assigns `partList_$eq(scala.collection.Seq)`, loads/binds them, then triggers tile/render notifications. @@ -518,6 +518,7 @@ tied to a released minimum dependency version. Unlisted contracts remain governe | `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 lookup and Java tile generation available separately | No migrated pack version verified; retain the Scala loader descriptor | | Private `MultiPartRegistry$` Scala `typeMap` field and `Map.get` / `Option` | Schematica `3b03ee937953`: `nbt.ForgeMultipart.init` and `createPart` | Reflect public static `MultiPartRegistry.getPartFactory(String.class)`; keep material lookup, `MicroblockClass.create(client, materialId)` and whole-preview rejection | Source patch/release pending; lookup and Java tile generation implemented | No migrated pack version verified; retain the exact private live Scala-map field | | `MultipartGenerator$.generateCompositeTile(TileEntity, scala.collection.Iterable, boolean)` | Schematica `3b03ee937953` exact reflection; GuideNH `7d8fb44e77b9` static-first assignability matcher | Static `MultipartGenerator.generateCompositeTile(TileEntity, java.lang.Iterable, boolean)` with Java parts; retain subsequent state setup/loading | Source patches/releases pending; preserve client part construction, candidate-reuse branch and notification order | No migrated pack version verified; retain the companion and Scala descriptor | +| `MicroblockGenerator$.create(MicroblockClass, int, boolean)` exact reflection and private shape copy | GuideNH `7d8fb44e77b9`: `getMicroblockGeneratorCreate`, `promoteMicroblockToClient` | Existing static `MicroblockGenerator.create` with the same parameter types/order; recreate family/material and restore encoded shape through public API | Source patch/release pending; guide/example tested on server, physical client and custom shape-setter overrides require adoption checks | No migrated pack version verified; retain companion singleton and exact descriptor | | `NormalOcclusionTest$.apply(Traversable, Traversable)` | OpenComputers `2c00f79be24b`: `common.block.Cable.canConnectFromSideFMP`, `server.network.Network.canConnectFromSideFMP` | `NormalOcclusionTest.testBoxes(ownBounds.asJava, otherBounds)`; `otherBounds` already comes from Java `getOcclusionBoxes()` | Source patch and release pending; retain side/color/face filtering | No migrated pack version verified; retain the companion and descriptor | | `NormalOcclusionTest$.apply(Traversable, Traversable)` | ForgeRelocationFMP `49a810b8c63b`: `FramePart.occlusionTest` | `NormalOcclusionTest.testBoxes(boxes.asJava, getOcclusionBoxes)`; retain combined normal/partial/collision boxes and caller order | Source patch and release pending; preserve temporary face bounds and replacement protocol | No migrated pack version verified; retain the companion and descriptor | @@ -628,6 +629,23 @@ Forge tests; the full current suite and independent ABI comparison check the int generation/worldless loading is covered, while physical-client microblock construction and GPU previews remain manual. Reference checkouts and consumer adoption remain unchanged. Evidence: `run/migration-composite-generation-reference/`. +GuideNH's microblock creation contract is documented at [microblock creation](docs/api/MICROBLOCK_CREATION.md). The +static Java method already existed, so this slice adds Javadocs, tests and an example with no production API/body +changes. GuideNH hardcodes the companion owner and caches its singleton; its source must switch both to use the static +method. It copies only shape after recreation, not arbitrary custom state or binding. The Java example preserves +all 256 shape bytes for a stock face microblock through `setShape`, which uses virtual setter dispatch unlike the old +private-field write; custom override validation remains a consumer gate. + +The example captures factory, material and shape before generation, matching GuideNH's read order. A regression +callback that mutates the source shape proves the copied value is the pre-callback value, not a later reread. + +Existing generated-material coverage proves the external Scala trait is attached before construction. New tests pin +exact static/companion reflection, fresh instances, factory/material identity, caller-owned NBT/shape and failure +propagation with reused scratch state. The example compiles without Scala. All 568 archived JVM tests and 267 tests +from the unchanged archived Forge mod pass. Physical-client creation/GPU previews remain manual; the dedicated +server strips the client's factory method. All 386 pack ABI/reflection rows remain across 27 consumers, and reference +checkouts are unchanged. Evidence: `run/migration-microblock-creation-reference/`. + ## 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 91eacd8..2d415ae 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 -**568 plain-JVM tests and 265 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **225 Java +**568 plain-JVM tests and 269 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,17 +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 addition: static `MultipartGenerator.generateCompositeTile(TileEntity, java.lang.Iterable, -boolean)` exposes staged client/server generation. Three Forge baseline cases were committed first as `ab5654b`; -four more cases cover the Java entry, exact reflection and a compiling setup/loading example. Exact reuse, no implicit -state copying/loading/installation, input traversal and failures remain unchanged. Both consumers' old Scala reflection -paths still work; the companion entry retains its descriptor/body with deprecation. Of 568 archived JVM tests, 567 pass; -one obsolete exact facade inventory assertion is excluded, updated in the full current suite and supplemented -by the independent ABI comparison. All 261 archived Forge cases pass without recompilation. All 444 class APIs, -17 ScalaSignature payloads, 3,760 existing method bodies and 116 generated dumps remain, with one public static entry -and one deprecation added. The example compiles without Scala. Client tile generation/worldless loading are covered; -physical-client microblock construction and GPU previews remain manual. -Evidence: `run/migration-composite-generation-reference/`; [guide](docs/api/COMPOSITE_GENERATION.md). +Latest API work documents and validates existing `MicroblockGenerator.create(MicroblockClass, int, boolean)` for +GuideNH. Two Forge baseline cases were committed first as `5d572ef`; two more test the compiling recreation example, +all encoded shape bytes and capturing source state before material callbacks. Static/companion reflection, fresh +parts, caller-owned shape/NBT, material trait injection and callback failure/scratch reuse are covered. No production +API or behavior changed: all 444 class APIs, 17 ScalaSignature payloads, 3,761 method bodies and 116 generated dumps +remain, with no additions/deprecations. All 568 archived JVM tests and the unchanged archived Forge mod's 267 cases +pass. The example compiles without Scala. Physical-client creation/previews and custom shape-setter override checks +remain consumer validation gates; GuideNH's old private shape write bypassed the public setter's virtual dispatch. +Evidence: `run/migration-microblock-creation-reference/`; [guide](docs/api/MICROBLOCK_CREATION.md). 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. @@ -61,14 +59,14 @@ 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 GuideNH's microblock creation contract: document and validate the existing static -`MicroblockGenerator.create(MicroblockClass, int, boolean)` as the replacement for its exact companion reflection. -Reuse that Java entry rather than adding a second one. Trace material-provided traits, side selection, class/factory -identity and caller-owned NBT loading, with a compiling example and explicit physical-client limits. The representative -external Java extension, private-material access migration and internal-boundary documentation remain separate work. +The next bounded candidate is GuideNH's private `BlockMicroMaterial.block` / `meta` access. Trace its accessor mixin +and reflection fallbacks, then document/test the existing public material accessors wherever they cover the same +contract. Preserve private fields until consumer release/adoption and keep virtual-accessor behavior explicit. +The representative external Java extension and internal-boundary documentation remain separate work. Progress: all ten Phase 9.1 table rows now have implemented/documented Java replacements, plus the separate Schematica -registry lookup and staged Java tile generation. Remaining work includes microblock/reflection guidance, extension examples and internal-boundary +registry lookup, staged Java tile generation and existing Java microblock-creation guidance. Remaining work includes +private material/reflection guidance, extension examples and internal-boundary documentation. Then consumer patches, releases and pack adoption must precede final Scala removal and client/pack release validation; it is not a percentage of the whole migration. diff --git a/docs/API.md b/docs/API.md index 099a4d3..379bbc4 100644 --- a/docs/API.md +++ b/docs/API.md @@ -15,6 +15,7 @@ without converting the rest of its code to Java. | 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) | +| Create a microblock with the requested material and side | `MicroblockGenerator.create(MicroblockClass, int, boolean)` — [construction, material traits and GuideNH migration](api/MICROBLOCK_CREATION.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) | diff --git a/docs/api/COMPOSITE_GENERATION.md b/docs/api/COMPOSITE_GENERATION.md index f1516cc..5377365 100644 --- a/docs/api/COMPOSITE_GENERATION.md +++ b/docs/api/COMPOSITE_GENERATION.md @@ -76,7 +76,8 @@ The old companion's `generateCompositeTile(TileEntity, scala.collection.Iterable body, deprecated for callers in favor of the static Java entry. Existing internal calls remain unchanged. GuideNH's argument-assignability matcher still rejects the Java parameter for a Scala sequence and falls back to the companion; Schematica's exact old reflective lookup remains valid. Consumer source patches/releases and pack adoption remain pending. -GuideNH's separate microblock-generator and private-material dependencies are not closed by this tile API. +GuideNH's separate microblock-generator call has an [existing Java replacement](MICROBLOCK_CREATION.md). +Private-material access remains a separate migration contract; neither is closed by this tile API alone. ## Validation diff --git a/docs/api/FACTORY_LOOKUP.md b/docs/api/FACTORY_LOOKUP.md index 2abb502..c55927b 100644 --- a/docs/api/FACTORY_LOOKUP.md +++ b/docs/api/FACTORY_LOOKUP.md @@ -29,6 +29,8 @@ looks up a `MicroblockClass` and calls `create(client, materialId)` before loadi `loadPart` instead would select the server/NBT construction path, even for a client preview. Passing a null packet or using deprecated `createPart(name, true)` is also unsuitable: microblock packet factories read a material ID from it. +See [microblock creation](MICROBLOCK_CREATION.md) for side selection, material traits and caller-owned shape/NBT state. + The [compiling Java example](../../src/functionalTest/java/codechicken/multipart/examples/PartFactoryLookupExample.java) checks for `MicroblockClass` and creates a fresh unbound microblock. The caller must resolve a valid material ID, load the part's NBT, prepare the correct composite tile and complete its existing lifecycle. This example only covers diff --git a/docs/api/MICROBLOCK_CREATION.md b/docs/api/MICROBLOCK_CREATION.md new file mode 100644 index 0000000..6dc8a09 --- /dev/null +++ b/docs/api/MICROBLOCK_CREATION.md @@ -0,0 +1,90 @@ +# Creating and recreating microblocks + +[Java API index](../API.md) + +Use the existing `MicroblockGenerator.create(MicroblockClass, int material, boolean client)` static Java entry. +It delegates to the retained companion implementation. This guide describes `algent/java`; it does not establish a +minimum published dependency version. No additional creation API or production behavior change is introduced here. + +```java +Microblock part = MicroblockGenerator.create(microClass, materialId, client); +``` + +`microClass.create(client, materialId)` uses the same generator; note its different parameter order. To find a factory +by part type, use [registered factory lookup](FACTORY_LOOKUP.md) and verify that it is a `MicroblockClass`. + +## Construction and ownership + +Creation chooses the factory's base trait and, for the client path, its client trait. It then resolves the material +from the active numeric ID map and invokes `IGeneratedMaterial.addTraits` when implemented. Finally it constructs a +fresh instance of the resulting generated class with the material ID as its constructor argument. Generated classes +are cached; part instances are not reused. Trait initializers execute during construction. + +The generator does not copy an existing part, assign a requested shape, load NBT, bind the part or install a tile. +Stock face microblocks begin with shape zero, which is not a completed placement shape. Restore shape/NBT before +using geometry or rendering and before [preparing/loading a composite tile](COMPOSITE_GENERATION.md). + +Resolve the intended material before construction. A later `part.load(tag)` or `material_$eq` updates stored material +but does not regenerate the class's material traits. For NBT reconstruction, resolve `tag.getString("material")`, +create the correctly sided part with that ID, then call `load(tag)`. Ordinary `MultiPartRegistry.loadPart` selects the +server/NBT path; it does not provide client preview construction. + +Call after factory/trait registration and material-map initialization, on the initialization/game thread. Numeric IDs +belong to the active map and may change across sessions or a multiplayer handshake; persist material names, not IDs. +See [material enumeration and ownership](MATERIAL_ENUMERATION.md). Invalid/unresolved IDs, null factories, callback +exceptions and constructor failures propagate; there is no new fallback or rollback. + +## Material-provided traits + +`IGeneratedMaterial.addTraits(BitSet, MicroblockClass, boolean)` receives the exact factory and side supplied by the +caller. Its borrowed mutable bit set already contains the selected base/client traits. Add registered trait IDs; +do not remove required traits. The generator consumes the modified set immediately after the callback. + +Do not retain the set or recursively call this generator from the callback: the next creation on that thread clears +and reuses it. On failure, already-performed callback side effects and scratch mutations remain; a later creation +clears scratch again. Thread-local scratch does not make registry changes or the complete generator thread-safe. + +ProjectRed's existing external Scala trait path remains supported. The Forge fixture confirms material-driven trait +injection and generated behavior; this does not replace the planned representative external Java extension example +or authorize removing Scala-signature support before consumer release/adoption. + +## GuideNH migration + +GuideNH `7d8fb44e77b9` explicitly resolves the companion's `create(MicroblockClass, int, boolean)` and invokes it on +`MODULE$`. It does not automatically discover the existing static method. Its optional integration can instead cache: + +```java +Class generator = Class.forName("codechicken.microblock.MicroblockGenerator"); +Class factoryType = Class.forName("codechicken.microblock.MicroblockClass"); +Method create = generator.getMethod("create", factoryType, int.class, boolean.class); +Object promoted = create.invoke(null, microClass, materialId, true); +``` + +Keep the exact parameter types and order. The old companion class, singleton, descriptor and behavior remain +unchanged for existing releases. + +GuideNH's promotion recreates the source family and material on the client, then copies the encoded shape byte. +The [compiling Java example](../../src/functionalTest/java/codechicken/multipart/examples/MicroblockCreationExample.java) +implements that core-data policy through `setShape(size, slot)`, preserving all eight shape bits. `getShape()` alone +is only the slot nibble, while `shape()` returns the complete byte. The example leaves source bindings untouched and +returns an unbound replacement. It is not a clone of arbitrary custom-part state or a shape-validity check. + +Factory, material and shape are captured before construction, as in GuideNH. Material callbacks can have side effects; +capturing shape after creation could copy a callback-modified value instead of the original one. + +Public `setShape` uses the virtual shape setter; GuideNH's old private-field write bypassed that dispatch. Validate +custom traits overriding these hooks before adopting the change. Preserve its existing missing/failed-promotion +handling, part order, Java collection migration, tile state setup and subsequent loading/notifications. Do not copy +the source tile binding to the new part. Private material-field access is a separate remaining GuideNH contract. + +## Side and validation limits + +Use `client=true` on the physical client for client variants. Unlike generating a client tile container, normal client +microblock construction cannot run in the dedicated-server harness: Forge strips `MicroblockClass.clientTrait()`. +The side parameter selects traits; it does not infer a world side or bypass Forge's side-only filtering. + +Server Forge tests cover both exact reflective entries, factory/material identity, fresh instances, shape/NBT +ownership, material trait injection, callback failures and scratch reuse. The Java example tests all 256 shape-byte +values without copying bindings or altering the source and compiles without Scala. Archived callers, existing APIs, +method bodies and generated dumps are checked separately. Physical-client creation and GuideNH preview/GPU output +remain [manual release checks](../../JAVA_MIGRATION_MANUAL_CHECKS.md); reference checkouts and adoption status are unchanged. diff --git a/docs/migration/HISTORY.md b/docs/migration/HISTORY.md index 46429dd..03e2a53 100644 --- a/docs/migration/HISTORY.md +++ b/docs/migration/HISTORY.md @@ -1947,3 +1947,27 @@ differences belong in the [divergence ledger](../../JAVA_MIGRATION_DIVERGENCES.m reference-only and releases/adoption are pending. Client tile generation/worldless loading are tested; actual client microblock construction and preview rendering remain manual. Next bounded task: GuideNH's existing Java microblock creation entry and its documented contract. Evidence: `run/migration-composite-generation-reference/`. + +### 2026-09-05 — Existing Java microblock creation contract + +- Traced GuideNH's exact companion selection and shape-only promotion. The static Java creation method already + delegates to that implementation, so no API addition, deprecation or production behavior change was needed. + Added Javadocs for creation and borrowed `IGeneratedMaterial` trait-set ownership, plus a consumer guide/example. +- Committed two Forge baseline cases first as `5d572ef`, with saved reference artifacts. Exact static/companion + reflection returns fresh unbound parts with the stock factory/material identity; shape/NBT loading is caller-owned. + Material callback exceptions propagate, leaving scratch changes until the next creation clears the reused set. + Existing generated-material coverage retains the external Scala trait path and its generated behavior. +- Added two example cases: all 256 encoded shape bytes survive public `setShape` recreation without copying bindings, + and factory/material/shape are captured before material callbacks, matching GuideNH's read order. A callback that + changes source shape verifies the original value is copied. This is a core-data recreation example, not a clone of + custom state. Public setter dispatch differs from GuideNH's private-field write; custom overrides remain an adoption check. +- The example compiles without Scala. Normal style/build checks and the final clean build pass; the final suite has + 568 JVM and 269 Forge tests, zero failures/errors/skips. All 568 archived JVM tests and 267 cases from the byte-identical + archived Forge mod pass with no exclusions. All 444 class APIs, 17 ScalaSignature payloads, 3,761 method bodies and + 116 generated dumps remain apart from build versions. No production source inventory or Java 8 target change. +- Added the GuideNH adoption ledger row and corrected the historical companion-only wording: this consumer explicitly + selects the companion even though the static replacement exists. Its source patch/release/adoption are pending. + The `+719` scan retains all 386 member/type/reflection rows across 27 consumers; reference checkouts remain unchanged. + Physical-client creation/previews remain manual because the dedicated server strips client factory methods. + Next bounded task: GuideNH's private material access versus existing public accessors. + Evidence: `run/migration-microblock-creation-reference/`. diff --git a/src/functionalTest/java/codechicken/multipart/examples/MicroblockCreationExample.java b/src/functionalTest/java/codechicken/multipart/examples/MicroblockCreationExample.java new file mode 100644 index 0000000..dde396e --- /dev/null +++ b/src/functionalTest/java/codechicken/multipart/examples/MicroblockCreationExample.java @@ -0,0 +1,21 @@ +package codechicken.multipart.examples; + +import codechicken.microblock.Microblock; +import codechicken.microblock.MicroblockClass; +import codechicken.microblock.MicroblockGenerator; + +/** Forge-tested compiling example for docs/api/MICROBLOCK_CREATION.md. */ +public final class MicroblockCreationExample { + + private MicroblockCreationExample() {} + + /** Recreates the family/material/shape on the requested side; does not clone other custom state or bindings. */ + public static Microblock recreateForSide(Microblock source, boolean client) { + MicroblockClass microClass = source.microClass(); + int material = source.material(); + byte shape = source.shape(); + Microblock created = MicroblockGenerator.create(microClass, material, client); + created.setShape(shape >> 4, shape & 0xF); + return created; + } +} diff --git a/src/functionalTest/java/codechicken/multipart/test/MicroblockGeneratorFunctionalTest.java b/src/functionalTest/java/codechicken/multipart/test/MicroblockGeneratorFunctionalTest.java index 2d8fe8a..ce9e486 100644 --- a/src/functionalTest/java/codechicken/multipart/test/MicroblockGeneratorFunctionalTest.java +++ b/src/functionalTest/java/codechicken/multipart/test/MicroblockGeneratorFunctionalTest.java @@ -26,10 +26,54 @@ import codechicken.microblock.MicroblockClass; import codechicken.microblock.MicroblockGenerator; import codechicken.microblock.MicroblockGenerator$; import codechicken.multipart.TileMultipart; +import codechicken.multipart.examples.MicroblockCreationExample; import scala.Tuple2; class MicroblockGeneratorFunctionalTest { + @Test + void javaExampleCapturesSourceShapeBeforeMaterialCallbacksRun() { + Microblock source = MicroblockGenerator.create(FaceMicroClass$.MODULE$, 0, false); + source.shape_$eq((byte) 0x25); + Tuple2[] materials = MicroMaterialRegistry.getIdMap(); + Tuple2 original = materials[0]; + IMicroMaterial material = (IMicroMaterial) Proxy.newProxyInstance( + getClass().getClassLoader(), + new Class[] { IMicroMaterial.class, MicroblockGenerator.IGeneratedMaterial.class }, + (proxy, method, args) -> { + if ("addTraits".equals(method.getName())) source.shape_$eq((byte) 0x51); + return defaultValue(method.getReturnType()); + }); + materials[0] = new Tuple2<>(original._1(), material); + try { + Microblock created = MicroblockCreationExample.recreateForSide(source, false); + assertEquals(0x25, created.shape()); + assertEquals(0x51, source.shape(), "Material callbacks can have side effects"); + } finally { + materials[0] = original; + MicroblockGenerator.freshBitSet(); + } + } + + @Test + void javaExamplePreservesEveryShapeByteWithoutCopyingBindingsOrChangingTheSource() { + Microblock source = MicroblockGenerator.create(FaceMicroClass$.MODULE$, 0, false); + TileMultipart sourceTile = new TileMultipart(); + source.bind(sourceTile); + for (int shape = Byte.MIN_VALUE; shape <= Byte.MAX_VALUE; shape++) { + source.shape_$eq((byte) shape); + Microblock created = MicroblockCreationExample.recreateForSide(source, false); + assertNotSame(source, created); + assertSame(source.getClass(), created.getClass()); + assertSame(source.microClass(), created.microClass()); + assertEquals(source.material(), created.material()); + assertEquals((byte) shape, created.shape()); + assertNull(created.tile()); + assertSame(sourceTile, source.tile()); + assertEquals((byte) shape, source.shape()); + } + } + @Test void staticAndCompanionReflectionCreateFreshPartsBeforeCallerOwnedShapeLoading() throws Exception { MicroblockClass factory = FaceMicroClass$.MODULE$; diff --git a/src/main/scala/codechicken/microblock/MicroblockGenerator$.java b/src/main/scala/codechicken/microblock/MicroblockGenerator$.java index 38c4653..762c0c5 100644 --- a/src/main/scala/codechicken/microblock/MicroblockGenerator$.java +++ b/src/main/scala/codechicken/microblock/MicroblockGenerator$.java @@ -40,6 +40,10 @@ public final class MicroblockGenerator$ extends ASMMixinFactory impl return ScratchBitSet$class.freshBitSet(this); } + /** + * Retained companion entry for compiled and reflective consumers. Java callers can use + * {@link MicroblockGenerator#create(MicroblockClass, int, boolean)} with the same construction contract. + */ public Microblock create(MicroblockClass microClass, int materialId, boolean client) { BitSet traits = freshBitSet(); traits.set(microClass.baseTraitId()); diff --git a/src/main/scala/codechicken/microblock/MicroblockGenerator.java b/src/main/scala/codechicken/microblock/MicroblockGenerator.java index af8c304..445160f 100644 --- a/src/main/scala/codechicken/microblock/MicroblockGenerator.java +++ b/src/main/scala/codechicken/microblock/MicroblockGenerator.java @@ -6,8 +6,18 @@ import scala.collection.Seq; public final class MicroblockGenerator { + /** Optional material capability for adding registered traits before a microblock is constructed. */ public interface IGeneratedMaterial { + /** + * Adds material-specific traits to the borrowed generator scratch set, which already contains the factory's + * base trait and, on the client path, its client trait. Add registered trait IDs without removing required + * traits. Do not retain this mutable set or recursively create a microblock from this callback: the next + * creation on this thread clears and reuses the same set. Exceptions propagate without rolling back changes. + * + * @param microClass the exact factory supplied to create + * @param client the requested construction side, not a world lookup + */ void addTraits(BitSet traits, MicroblockClass microClass, boolean client); } @@ -42,6 +52,27 @@ public final class MicroblockGenerator { return MicroblockGenerator$.MODULE$.freshBitSet(); } + /** + * Constructs a fresh, unbound microblock using the factory's registered traits and an ID from the active material + * map. Selects the base trait, then the client trait if requested, then invokes the material's + * {@link IGeneratedMaterial#addTraits(BitSet, MicroblockClass, boolean)} callback if implemented. Generated classes + * are cached, but part instances are new and their trait initializers run for each construction. + * + *

+ * Does not copy another part, load NBT, assign shape, bind to a tile or install anything in a world. Callers + * restore shape or load NBT before preparing/loading the composite tile. Resolve the intended material before + * construction; subsequently changing a part's material field does not regenerate its material-specific traits. + * + *

+ * Call on the initialization/game thread after factory/trait registration and material-map setup. On multiplayer + * clients use the active synchronized material IDs. Client microblock construction requires the physical client; + * the dedicated server strips client-only factory methods. Null factories, invalid/unresolved IDs and callback or + * construction failures propagate through the existing generator. No fallback or rollback is added. + * + * @param microClass factory whose registered traits define the microblock family + * @param material numeric ID in the active material map, not a persistent saved identifier + * @param client true for client traits, false for server traits + */ public static Microblock create(MicroblockClass microClass, int material, boolean client) { return MicroblockGenerator$.MODULE$.create(microClass, material, client); }