[Target 2.10+] Port ForgeMultipart to Java. Checkpoint with binary compatibility preserved for safe consumers port. (#59)

This commit is contained in:
Algent authored and GitHub committed 2026-11-17 18:43:29 +01:00
1 parent 264aa16cf0
commit 3b181eb231
618 files changed
+61535 -9991

No files matched your search

+75
View File
@@ -0,0 +1,75 @@
# 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`.
## 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<Block>`; `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
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`.
+61
View File
@@ -0,0 +1,61 @@
# Multipart button orientations
[Java API index](../API.md)
`ButtonPart.setOrientation(int, ForgeDirection)` maps a button's orientation metadata to the multipart face it
occupies. It updates the metadata-to-face and face-to-metadata lookups together, so placement, face slots, support
checks and strong redstone output continue to agree.
Et Futurum Requiem can enable its floor and ceiling button metadata during common initialization with direct calls:
```java
ButtonPart.setOrientation(0, ForgeDirection.UP);
ButtonPart.setOrientation(5, ForgeDirection.DOWN);
```
The [compiling example](../../src/functionalTest/java/codechicken/multipart/examples/ButtonOrientationExample.java)
contains the same two calls.
## Metadata and face meaning
Pass only the orientation metadata from the low three bits, from `0` through `7`. Do not include bit `8`, which records
the pressed state, or bit `16`, which selects a wooden button. The face is the standard Forge direction returned by
`ButtonPart.getFace()`: `UP` for a ceiling button and `DOWN` for a floor button. `UNKNOWN`, `null` and out-of-range
metadata are rejected with `IllegalArgumentException` before either map changes.
The mapping is one-to-one. Setting an existing metadata value to another face clears its old reverse entry; assigning
a face already used by another metadata value clears that old forward entry. Repeating an existing pair is harmless.
Call the method during common mod initialization on each physical side, before worlds load button parts or players can
place them. The mappings are process-global. Changing one later also changes how existing button metadata is
interpreted for slots, support and redstone notification, so runtime reconfiguration is unsupported.
This method does not define a vanilla button block's bounds. `ButtonPart` captures all 16 button block bounds during
class initialization, after normal class transformations; a mod adding metadata orientations must still make its
button block expose the matching bounds.
## Reading orientation metadata
`ButtonPart.metaForSide(int)` returns the current metadata for an attachment face index (`0` through `5`), including
`-1` for an unmapped face. It reads the live inverse mapping, so both `setOrientation` and legacy array mutations or
replacement remain visible. Invalid indices throw `IndexOutOfBoundsException`; the accessor does not mask indices,
check world support, construct a part or reject an unmapped result on the caller's behalf.
ProjectRed's `ItemPartButtonCommons.newPart` can replace `ButtonPart.sideMetaMap(side ^ 1)` with:
```scala
val b = getNewInst(ButtonPart.metaForSide(side ^ 1))
```
Keep its existing vertical-face rejection, support check, custom factory and `onPlaced` call. Here `side` is the
clicked face, so `side ^ 1` is the attachment face. `sideForMeta` performs the opposite lookup;
`ButtonPart.placement` is not a replacement because it constructs an ordinary button and applies its own validation.
## Migrating Et Futurum Requiem
Replace the reflective reads, four array writes and reflective field assignments with the two calls above. Do not
catch and ignore API failures: an invalid metadata or direction is a configuration error that should remain visible.
Keep Et Futurum's existing FMP presence/version gate so older FMP versions never load the typed compatibility class.
The public mutable `metaSideMap` and `sideMetaMap` fields remain binary and reflective compatibility surfaces for old
releases. New integrations should not read, replace or mutate them directly.
+59
View File
@@ -0,0 +1,59 @@
# Building client multipart previews
[Java API index](../API.md)
Use `MultipartHelper.createPreviewTileFromNBT(World, NBTTagCompound)` to rebuild saved multipart NBT as an
uninstalled client tile. It replaces the registry reflection, client-part promotion, Scala collection conversion,
composite generation and manual loading previously needed by preview integrations.
```java
TileMultipart preview = MultipartHelper.createPreviewTileFromNBT(clientWorld, savedTile);
if (preview == null) {
return false;
}
return MultipartRenderer.renderWorldBlock(
blockAccess, x, y, z, multipartBlock, multipartBlock.getRenderType(), renderBlocks);
```
The [compiling example](../../src/functionalTest/java/codechicken/multipart/examples/ClientPreviewExample.java) uses
only Java API types. Keep this code in a client integration class because `MultipartRenderer` is client-only.
## Reconstruction contract
The helper accepts only a `savedMultipart` tag with at least one supported part. It preserves part order, loads each
part from its original tag, generates the required client tile traits, restores tile coordinates and NBT state, and
binds the parts. With a client world it then calls `onWorldJoin`, broadcasts a local part change, marks the render and
rebuilds the client render cache. With a null world it creates a worldless staged preview; render caches initialize
lazily.
A non-null world must have `isRemote == true`. The helper does not validate placement, install the tile in a chunk,
notify neighbors, recalculate lighting or send packets. It reads the supplied NBT without mutating it.
Reconstruction is all-or-nothing. A foreign or empty tag, missing factory, or factory that does not support preview
construction returns null. Factory, part loading and generated-trait failures propagate.
## Factory support
`IPartFactory2.createPartForClientPreview(String, NBTTagCompound)` constructs the client variant needed for saved NBT.
The default returns null, so an existing packet-aware factory does not accidentally treat NBT as a description
packet. Override it when the factory can return a fresh, unbound client part without consuming or changing the tag:
```java
@Override
public TMultiPart createPartForClientPreview(String name, NBTTagCompound tag) {
return new ExamplePart();
}
```
The helper calls `part.load(tag)` afterward. Legacy Boolean and Scala-function factory adapters already route preview
construction through their client branch. Built-in microblock factories resolve the saved material name and construct
the generated client microblock before loading its shape and other state.
## Consumer migration
- Schematica can replace its private registry map, `MicroblockClass.create`, Scala iterable conversion, companion
generator, reflected loader and per-part refresh loop with this helper.
- GuideNH can replace its server-tile reconstruction, `TileMultipartClient` promotion, microblock promotion and
Scala reload/finalization with this helper. Its material export and part statistics already use typed Java traversal.
Keep the old reflection fallback only while supporting an older FMP release that lacks this API.
+83
View File
@@ -0,0 +1,83 @@
# Staged composite-tile generation
[Java API index](../API.md)
`MultipartGenerator.generateCompositeTile(TileEntity, java.lang.Iterable<TMultiPart>, boolean)` selects a tile's
generated capabilities without loading its parts. The [compiling example](../../src/functionalTest/java/codechicken/multipart/examples/CompositeGenerationExample.java)
then assigns world/position and loads the same parts, leaving installation to its caller.
```java
TileMultipart prepared = MultipartGenerator.generateCompositeTile(candidate, parts, client);
// Prepare world, coordinates and any required tile NBT before loading.
prepared.loadPartList(parts);
```
Use a `List<TMultiPart>` or another repeatable collection when the same parts will subsequently be loaded. Generation
accepts `Iterable<TMultiPart>`; loading accepts `Collection<TMultiPart>`. A one-shot iterable can select traits, but
cannot then supply the same parts again. The generator reads the input once on every call, including candidate reuse,
without copying it. Do not mutate it during generation or change the required capabilities between generation and loading.
## Selection and ownership
| Candidate and required traits | Result |
| --- | --- |
| Null or a non-multipart tile | A fresh empty generated tile |
| Registered multipart class with exactly the required trait set | The same tile, with all existing state untouched |
| Registered multipart class with a different trait set or side | A fresh empty replacement; the candidate remains untouched |
| Multipart class unknown to the generator | `NoSuchElementException`, after reading the parts |
An empty iterable is valid and chooses the side's base tile. Order and duplicate parts do not add extra copies of a
trait, but each input entry is visited. The generator caches constructed classes; fresh tiles are still distinct objects.
Generation does not load or bind parts, assign world/position, copy source state, invalidate an old tile, install a
replacement or send notifications. New tiles have empty part storage and caches. Existing part-to-tile bindings remain
until the caller loads/rebinds them; loading a replacement does not clear the old tile's stored list.
Call after trait registration on the initialization/game thread. Trait selection uses existing caches and scratch
state. Iterator exceptions, null inputs/elements and unregistered-class failures propagate without rollback of that
internal state. Generation is neither a placement check nor a transaction for replacing a live tile.
## Side and loading lifecycle
`client=true` selects client tile capabilities. It does not turn server parts into client part variants; supply the
correctly constructed parts yourself. The world assigned for loading must agree with the intended side. The example
also allows null for explicitly worldless staging, which omits world-dependent loading callbacks.
Prepare position, world and any required tile NBT before [loading](PART_LOADING.md). With a world, the default loader
notifies parts and neighbors and updates lighting; a client world also triggers `onWorldJoin`. Preserve the integration's
subsequent installation, tile/render notifications and synchronization. Do not add them blindly to a worldless preview.
For ordinary world placement use `TileMultipart.canPlacePart` / `addPart`. For immediate server construction and
loading, the existing `MultipartHelper.createTileFromParts` remains supported. It is not a substitute for consumers
that must set state between generation and loading.
## Schematica and GuideNH migration
For saved-NBT client previews, prefer the complete [client preview helper](CLIENT_PREVIEW.md). It owns client part
construction, generation, loading and local render preparation. Use this lower-level generator for reconstruction
flows that need to prepare or reuse a candidate tile themselves.
Prefer the direct call `MultipartGenerator.generateCompositeTile(candidate, parts, client)`, as in the compiling
example. Gate optional typed integration code as described in the [API index](../API.md#direct-calls-and-optional-integration).
For temporary interoperability with an existing reflective integration, the method can also be resolved with:
```java
Method generate = MultipartGenerator.class.getMethod(
"generateCompositeTile", TileEntity.class, java.lang.Iterable.class, boolean.class);
TileMultipart tile = (TileMultipart) generate.invoke(null, candidate, parts, client);
```
An optional integration can obtain the owner through `Class.forName("codechicken.multipart.MultipartGenerator")`.
Pass a Java list directly and cache the method during integration initialization.
- **Older Schematica integrations:** remove `JavaConversions.collectionAsScalaIterable` from generation; keep material resolution,
[factory lookup](FACTORY_LOOKUP.md), side-specific microblock construction, per-part NBT loading and rejection when
any part is missing. Preserve its following tile `readFromNBT`, `loadPartList(parts)` and per-part notification order.
- **Older GuideNH integrations:** keep promotion of parts to their client variants, then use a Java list for generation. Preserve its
same-instance branch, copying of coordinates/world/block state, storage assignment where required, loading,
`notifyTileChange` and `markRender`. Generation does not perform any of those steps automatically.
The old companion's `generateCompositeTile(TileEntity, scala.collection.Iterable, boolean)` keeps its descriptor and
body, deprecated for callers in favor of the static Java entry. Existing direct calls and Schematica's exact
reflective lookup remain valid. GuideNH's separate microblock-generator call has an
[existing Java replacement](MICROBLOCK_CREATION.md).
+91
View File
@@ -0,0 +1,91 @@
# Writing and placing a custom part
[API index](../API.md) · [Factory registration](PART_REGISTRATION.md)
This guide connects the ordinary custom-part lifecycle from registration through placement, saved state, client
state and removal. The [compiling example](../../src/functionalTest/java/codechicken/multipart/examples/PartRegistrationExample.java)
uses one integer as representative state; replace its empty geometry and rendering with the capabilities your part
needs.
Existing part binaries remain supported; use the [release notes](../RELEASE_NOTES.md) when rebuilding source.
## Register and construct
Give every published part type a stable persistent ID and register its factory during common `preInit` or `init`, on
both client and server:
```java
MultiPartRegistry.registerPartFactory(new PartRegistrationExample(), "yourmod:part");
```
The factory returns a fresh, unbound part. It should select the implementation, not finish loading it: FMP calls
`load` after the NBT factory path and `readDesc` after the packet factory path. Preserve existing IDs and packet
prefixes when migrating. See [factory registration](PART_REGISTRATION.md) for payload ownership and failure ordering.
A basic part extends `TMultiPart`, returns its registered ID from `getType()`, and overrides only the capabilities and
callbacks it needs. The base class ticks by default, so a part without per-tick logic should return `false` from
`doesTick()` as the example does. Add collision/ray-trace boxes, drops, rendering, slots, redstone or other capability
interfaces according to the part's real behavior.
## Place on the server
Choose the target from the item or interaction, then check and place on the server:
```java
TileMultipart tile = PartRegistrationExample.place(world, pos, initialValue);
if (tile == null) {
return false;
}
```
The example returns null on the client or when `TileMultipart.canPlacePart` rejects the candidate. A successful
`TileMultipart.addPart` installs or updates the generated container, binds the part, calls `onAdded`, notifies the
world and clients, and returns the current tile. Retain that return value: adding a capability can replace a previous
tile instance. A successful `canPlacePart` is only a check; do not mutate inventory or other durable state until
`addPart` succeeds.
## Persist and synchronize state
Use separate callbacks for disk and network state:
| Purpose | Write | Read | When |
| --- | --- | --- | --- |
| Saved server state | `save(NBTTagCompound)` | `load(NBTTagCompound)` | World save and server reconstruction |
| Initial client state | `writeDesc(MCDataOutput)` | `readDesc(MCDataInput)` | Chunk description and part addition |
| Later client changes | `sendDescUpdate()` | Base `read` calls `readDesc` | Buffered part update |
The example's `setValue` is server-owned and performs the three actions needed because its value is assumed to affect
all three concerns:
```java
sendDescUpdate();
tile().notifyPartChange(this);
tile().markDirty();
```
`sendDescUpdate` synchronizes the description payload; the base client `read` then calls `readDesc` and marks the tile
for rendering. `notifyPartChange` calls sibling-part callbacks and updates the block, neighbors and lighting.
`markDirty` requests persistence. Use only the calls the changed state requires, but keep packet reads exactly
symmetric with writes. Run authoritative mutation on the server; the client applies network state in `readDesc` or a
custom `read` implementation.
## Lifecycle callbacks
`onAdded` / `onRemoved` describe placement and removal. Their base implementations call `onWorldJoin` /
`onWorldSeparate`. Server chunk load/unload and movement can call the world-level hooks again, while initial client
reconstruction calls `onWorldJoin` without `onAdded`. Put repeatable external-network registration in the world-level
hooks, and one-time placement/removal effects in the narrower hooks. Preserve the base call when overriding a narrow
hook unless deliberately replacing its world-level behavior.
`preRemove` runs before the part leaves storage and before its binding is cleared. Remove on the server and retain the
returned tile because dropping the last capability can replace the container, while removing the final part returns
null after the block is removed:
```java
TileMultipart current = part.tile();
TileMultipart replacement = current.remPart(part);
```
Ordinary placement and removal already perform container synchronization and notifications. The generation,
`setPartList` and `loadPartList` APIs are for controlled reconstruction and have different ownership rules; see
[part loading](PART_LOADING.md) and [composite generation](COMPOSITE_GENERATION.md) before using them.
+134
View File
@@ -0,0 +1,134 @@
# Custom generated tile traits from Java
[API index](../API.md) · [Stable capability access](TILE_TRAIT_ACCESS.md) · [Composite generation](COMPOSITE_GENERATION.md)
A custom tile trait adds behavior to every generated `TileMultipart` that contains a part implementing a chosen marker
interface. Use it for tile-wide aggregation or lifecycle behavior. If the tile only needs to expose one interface and
forward its methods to one implementing part, use `MultipartGenerator.registerPassThroughInterface` instead; FMP
already generates that forwarding and rejects a second implementor through occlusion.
The complete compiling example has four small types:
- [CustomTileTraitPart.java](../../src/functionalTest/java/codechicken/multipart/examples/CustomTileTraitPart.java) is
the marker and contribution contract implemented by requesting parts.
- [CustomTileTraitCapability.java](../../src/functionalTest/java/codechicken/multipart/examples/CustomTileTraitCapability.java)
is the stable interface used by callers.
- [CustomTileTrait.java](../../src/functionalTest/java/codechicken/multipart/examples/CustomTileTrait.java) is the raw
input class FMP transforms, plus its ordinary helper.
- [CustomTileTraitExample.java](../../src/functionalTest/java/codechicken/multipart/examples/CustomTileTraitExample.java)
registers and accesses the capability.
These files live in the functional-test source set and are examples, not classes shipped in the production artifact.
## Registration and selection
Register during common mod initialization, before FMP first inspects any part class implementing the marker:
```java
private static final String TRAIT = "example.multipart.ContributionTileTrait";
public static void register() {
MultipartGenerator.registerTrait(ContributionPart.class.getName(), TRAIT);
}
```
Keep the trait name as a string literal. `ContributionTileTrait.class.getName()` loads the untransformed class before
FMP can rewrite it. The marker is an ordinary interface, so its class literal is safe. Names may contain dots or
slashes.
The two-argument overload installs the same trait on client and server generated tiles. Use
`registerTrait(marker, clientTrait, serverTrait)` when the sides differ; either trait name may be null. The order is
client first, then server. Register a parent Java trait before a child trait.
Registration is global for the running game. A second mapping for the same marker and side logs an error and leaves
the first mapping active. Registration loads and validates the trait bytes, so missing or invalid traits fail at that
point. It does not register a part type, construct a tile, load parts or bind ownership.
When FMP first sees a concrete part class, it records every registered marker that class implements. Composite classes
are then cached by the exact selected trait set and side. Registering after that inspection is too late for the cached
part class.
## Trait and stable capability
The transformed input is a top-level class extending `TileMultipart`. It may be abstract and needs a no-argument
constructor. Put the API that other code calls on a separate ordinary interface:
```java
public interface ContributionTileCapability {
int totalContribution();
}
public abstract class ContributionTileTrait extends TileMultipart
implements ContributionTileCapability {
@Override
public int totalContribution() {
return ContributionTileTraitAccess.total(this);
}
}
```
At runtime FMP rewrites `ContributionTileTrait` into an interface and copies its method bodies into a generated helper.
Calling through the untransformed class can therefore emit invalid class method or field bytecode. Callers use the
stable capability instead:
```java
int total = tile instanceof ContributionTileCapability
? ((ContributionTileCapability) tile).totalContribution()
: 0;
```
Keep the absent-capability behavior in the caller-facing helper. The example returns zero for null and ordinary tiles.
Adding or removing a requesting part may replace the tile with another generated class, so retain the tile returned by
FMP's normal placement and removal APIs.
## Transformer-safe method bodies
The current Java trait transformer supports the example's small delegating method. Keep substantial work in an
ordinary top-level helper outside the transformed class:
```java
final class ContributionTileTraitAccess {
static int total(Object receiver) {
TileMultipart tile = (TileMultipart) receiver;
int total = 0;
for (TMultiPart part : tile.jPartList()) {
if (part instanceof ContributionPart) {
total += ((ContributionPart) part).contribution();
}
}
return total;
}
}
```
The helper parameter must be `Object`. If it is typed as the raw trait, javac can remove the cast to `TileMultipart`;
after transformation the verifier then sees an interface receiver where the bytecode expected a class. The helper is
also where inherited field/method access and field access on method arguments belong, because the transformer can
otherwise mistake those reads for trait-owned state.
Keep the transformed class free of nested, local and anonymous classes, lambdas and compiler-generated inner-class
helpers. Primitive-array allocation is also unsupported in a trait body. Put those operations in the ordinary helper.
Client-only members may use Forge's `@SideOnly(Side.CLIENT)`; FMP removes opposite-side members before collecting the
trait. Test the resulting generated class on each selected side.
## State and lifecycle
Prefer derived behavior when it is cheap enough. The example sums the current `jPartList()` and owns no tile state,
which avoids NBT, packet, invalidation and transition rules.
If a trait declares fields, FMP generates `copyFrom(TileMultipart)` when the trait does not declare one. It copies each
non-transient field only when the source tile has the same trait; transient fields are excluded. Persistent or
client-synchronized state still needs explicit NBT/description handling. A custom `copyFrom` replaces the generated
field copier, so it must preserve the normal superclass chain and define behavior for sources without the trait.
Cached aggregates must also follow every lifecycle path that can change them. Override the relevant `bindPart`,
`partRemoved` and `clearParts` hooks, call `super` in the established order, and cover tile promotion/demotion and
loading with a focused Forge test. Do not use a custom cache unless measurement shows the derived scan is too costly.
`MultipartGenerator.generateCompositeTile` only chooses or constructs the empty composite class. If using that advanced
API directly, prepare world/position or saved state and then call `loadPartList`; ordinary placement performs the
required transition itself. See the [staged generation guide](COMPOSITE_GENERATION.md) for ownership and failure rules.
[CustomTileTraitFunctionalTest.java](../../src/functionalTest/java/codechicken/multipart/test/CustomTileTraitFunctionalTest.java)
shows how to register a trait during Forge initialization and assert selection and dispatch on both sides.
+68
View File
@@ -0,0 +1,68 @@
# Registered part factory lookup
[Java API index](../API.md)
`MultiPartRegistry.getPartFactory(String)` returns the registered `IPartFactory2` for an exact part type name, or
`null` when no factory is mapped.
```java
IPartFactory2 factory = MultiPartRegistry.getPartFactory("mcr_face");
```
Lookup is case-sensitive, uses string equality and reads the current registration map. It neither constructs a part,
logs unknown names, waits for registration nor changes registry state. It does not depend on the numeric network ID
map. Look up after the owning mod has registered its types, on the initialization/game thread; no synchronization is
added. Use published, non-null type names.
The result is the exact registered factory instance, not a copy or a mutable registry view. Do not modify its state.
Registration remains the job of [`registerPartFactory`](PART_REGISTRATION.md); lookup does not expose a replacement,
removal or enumeration operation. An earlier lookup result does not update itself if registry state later changes.
## Choose the construction path
Most consumers should continue using `loadPart(name, nbt)` or `readPart(input)`. Those choose the registered factory's
NBT/server or packet/client method. Their caller still invokes `part.load(nbt)` or `part.readDesc(input)`, respectively,
and later binds/places the part. See [factory and payload contracts](PART_REGISTRATION.md).
Factory lookup is useful when a supported factory subtype provides a specialized construction method. Older Schematica
looks up a `MicroblockClass` and calls `create(client, materialId)` before loading the saved microblock NBT. Calling
`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.
New preview integrations should use the complete [client preview helper](CLIENT_PREVIEW.md). See
[microblock creation](MICROBLOCK_CREATION.md) when a caller specifically needs an unbound microblock.
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
factory selection and construction, not a complete schematic loader. Its null result for an unsupported type must
cause the whole preview to be rejected when matching Schematica's all-parts-required policy.
## Migrating Schematica's optional reflection
Prefer direct `MultiPartRegistry.getPartFactory(partID)` calls, as in the compiling example above. Isolate typed
optional integration code behind mod-presence/version checks; see the [direct-call policy](../API.md#direct-calls-and-optional-integration).
The following is only a legacy interoperability option for a consumer retaining reflection temporarily. It replaces
the companion singleton/private-field lookup and Scala `Map.get` / `Option` handling:
```java
Class<?> registry = Class.forName("codechicken.multipart.MultiPartRegistry");
Method lookup = registry.getMethod("getPartFactory", String.class);
Object factory = lookup.invoke(null, partID);
if (factory == null) {
return null; // Keep the caller's missing-part rejection.
}
```
Cache the `Method` during integration initialization as Schematica already does. Continue resolving
`MicroblockClass.create(boolean.class, int.class)` with its exact parameter types and invoking it on this factory.
Not every registered factory is a microblock class: keep the existing rejection of an unsupported factory, or check
the reflected microblock class's `isInstance(factory)` explicitly before invoking. Do not silently produce a partial preview.
This removes only the registry-map Scala dependency. The [client preview helper](CLIENT_PREVIEW.md) replaces the
complete Schematica reconstruction path when the minimum FMP version can require it.
The private `MultiPartRegistry$.codechicken$multipart$MultiPartRegistry$$typeMap` field keeps its exact name, modifiers,
Scala mutable-map type and live backing, so existing binary/reflection callers keep working.
Client microblock creation only works on a physical client: a dedicated server strips `clientTrait()`.
+40
View File
@@ -0,0 +1,40 @@
# Struck part index
[API index](../API.md)
`BlockMultipart.hitPartIndex(MovingObjectPosition)` returns the index of the part a multipart ray trace struck, or
`-1` if the hit carries no part index.
```java
int index = BlockMultipart.hitPartIndex(hit);
List<TMultiPart> parts = tile.jPartList();
TMultiPart struck = index >= 0 && index < parts.size() ? parts.get(index) : null;
```
See the [compiling example](../../src/test/java/codechicken/multipart/examples/HitPartExample.java).
## Where the index comes from
`TileMultipart.rayTraceAll` asks each part in `jPartList()` order for its own hit. It then wraps each hit's data as
`(index, partData)`, so a part that misses still uses up its index. `collisionRayTrace` returns the nearest of those
hits. A hit from `BlockMultipart.collisionRayTrace` or `RayTracer.retraceBlock` on a multipart block goes through the
same path.
The index refers to the tile's part list when the trace ran. Adding or removing parts afterwards makes it stale, so
retrace rather than keeping a hit across ticks. The method reads only the hit. It does not check coordinates, look
up a tile or bounds-check the index. Retrieve the tile at the hit's block yourself, as the example does.
`-1` means the hit is null, a plain `MovingObjectPosition`, or an `ExtendedMOP` whose data is not FMP's index pair.
For example, another mod's tile can produce an `ExtendedMOP` with its own data.
## Legacy compatibility
`BlockMultipart.reduceMOP(MovingObjectPosition)` and its companion entry remain unchanged and are not deprecated.
They return a `scala.Tuple2` of the boxed `Integer` index and a copy of the hit rebased onto the part's own data.
FMP's activation, click, harvest, hardness, hit-effect, pick-block and highlight dispatch uses the rebased hit; there is no Java replacement for it
because no consumer needs one.
GT5U `5.09.54.205` reads `(Integer) BlockMultipart.reduceMOP(hit)._1()` to recolor ProjectRed wires. That call
can become `hitPartIndex(hit)` with the same value and no Scala types. Keep the existing `hit instanceof ExtendedMOP`
and coordinate checks, which protect the tile lookup. The released GT5U jar keeps linking the `Tuple2` descriptor,
which stays until a migrated release is in the target pack.
+49
View File
@@ -0,0 +1,49 @@
# Read a microblock's block and metadata
[Java API index](../API.md)
Use the existing public `BlockMicroMaterial.block()` and `meta()` methods. Neither reflection nor an accessor mixin
is needed. The [compiling Java example](../../src/functionalTest/java/codechicken/multipart/examples/MaterialAccessExample.java)
implements the primary-material query using GuideNH's filtering and metadata convention, with the failure and
accessor-order differences documented below:
1. Traverse `TileMultipart.jPartList()` in its stored order.
2. For each `Microblock`, resolve `material()` through `MicroMaterialRegistry.getMaterial(int)`.
3. If the result is a `BlockMicroMaterial`, read `block()` then `meta()`.
4. Skip null/air blocks and absent/empty block registry names; return the first usable block ID.
For example, wool with metadata 14 exports as `minecraft:wool:14`. GuideNH appends a metadata suffix only when the
value is positive; zero and negative values export the unsuffixed block ID. This is GuideNH's export convention,
not a general material serialization format. The example preserves positive values above 15 without masking.
## Identity, lifecycle and overrides
- `block()` returns the constructor's block by identity in the base implementation, including null. `meta()` returns
the original integer unchanged. Both are public virtual methods; consumer calls must respect subclass overrides.
- A microblock's numeric `material()` value is an ID in the active material map, not block metadata. Query after
registry initialization and, on a client, material-ID synchronization. Do not persist these numeric IDs across
sessions; see [material enumeration](MATERIAL_ENUMERATION.md).
- `IMicroMaterial` does not promise a block/meta representation. Skip non-block materials for this block-only query;
do not cast every registered material to `BlockMicroMaterial` or infer its block from an item drop.
- `blockKey()` caches the constructor block's registry name. It can differ from an overridden `block()` and from
the material's registered name. Export the registry name of the returned block, as the example does.
- This is a read operation with no binding, world access, material registration or tile mutation. Observe the
[part-list ownership contract](PART_TRAVERSAL.md#collection-ownership-and-ordering); the traversal is not a snapshot.
## GuideNH migration
GuideNH 1.3.33 onward already uses direct part traversal, material lookup and public getters in
`resolvePrimaryMicroblockId`, without the `AccessorBlockMicroMaterial` mixin. FMP's private fields stay unchanged for
older GuideNH releases.
The old mixin reads constructor fields directly, bypassing overrides. The old reflection fallback already calls
the public virtual getters. The supported typed path follows those getters too, so custom materials that override
them may produce a different export from the mixin. Validate those materials in GuideNH; do not introduce raw-field
accessors to preserve an implementation detail that disagrees with the material's public behavior.
The example returns null for a null/non-multipart tile or no usable block. Invalid material IDs and exceptions from
custom accessors propagate. Current GuideNH instead catches runtime failures during material lookup, logs and
continues to the next part; getter failures propagate. It reads metadata only after accepting the block and registry
name, and calls `meta()` twice for positive values. The example reads metadata once, before the null/air check.
These differences matter for failing or stateful custom getters; the example is not a drop-in copy of current
GuideNH's failure/accessor-order policy. Validate any intentional change during migration.
+62
View File
@@ -0,0 +1,62 @@
# Enumerating microblock materials from Java
[API index](../API.md)
Use `MicroMaterialRegistry.materialCount()` with the existing `materialName(int)` and `getMaterial(int)` methods to
enumerate materials without importing Scala types.
## Example
The following method copies the active material names in numeric ID order:
```java
public static List<String> materialNames() {
int count = MicroMaterialRegistry.materialCount();
List<String> names = new ArrayList<>(count);
for (int id = 0; id < count; id++) {
names.add(MicroMaterialRegistry.materialName(id));
}
return names;
}
```
Imports and the enclosing class are in the [compiling example](../../src/test/java/codechicken/microblock/examples/MaterialEnumerationExample.java).
Use `MicroMaterialRegistry.getMaterial(id)` in the loop when you also need the `IMicroMaterial`, for example to obtain
its item. That returns the registered instance, not a copy.
The example's list is an independent copy; editing it does not change the registry.
## Timing, order and identity
- Enumerate after ForgeMicroblock has built its ID map during post-initialization. A consumer's own post-init handler
needs suitable mod ordering if it enumerates there; later lifecycle/game callbacks can use the initialized map.
Consumers must not call `setupIDMap()` themselves to force readiness.
- On a multiplayer client, enumeration of the connected server's IDs requires a completed, successful FMP handshake.
FMP also rebuilds the local map before server startup. Reacquire IDs after map replacement.
- Use the game/lifecycle thread. The calls are live lookups, not an atomic snapshot: do not rebuild the map or perform
registration/handshake work from inside an enumeration loop.
- Local setup orders IDs by material name. A multiplayer client adopts server order; do not sort or filter IDs when
preserving a mapping. Store material names in saved data and resolve their numeric IDs for the active map.
- `materialCount()` counts ID slots, including the missing-material placeholder when present. It throws
`IllegalStateException` before initialization and returns zero for an initialized empty map.
- A failed handshake can leave unresolved slots. The count includes them; `materialName(id)` and `getMaterial(id)`
retain their existing `NullPointerException` for such slots. FMP disconnects the client for missing mappings.
The count is not a handshake-success indicator, and callers should not silently skip unresolved IDs.
- The existing indexed lookups throw `ArrayIndexOutOfBoundsException` outside the active ID range and
`NullPointerException` before map initialization.
## Migrating existing consumers
| Legacy expression | Java API |
| --- | --- |
| `getIdMap().length` | `materialCount()` |
| `getIdMap()[id]._1()` | `materialName(id)` |
| `getIdMap()[id]._2()` | `getMaterial(id)` |
| Loop over the tuple array | Loop over IDs from zero to `materialCount()`, exclusive |
For UtilitiesInExcess, apply this to `FMPRecipeLoader.run()` and `UEMultipartItem.getSubItems()`: replace each tuple
loop with an ID loop and use `materialName(id)` wherever the tuple name was used. Preserve its recipe/item ordering,
filters and material-name NBT. A material object, when needed, is available from `getMaterial(id)`.
Extra Utilities' NEI handlers use both tuple fields; both indexed replacements are available.
The static and companion `getIdMap()` methods are deprecated, with their original descriptors and live-array
behavior retained. The addition does not change packet or NBT formats.
+89
View File
@@ -0,0 +1,89 @@
# 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.
```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. The complete [client preview helper](CLIENT_PREVIEW.md) selects the registered factory's preview path
and performs the remaining tile reconstruction.
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. For a Java trait, see the
[illuminated microblock extension](MICROBLOCK_EXTENSIONS.md).
## GuideNH migration
GuideNH preview reconstruction should use the complete [client preview helper](CLIENT_PREVIEW.md). The direct
generator remains useful when code specifically needs to create or transform one unbound microblock.
GuideNH currently calls `MicroblockGenerator$.MODULE$.create(MicroblockClass, int, boolean)`; older releases resolved
that same call reflectively. Prefer the typed creation example, with [gated optional integration](../API.md#direct-calls-and-optional-integration). The following cache is only
a temporary interoperability option for consumers retaining reflection:
```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.
The example captures factory, material and shape before construction. Current GuideNH reads the source shape after
creation; material callbacks can have side effects, so that ordering can copy a callback-modified value. Preserve or
explicitly validate that policy when migrating custom materials.
Public `setShape` uses the virtual shape setter; current GuideNH already calls `shape_$eq` directly, while its older
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 has a separate [typed query guide](MATERIAL_ACCESS.md).
## Side limits
Use `client=true` on the physical client for client variants. Unlike generating a client tile container, client
microblock construction cannot run on a dedicated server: Forge strips `MicroblockClass.clientTrait()`.
The side parameter selects traits; it does not infer a world side or bypass Forge's side-only filtering.
+76
View File
@@ -0,0 +1,76 @@
# Extend generated microblocks from Java
[Java API index](../API.md)
Use `MicroblockGenerator.registerTrait(String)` with a Java source trait, then add its returned ID from an
`IGeneratedMaterial.addTraits` callback. The existing public API selects the Java compiler path automatically;
consumers do not need reflection, Scala types, companion lookup or direct compiler calls.
This example follows ProjectRed's illuminated microblock contract. It comprises three compiling Java files:
- [IlluminatedMicroblockTrait](../../src/functionalTest/java/codechicken/multipart/examples/IlluminatedMicroblockTrait.java):
the generated extension's dynamic-render flag, light value and client render callback.
- [IlluminatedMicroMaterial](../../src/functionalTest/java/codechicken/multipart/examples/IlluminatedMicroMaterial.java):
block-backed material and material-provided trait selection, including cutter metadata handling.
- [IlluminatedMicroblockExample](../../src/functionalTest/java/codechicken/multipart/examples/IlluminatedMicroblockExample.java):
registration, ordinary Java implementation, configuration supplier and halo-renderer adapter.
Copy/adapt these into the consumer's own package; update the literal registration name accordingly. They are example
sources in FMP's functional-test source set, not production classes shipped for consumers to depend on.
## Registration and compilation
1. Register the consumer's lamp block first. During mod initialization, call `registerMaterials(lamp)` once, on both
physical sides and before FMP creates the material-ID map. The helper registers the trait before materials.
2. Wire `dimLampParts` to a supplier of the consumer's current configuration. On the physical client, set
`haloRenderer` to its halo queue before rendering; ProjectRed can forward to `RenderHalo.addLight(x, y, z, colour, box)`.
Keep renderer-only dependencies out of common initialization. The helper supplies no renderer fallback.
3. Retain the consumer's existing material names, metadata 16 through 31, configuration defaults and block identity.
The test fixture uses its own lamp block; a real ProjectRed migration uses ProjectRed's registered lamp.
4. Create parts through the [public microblock creation API](MICROBLOCK_CREATION.md). The material adds the same
extension ID for every shape and both sides, without clearing the borrowed bit set. The generator also selects
the shape's built-in traits and client trait where applicable. Repeated construction reuses the generated class,
not the instance. Changing a part's material afterward does not regenerate its traits.
**Register the Java trait by name before loading it.** A Java class literal is appropriate for retained Scala
interfaces, but can load the untransformed Java input too early. Name-based registration is a supported generator
operation, not consumer reflection. IDs are local to this generator and must not be persisted or reused as tile-trait IDs.
The Java input extends `Microblock`, is abstract, and has a public no-argument constructor calling `super(0)`.
FMP discards that direct super call; the composite's real constructor receives the requested material ID. No extra
trait state is needed for this extension. Keep the input top-level, without nested/anonymous classes or lambdas.
After registration FMP rewrites that class into an interface. Do not instantiate it, subclass its raw class from
ordinary consumer Java, or invoke inherited members through that raw class type. `instanceof` works after
registration; dispatch uses stable `Microblock` methods. For new extension-specific methods, declare a separate
ordinary capability interface rather than emitting class calls against the transformed input.
The existing transformer cannot safely handle all inherited field/method accesses in a trait body. Its thin overrides
therefore delegate to an ordinary helper using an **Object parameter**, then cast to `Microblock` in that helper.
This forces the required runtime cast and keeps loops, allocation and callbacks outside the transformed input.
## Behavioral contract
- The dynamic-render flag is always true. The client callback submits halos only on pass zero. It uses the part's
tile coordinates, not the supplied camera-relative render position; colour is material metadata minus 16.
- Cutter strength asks the block for the harvest level at `meta() % 16`, preserving the illuminated metadata bit's
exclusion. Ordinary block/meta access remains virtual through the supported methods.
- With dimming enabled, collect all siblings carrying this extension, sum `getSize() / 8.0`, multiply by 15,
truncate to an integer, then cap at 15. Capture the matching parts before invoking size callbacks. With dimming
disabled, any matching sibling gives light 15, otherwise zero. Do not substitute volume for encoded size.
- Read `tile().jPartList()` without detached-part filtering: this preserves the reference's membership behavior.
The part must be bound before querying light; an unbound part fails rather than inventing a light value. Callback
failures propagate. This example adds no stored per-part state, NBT keys or packet fields.
- Ordinary halos copy collision boxes and expand them by 0.025; source boxes remain untouched. Hollow halos instead
use four rotated strips around the current connector opening. Their middle strips are trimmed along the opening,
so simply expanding hollow collision boxes does not reproduce the same geometry. Halo boxes are newly allocated
and may be retained by the renderer queue. Configuration and renderer access run on the owning game/render thread.
`@SideOnly(CLIENT)` belongs on the trait's render override. The common light flag/value remain present on the server.
The helper uses common geometry types, allowing headless verification; only the supplied halo renderer needs a client.
This is a behavior-preserving migration example, not a performance optimization or a replacement rendering engine.
## Migrating ProjectRed
Preserve ProjectRed's registration order and names, and wire its existing configuration and halo queue into the
example's hooks. Its existing external Scala trait keeps working until it migrates.
+58
View File
@@ -0,0 +1,58 @@
# Consumer migration checklist
[API index](../API.md) · [Java-port release notes](../RELEASE_NOTES.md)
Use this when rebuilding a mod against the Java-port artifact. It is a release checklist, not a replacement for the
method-specific guides linked from the API index.
## Before editing
- [ ] Inventory source and reflective references to `codechicken.multipart` and `codechicken.microblock`, including
inherited traits, companion objects, `$class` helpers and private fields.
- [ ] Preserve published part/material IDs, NBT keys and packet field order unless the change includes an explicit data
migration or protocol break.
- [ ] Identify the exact FMP artifact used to compile and run. New Java APIs on `algent/java` have no minimum published
version yet; require a release that actually contains every method used.
- [ ] If FMP is optional, keep FMP-typed code in a compatibility class loaded only after checking mod presence and a
supported version. Keep FMP types out of classes loaded unconditionally.
## Change the integration
- [ ] Prefer the documented direct API over companion lookup, private-field access or new reflection.
- [ ] Call generated tile behavior through `TileMultipart` or a stable capability interface such as `IRedstoneTile`,
`IInventory`, `ISidedInventory` or `IFluidHandler`. Do not compile method or field access against raw classes under
`codechicken.multipart.scalatraits` or `TileMultipartClient`; Forge transforms those classes into interfaces.
- [ ] For recompiled Scala traits, audit every method formerly supplied by trait linearization. A successful compile is
insufficient: Java superclass methods can silently win over interface defaults. Apply the explicit forwarders in
the [release notes](../RELEASE_NOTES.md#2-silent-behavior-changes-recompiled-scala-trait-composition).
- [ ] Use `canPlacePart` followed by `addPart` for normal server placement, and `remPart` for removal. Retain the tile
returned by additions/removals because generated capabilities can replace the container; final removal returns null.
- [ ] Use `save`/`load` for server persistence and `writeDesc`/`readDesc` or a symmetric custom update for clients.
Mark persistent state dirty, synchronize client-visible state and notify parts/neighbors only when that state needs
each effect. See the [custom-part lifecycle](CUSTOM_PARTS.md).
- [ ] Treat `generateCompositeTile`, `setPartList` and `loadPartList` as reconstruction operations. Follow their state,
binding, installation and notification responsibilities instead of substituting them for ordinary placement.
## Verify the rebuilt consumer
- [ ] Compile against the same FMP artifact required at runtime, then inspect the rebuilt bytecode for references to raw
transformed trait classes, removed Scala-shaped entry points and legacy private fields.
- [ ] Test optional integration with FMP absent and present. Test a dedicated server separately from a physical client;
headless Forge coverage does not establish client class stripping, rendering or GPU behavior.
- [ ] Load representative pre-migration saves and exercise placement, updates, removal, chunk reload and movement for
every changed part or integration. Verify NBT and packet state, generated capabilities and callback order.
- [ ] Run the rebuilt jar in the target pack with the actual interacting mods. Record manual limits instead of treating
source inspection or isolated tests as full-pack proof.
## Close adoption before removing compatibility
A source patch proves only that the migration was written. Keep the old bridge, descriptor, field or Scala runtime
path until all applicable gates are complete:
1. The consumer patch is merged and its rebuilt jar passes the checks above.
2. A consumer release containing that jar exists.
3. The target pack requires the compatible FMP and consumer releases.
4. A fresh consumer scan confirms no supported released jar still uses the legacy contract.
Documented Java entry points are intended to survive later Scala removal. Undocumented public members, raw transformed
classes and Scala-shaped bridges do not gain that guarantee merely because current source can call them.
+113
View File
@@ -0,0 +1,113 @@
# Testing occlusion from Java
[API index](../API.md)
`TileMultipart.testOcclusion(Collection<? extends TMultiPart>, TMultiPart)` tests a supplied collection of parts
through the tile's existing occlusion hook, including generated partial-occlusion checks. For raw geometry,
`NormalOcclusionTest.testBoxes(Iterable<? extends Cuboid6>, Iterable<? extends Cuboid6>)` tests two groups of bounding
boxes without constructing parts. See [box-versus-box queries](#box-versus-box-queries).
## Example
Use a `NormallyOccludedPart` to test a normal bounding shape against a supplied group of parts:
```java
public static boolean fitsShape(TileMultipart tile, Collection<? extends TMultiPart> parts, Cuboid6 bounds) {
return tile.testOcclusion(parts, new NormallyOccludedPart(bounds));
}
```
See the [complete Java example](../../src/test/java/codechicken/multipart/examples/OcclusionExample.java).
Collections of part subclasses, such as `List<NormallyOccludedPart>`, are accepted without a cast.
Pass `tile.jPartList()` to test against the tile's currently stored parts, or pass a separate collection for a preview
or selected subset. To exercise a real candidate's custom occlusion behavior, pass that part instead of the shape
wrapper. The wrapper represents normal bounding geometry, not all the capabilities of a custom part.
## What the query checks
The base tile tests each supplied part against the candidate, then tests the candidate against that same part. It
proceeds in input iteration order and stops immediately when either direction rejects. Unbound/detached parts and
duplicate entries participate; the candidate is not automatically excluded if it is also in the collection.
Generated partial-occlusion tiles retain their extra aggregate check. When the candidate implements `JPartialOcclusion`,
the existing trait checks the group plus the candidate before the ordinary pair callbacks. A plain `TileMultipart`
does not gain that capability just because the supplied parts need it. Use the appropriate composite tile; this method
does not generate or select tile traits.
This is an occlusion query, not full placement approval. It does not check placement permissions, duplicate membership,
slot occupancy or world replaceability, and does not bind/store parts or send notifications. For ordinary placement
and replacement, continue using `canPlacePart`, `canAddPart` and `canReplacePart` as appropriate. In particular,
`canReplacePart(outgoing, candidate)` performs its existing outgoing-part exclusion; this collection query does not.
## Ownership, callbacks and failures
The Java entry copies the input into an immutable sequence before calling the legacy hook. Order, duplicates, null
entries and part identities are preserved. Callback edits to the caller's collection do not change the current
query's sequence. Part objects are shared, so mutations of their state can affect later callbacks. A nested query
takes its own copy.
Copying failures, including a null collection, propagate before the legacy hook is called. There is no eager
candidate/null-entry validation: with the base implementation, an empty collection accepts even a null candidate,
and an early rejection can avoid a later null dereference. Callback exceptions propagate unchanged and stop the query;
callback side effects already performed are not undone. Overrides may add checks or customize these boundaries.
Use the game thread when querying live parts. A geometric query may invoke arbitrary part callbacks, including ones
that read or modify world/part state; it is not a thread-safety guarantee.
## Overrides and migration
Dispatch is `testOcclusion(Collection, candidate)` → virtual `occlusionTest(scala.collection.Seq, candidate)`.
The old method keeps its descriptor and body, and is deprecated for callers. Existing subclasses and generated traits
continue to override it. `canAddPart` and `canReplacePart` still call that hook directly; overriding only the new
Java method does not intercept their checks. The distinct Java name avoids introducing another Scala/Java overload
pair, following the [loader compilation finding](PART_LOADING.md#overrides-and-reflection).
Consumers such as ProjectRed and ForgeRelocationFMP already use the Java-typed `canReplacePart` API and need no rename
for that contract. Part-level `occlusionTest(TMultiPart)` remains supported as-is. The Scala `NormalOcclusionTest.apply`
box-versus-box entry is a separate, still-used contract with the Java replacement below.
## Box-versus-box queries
Use `NormalOcclusionTest.testBoxes` when you already have box iterables, including `getOcclusionBoxes()` results:
```java
public static boolean fitsBounds(Iterable<? extends Cuboid6> occupied, Cuboid6 candidate) {
return NormalOcclusionTest.testBoxes(occupied, Collections.singletonList(candidate));
}
```
See the [complete example](../../src/test/java/codechicken/multipart/examples/BoxOcclusionExample.java). Both
arguments accept box subclasses and need only implement Java `Iterable`.
The query fully consumes the first input, then the second, requesting each input's iterator once. It takes shallow
snapshots before testing any pairs, even when one input is empty or the first pair will overlap. Iteration failures
therefore take precedence over geometry results; a failure in the first input prevents reading the second. Input
collections can change during intersection callbacks without changing the captured membership, but boxes themselves
are shared: coordinate changes remain visible. Supply finite iterables and use the game thread for live geometry.
Each first-group box calls `intersects` on second-group boxes in encounter order. Duplicates participate; the first
intersection returns `false`. No intersections returns `true`. The existing `Cuboid6.intersects` tolerance is retained:
touching faces and sub-tolerance overlaps are allowed. Only cross-group pairs are tested, not pairs within one group.
Neither input nor its boxes is modified by the helper; custom iterators or `intersects` overrides can have side effects.
Null inputs fail during copying. Null box entries are not eagerly rejected: an empty opposite group never uses them,
and an earlier intersection may avoid them. A reached intersection involving an ordinary null box fails. Iterator and
intersection exceptions propagate unchanged, without undoing callback side effects.
This does not run part callbacks, generated aggregate partial-occlusion checks, slot checks or placement logic.
Use `tile.testOcclusion` for the tile's occlusion protocol, and the placement/replacement APIs for their wider checks.
The existing `NormalOcclusionTest.apply(JNormalOcclusion, TMultiPart)` part helper remains unchanged.
Both Scala box-list `apply(Traversable, Traversable)` entries, static and companion, are deprecated with their original
descriptors and bodies retained. OpenComputers' cable/network checks can pass `getOcclusionBoxes()` directly as the
second argument; their Scala `ownBounds` collection needs a Java adapter:
```scala
import scala.collection.JavaConverters._
NormalOcclusionTest.testBoxes(ownBounds.asJava, otherBounds)
```
ForgeRelocationFMP can similarly adapt its assembled Scala `boxes` sequence and pass its existing Java
`getOcclusionBoxes` iterable directly. Keep its combined normal, partial and collision boxes and caller order intact.
Scala consumers can adopt this FMP API while keeping their own Scala code.
+94
View File
@@ -0,0 +1,94 @@
# Loading and assigning multipart parts from Java
[API index](../API.md)
`TileMultipart.loadPartList(Collection<TMultiPart>)` and `setPartList(List<TMultiPart>)` adapt to the existing
virtual Scala-parameter hooks. Both legacy entries are deprecated for callers and remain supported for existing
binaries, subclasses and reflection.
These are reconstruction operations, not normal placement/removal. Use `TileMultipart.addPart` / `remPart` for world
changes. Use `MultipartHelper.createTileFromParts(Iterable<TMultiPart>)` to construct a new server composite tile; the
loader itself does not choose traits, promote a tile or install it in the world.
For separate client/server generation before world/NBT setup and loading, use the
[staged composite-generation API](COMPOSITE_GENERATION.md).
For an uninstalled client tile reconstructed from saved multipart NBT, use the complete
[client preview helper](CLIENT_PREVIEW.md) instead of assembling these steps.
## 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<TMultiPart> 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).
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 calls the Scala loader directly; older releases select it with assignability-based reflection.
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 an older GuideNH-compatible path, 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. Current GuideNH no longer uses the raw setter or reflection, but still needs to migrate its
Scala parts and companion generator to the [static Java replacement](COMPOSITE_GENERATION.md).
Schematica can select the Collection loader and pass its existing Java list directly.
New versions of both integrations should use the [client preview helper](CLIENT_PREVIEW.md).
+80
View File
@@ -0,0 +1,80 @@
# Registering part factories from Java
[API index](../API.md)
Use `MultiPartRegistry.registerPartFactory(IPartFactory2, String...)`. It delegates to the existing registry and
avoids the Scala types in the `registerParts` overload family.
To inspect a registered factory without constructing a part, see [factory lookup](FACTORY_LOOKUP.md), including
Schematica's replacement for private registry-map reflection.
## Example and timing
The [complete compiling example](../../src/functionalTest/java/codechicken/multipart/examples/PartRegistrationExample.java)
implements both required `IPartFactory2.createPart` methods, opts into saved-NBT client previews, and registers one
persistent type:
```java
MultiPartRegistry.registerPartFactory(new PartRegistrationExample(), PartRegistrationExample.PART_TYPE);
```
Call from your mod's common `preInit` or `init` handler on both sides, before FMP closes registration in `postInit`.
FML must have an active mod container; that container becomes the owner returned by `getModContainer(type)`.
Registration stores the factory without constructing, loading, binding or placing a part.
The example creates fresh, unbound instances whose `getType()` returns `yourmod:part`. Replace that sample ID and part
implementation with your own. Geometry, rendering and gameplay callbacks belong to the real part. Preserve already
published IDs exactly when migrating; adding a namespace to an existing ID changes its save/network identity.
Both single IDs and arrays are accepted. Multiple names can share a factory that selects the part class by name.
## Factory and payload ownership
`IPartFactory2` has two abstract methods, so it is not a single-method lambda interface. Its third method is an
optional default:
| Construction path | Factory input | What happens next |
| --- | --- | --- |
| Server/NBT | `createPart(String, NBTTagCompound)` receives the original tag object | Normal reconstruction calls `part.load` with that same tag |
| Client/description | `createPart(String, MCDataInput)` receives the original input, after the registry ID | Normal reconstruction calls `part.readDesc` with that same input at its current cursor |
| Client preview/NBT | `createPartForClientPreview(String, NBTTagCompound)` receives the original tag object | [Preview reconstruction](CLIENT_PREVIEW.md) calls `part.load` with that same tag; the default returns null |
A factory may inspect NBT or consume a packet discriminator to choose a class. There is no packet copy or rewind;
coordinate any consumed prefix with the part's `writeDesc` and `readDesc` protocol. FMP's microblock factory consumes
the material ID this way. Do not call `load` or `readDesc` in the factory merely to initialize the remaining payload,
because normal reconstruction calls them afterward. Return a fresh, unbound part for every supported name.
Direct `MultiPartRegistry.loadPart` and `readPart` calls only construct the part; their caller remains responsible for
the following payload/lifecycle work. The deprecated `createPart(name, boolean)` passes a null NBT or packet argument;
factories reached through that old path must tolerate it. Neither registration entry adds eager factory validation.
## Ordering and failures
IDs are processed in array order. The array itself is not retained, so changing it afterward does not rename registered
parts. The factory object is retained. A duplicate ID throws immediately, leaving any earlier IDs from that call
registered and skipping the suffix. Registration is not transactional; fix duplicate IDs rather than retrying the
whole batch. Later server ID-map setup sorts registered names; registration order is not a stable network numeric ID.
The new entry preserves the old Java array entry's failure order: a closed registry fails first, then the registry
enters its registering state and checks FML's active container, then it reads the array. Empty arrays still perform
the state/container checks; a null array fails after them. Supply a non-null factory and valid, unique non-null names;
the legacy implementation does not eagerly validate those values. Iterator conversion in the retained Scala sequence
entry still occurs before these checks, so malformed Scala inputs can fail earlier.
Factory exceptions propagate when constructing parts, not during registration. A registration call does not probe
factory results or promise that a later NBT/packet will be accepted.
## Migrating old callers
- `IPartFactory2` callers: retain the factory and IDs, then call `registerPartFactory`. ProjectRed can keep its existing
server/NBT and client/packet methods. Override `createPartForClientPreview` only when saved NBT can select a fresh
client variant. Scala code can pass a `String[]`/`Array[String]` as Java varargs using `: _*`.
- `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](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
deprecated; the older Boolean/function entries were already deprecated and now point to the supported replacement.
The old Java array entries remain callable too. Prefer the new name for consumer Java source: the old overload family
requires `scala.collection.Seq` and `scala.Function2` on the compile classpath even for Java factory/string inputs.
+95
View File
@@ -0,0 +1,95 @@
# Reading and visiting multipart parts from Java
[API index](../API.md)
Use `TileMultipart.jPartList()` for ordered collection access, and `forEachPart(Consumer<TMultiPart>)` for callbacks
that skip detached parts. Both methods work on generated tiles.
## Examples
Read all part types in list order:
```java
public static List<String> partTypes(TileMultipart tile) {
List<String> types = new ArrayList<>();
for (TMultiPart part : tile.jPartList()) {
types.add(part.getType());
}
return types;
}
```
To visit only parts that are still bound to this tile:
```java
public static List<String> boundPartTypes(TileMultipart tile) {
List<String> types = new ArrayList<>();
tile.forEachPart(part -> types.add(part.getType()));
return types;
}
```
See the [complete Java example](../../src/test/java/codechicken/multipart/examples/PartTraversalExample.java). The
returned name lists are independent copies.
## Collection ownership and ordering
`jPartList()` wraps the sequence returned by the virtual `partList()` getter at that call. It preserves every entry,
its index and its object identity, including detached parts. Use it for indexing, searches, serialization and ordinary
iteration. It does not require parts to have joined a world.
Normal FMP additions/removals replace an immutable sequence. A previously returned Java list keeps the old sequence;
call `jPartList()` again for the tile's new contents. A legacy setter or getter override can instead supply a mutable
sequence, in which case mutations of that sequence remain visible through its Java view. Therefore the method does
not promise either an independent snapshot or an unmodifiable list for every implementation.
Treat the view as read-only. Editing it, even when the backing sequence permits it, does not perform part binding,
slot updates, notifications or synchronization. Use `TileMultipart.addPart(world, pos, part)` and `tile.remPart(part)`
for normal world changes, retaining their returned tile because adding/removing capabilities can replace the tile
instance. To capture independent list storage, use `new ArrayList<>(tile.jPartList())`; the part objects remain shared.
## Callback behavior
Use the game thread. The default `forEachPart` traversal has the same behavior as the legacy `operate` hook:
- Capture the current sequence once and visit it in order. Normal additions during a callback publish a new sequence,
so the current traversal does not visit the added parts.
- Check `part.tile() == this` immediately before each callback. Parts detached or rebound to another tile are skipped,
including when an earlier callback replaces the tile and transfers its parts.
- A nested traversal captures the sequence anew and can observe the updated list. Each call has its own traversal state.
- Propagate the original callback exception immediately and stop that traversal. Side effects already performed remain.
- Preserve the iterator behavior of legacy mutable sequences. Do not structurally mutate such a sequence during traversal.
- Pass a non-null callback. For compatibility, there is no eager null check: with the default hook, null throws
`NullPointerException` only when a part still bound to this tile reaches the callback. Empty sequences or sequences
containing only detached/transferred parts invoke nothing.
`tile.jPartList().forEach(action)` visits every entry, including detached parts. It is not equivalent to
`tile.forEachPart(action)`. Preserve the consumer's original filtering and callback behavior when migrating.
## Overrides and legacy entry points
The dispatch paths are `jPartList()` → virtual `partList()`, and `forEachPart(consumer)` → virtual `operate(adapter)`.
The existing Java adapter and traversal implementation are shared; the legacy methods keep their descriptors and
bodies. Both legacy methods are deprecated for callers, with replacements named in their Javadocs.
Existing getter and `operate` overrides remain supported and can customize these behaviors. Lifecycle callbacks still
call `operate` directly. Overriding `forEachPart` intercepts calls to that convenience method only; it does not intercept
ticks, chunk callbacks or other lifecycle dispatch. Keep a legacy `operate` override in place if it supplies that hook.
No replacement lifecycle override contract is introduced by this addition.
## Consumer migration
| Existing use | Java replacement |
| --- | --- |
| `partList().size()` / `isEmpty()` / `indexOf(part)` | The corresponding `jPartList()` list method |
| Scala sequence indexing (`partList().apply(index)` or `tile.partList(index)`) | `tile.jPartList().get(index)` |
| Scala iterator for reading/searching every part | Enhanced `for` loop over `tile.jPartList()` |
| `operate(scalaFunction)` callback | `forEachPart(javaConsumer)`; preserve any existing hook overrides |
AE2's placement helper and Extra Utilities' renderer loops can use `jPartList()` without adding detached-part filtering.
ProjectRed's illumination calculations and packet/render indices, and OpenComputers' cable/print/network searches,
must retain their original order, filters and aggregation. Those mods can remain Scala internally while calling Java
collection methods. Existing Java consumers already using `jPartList()` need no rename.
GuideNH already uses `jPartList()` for material export and statistics. Its preview reconstruction and AE2 bridge
still use Scala `partList`; those move to the [client preview helper](CLIENT_PREVIEW.md).
+31
View File
@@ -0,0 +1,31 @@
# Multipart render ID
[API index](../API.md)
`TileMultipart.getRenderID()` and `setRenderID(int)` expose FMP's existing global block-render registration ID.
```java
int renderType = TileMultipart.getRenderID();
```
See the [compiling example](../../src/test/java/codechicken/multipart/examples/RenderIdExample.java). Reading the ID does not initialize a client renderer, allocate an ID or access a tile.
## Meaning and lifecycle
The initial value is `-1`. FMP's client renderer obtains an ID from Forge's `RenderingRegistry` when the renderer
singleton is first initialized, normally from client postInit. `BlockMultipart.getRenderType()` and the renderer's
`getRenderId()` read that same shared value. The dedicated server normally retains `-1`.
This is not a per-tile setting, a part type ID, a microblock material ID or a persistent identifier. Read the value
after normal client initialization when comparing render types; do not cache `-1` as the eventual client ID.
The setter is for controlled render setup. It only assigns the existing field, accepting every `int` unchanged,
including negative values. It does not reserve an ID, register a handler, update Forge's mapping, synchronize clients
or rebuild rendering. FMP's later renderer initialization still performs its own assignment. Ordinary integrations
should read the value and leave registration to FMP. Make any intentional setup changes on the initialization/game
thread; there is no new synchronization guarantee.
## Legacy compatibility
The old static and companion `renderID()` / `renderID_$eq(int)` methods remain with unchanged descriptors and bodies,
and are deprecated in favor of the Java names. All readers and writers share the original storage.
+53
View File
@@ -0,0 +1,53 @@
# Saw cutting strength
[Java API index](../API.md)
`ItemSaw.setHarvestLevel(int)` changes an existing FMP saw's cutting strength without reflection. The value is read
by `harvestLevel()`, `getCuttingStrength(ItemStack)` and `getMaxCuttingStrength()`, so recipes and FMP's 3D saw
renderer observe the same updated tier.
IguanaTweaksTConstruct can replace its private-field lookup and write with direct calls:
```java
ItemSaw saw = (ItemSaw) item;
int oldStrength = saw.harvestLevel();
int updatedStrength = HarvestLevelTweaks.getUpdatedHarvestLevel(oldStrength);
saw.setHarvestLevel(updatedStrength);
```
The [compiling example](../../src/test/java/codechicken/microblock/examples/SawStrengthExample.java) contains the
setter call.
Iguana's client proxy also reads the three built-in saws and the renderer mode through `MicroblockProxy$.MODULE$`.
The Java facade exposes the same state directly:
```java
Item stoneSaw = MicroblockProxy.sawStone();
Item ironSaw = MicroblockProxy.sawIron();
Item diamondSaw = MicroblockProxy.sawDiamond();
if (!MicroblockProxy.useSawIcons()) {
// Register the existing 3D saw renderers.
}
```
Keep the companion access only for already released binaries; rebuilt Java consumers should use the static facade.
## State and lifecycle
The setter changes only cutting strength. It does not recalculate the saw's durability or alter existing item-stack
damage. This matches Iguana's current post-construction field mutation. The integer is intentionally unrestricted,
like the constructor and legacy field; the consumer owns its tier mapping.
FMP calculates `MicroMaterialRegistry.getMaxCuttingStrength()` once during ForgeMicroblock post-initialization.
Startup integrations that add or relevel saws must finish first so the cached maximum sees the final tiers. Iguana's
optional ordering should therefore include `before:ForgeMicroblock` while retaining its existing FMP presence gate.
Call the setter on the main initialization thread, before recipes can be used.
The method is specific to `ItemSaw`. Other `Saw` implementations may derive strength from each `ItemStack` and do
not promise mutable global strength.
## Legacy compatibility
The private `harvestLevel: int` field remains in place for existing Iguana releases. It is mutable so the supported
setter and legacy reflection update the same storage. New integrations should use the public getter and setter and
should not catch and ignore API failures.
+57
View File
@@ -0,0 +1,57 @@
# Tile lookup and conversion results
[Java API index](../API.md)
`TileMultipart.getOrConvertTileResult(World, BlockCoord)` returns a `TileConversionResult` with `getTile()` and
`isConverted()` accessors.
```java
TileConversionResult result = TileMultipart.getOrConvertTileResult(world, pos);
TileMultipart tile = result.getTile(); // May be null.
boolean placeholder = result.isConverted();
```
The [compiling example](../../src/functionalTest/java/codechicken/multipart/examples/TileConversionExample.java) selects a
converted placeholder for inspection.
## Outcomes and ownership
| World state | `getTile()` | `isConverted()` |
| --- | --- | --- |
| A multipart tile already exists | That exact tile | `false` |
| A registered converter accepts the block | A fresh generated placeholder with its converted part bound | `true` |
| No multipart tile and no successful conversion | `null` | `false` |
An unrelated tile entity does not count as a multipart tile. Converters still get a chance to handle its block.
The existing-tile path returns before querying the block or converters. Conversion follows the existing registry
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
original block or installed the tile in the world. This lookup does not invoke the part's `onAdded` or `onConverted`
callbacks. Repeating it can create another tile and part; do not rely on identity across conversion queries.
Converters and binding hooks execute normally and can have side effects or throw. This is not a pure query or a
placement permission check. Call it on the appropriate world thread after FMP initialization. Converter failures
propagate without a new fallback or rollback guarantee.
For ordinary placement, use `canPlacePart(world, pos, part)` and then `addPart(world, pos, part)`, retaining the tile
returned by the addition. Addition performs conversion again and handles installation, callbacks and generated tile
replacement. Do not manually install the earlier placeholder, and do not treat it as a reservation of that location.
Use `getTile(world, pos)` to find only an existing multipart tile. The existing `getOrConvertTile(world, pos)` remains
supported when only the tile is needed; it has the same placeholder caveat and does not need migration.
## Legacy compatibility
Both static and companion `getOrConvertTile2(World, BlockCoord)` tuple entries remain, with unchanged descriptors and
bodies, deprecated in favor of the named Java result. The new method delegates to that existing path.
`MicroblockPlacement.gtile()` remains a separate Scala-shaped accessor.
AE2, Chisel, OpenComputers and Extra Utilities already use the tile-only method and need no change for this contract.
+140
View File
@@ -0,0 +1,140 @@
# Calling generated tile capabilities from Java
[API index](../API.md) · [Composite generation](COMPOSITE_GENERATION.md)
Call generated tiles through `TileMultipart` or a stable public capability interface. Several dev-jar classes under
`scalatraits`, and `TileMultipartClient`, are raw inputs to FMP's transformer: Forge changes them into interfaces
before generating a concrete tile. A Java signature that compiles against those classes can still fail at runtime.
## Why raw trait calls fail
These consumer expressions compile against the current dev jar but are unsafe:
```java
((TRedstoneTile) tile).openConnections(side); // javac emits invokevirtual for a class
((TSlottedTile) tile).v_partMap; // javac emits getfield
```
At runtime `TRedstoneTile` is an interface, so the first call throws `IncompatibleClassChangeError`. `TSlottedTile`
has generated accessor methods instead of that field, so the second throws `NoSuchFieldError`. A cast or an
`instanceof` check alone can still succeed; that does not make subsequent class-method/field bytecode valid.
Merely adding Scala to the compile classpath does not turn these raw Java classes into interface stubs.
Already compiled consumers using the original interface/accessor descriptors remain supported. Recompiling source
against the raw Java port is a separate gate. Do not instantiate or subclass raw trait inputs in consumer code, or
call their generated `$class` helpers as a new integration strategy. Reflection is not the migration target.
## Stable entry points
| Need | Compile against | Contract |
| --- | --- | --- |
| Parts, slot reads, placement, lifecycle | `TileMultipart` | `jPartList()`, `partMap(slot)`, placement and documented notifications dispatch through generated overrides |
| Open redstone geometry | `IRedstoneTile` | `openConnections(side)`; capability is present when the tile hosts a redstone part |
| Offered redstone connections or masked power | `IRedstoneConnector` | `getConnectionMask(side)`, `weakPowerLevel(side, mask)`; also used by non-FMP connectors |
| Ordinary tile power queries | `TileMultipart` | `strongPowerLevel(side)`, `weakPowerLevel(side)`; preserve each method's side convention |
| Inventory or sided inventory | Minecraft `IInventory` / `ISidedInventory` | Use the interface implemented by the tile, rather than raw `JInventoryTile` or its internal caches |
| Inventory slots after a part's size changes | `TileMultipart` | `refreshInventorySlots()`; see [refreshing inventory slots](#refreshing-inventory-slots) |
| Fluid operations | Forge `IFluidHandler` | Use the interface rather than raw `TFluidHandlerTile` or `tankList` |
| A consumer-owned pass-through capability | The original ordinary Java interface | Register with `MultipartGenerator.registerPassThroughInterface`; generated calls forward to the implementing part |
Test the capability when it is optional. Keep using the tile returned by placement/removal because adding or removing
capabilities can replace the tile instance. These interfaces do not give a snapshot, reserve a tile, or add thread
safety. Apply the owning method's lifecycle and side rules. Client-only rendering calls remain client-only even when
a stable base method exists.
## Compiling redstone example
[TileTraitAccessExample.java](../../src/functionalTest/java/codechicken/multipart/examples/TileTraitAccessExample.java)
uses only `TileMultipart` and `IRedstoneTile` and compiles as Java 8 without Scala on the classpath:
```java
boolean open = TileTraitAccessExample.hasOpenConnection(tile, side, mask);
```
The example returns false for a null tile or absent capability. Its caller supplies a Minecraft side in 0..5 and
a mask using bits 0..3 for rotations around that side and bit 4 for the center. `openConnections` describes openings
after face/edge obstruction; `getConnectionMask` describes the connections offered by contained parts. They are not
interchangeable. The API does not validate the side or add a cache.
ProjectRed's `transmission/redwires.scala` already knows its tile supports redstone. Its migration can change only
the cast type, preserving the surrounding mask and rotation calculation:
```scala
tile.asInstanceOf[IRedstoneTile].openConnections(absDir)
```
That emits an interface call with the stable owner. ProjectRed can remain Scala internally.
## Refreshing a changed slot mask
Use `TileMultipart.refreshPartSlots(part)` after an already stored part validates and applies a new
`TSlottedPart.getSlotMask()`. It provides the Java replacement for OpenComputers' direct `TSlottedTile.v_partMap`
mutation:
```java
tile.refreshPartSlots(this);
tile.notifyPartChange(this);
sendDescUpdate();
```
The [compiling example](../../src/functionalTest/java/codechicken/multipart/examples/TileTraitAccessExample.java) keeps
the cache operation itself separate because validation, state changes and notification policy belong to the part:
```java
TileTraitAccessExample.refreshSlots(tile, part);
```
On a generated slotted tile, FMP scans the live slot array in index order, clears every entry for which
`Objects.equals(stored, part)` is true, then dispatches the existing virtual `bindPart(part)` once. This preserves
Scala `==` behavior, including distinct equal objects. It reads the array directly, matching the old consumer rather
than a possible `partMap` override. Unrelated slots, part-list storage and tile ownership stay unchanged. The current
mask may overwrite a slot if the caller skipped its normal replacement/occlusion check.
A tile without the slotted capability does nothing. The method does not check that the part is stored, bound to this
tile or slotted, and it does not validate placement, send notifications, mark dirty/render state or schedule updates.
Call it on the owning world thread only after the new shape passes the consumer's existing `canReplacePart` logic.
Keep the tile/part's existing notification, sound, packet and scheduling sequence afterward.
`bindPart` dispatches through every generated cache trait, so those hooks still run once. As before, some non-slot
caches append on bind and are not generally idempotent. This API matches OpenComputers' print part, whose additional
capabilities do not append such caches; it is not a general refresh for inventory/fluid capability changes (see
[refreshing inventory slots](#refreshing-inventory-slots)). A whole
`loadPartList` reconstruction would run broader cache, binding and notification behavior and is not equivalent.
## Refreshing inventory slots
A tile holding `IInventory` parts exposes one flattened inventory: each part's slots in part order. FMP caches that
mapping and rebuilds it when inventory parts are added, removed, loaded or copied. When a stored part changes its
own `getSizeInventory()`, call `TileMultipart.refreshInventorySlots()`. It replaces AE2's direct
`TIInventoryTile.rebuildSlotMap()` call and drops the `instanceof` check, because tiles without inventory parts do
nothing:
```java
tile.refreshInventorySlots();
notifyNeighbors();
```
The [compiling example](../../src/functionalTest/java/codechicken/multipart/examples/TileTraitAccessExample.java)
wraps the same call:
```java
TileTraitAccessExample.refreshInventory(tile);
```
It only recomputes the mapping from the inventories already tracked. It does not add or remove inventories, call
`bindPart`, touch other trait caches, move items, mark the tile dirty or notify neighbors. Keep the caller's existing
notifications afterward and call it on the owning world thread. Do not use `refreshPartSlots` for this: its
`bindPart` dispatch would track the inventory part a second time.
The old `TIInventoryTile.rebuildSlotMap()` call stays supported for released AE2 jars, and both calls do the same
rebuild.
## Custom generated tiles
For custom generated tiles, keep consumer-callable methods on an ordinary Java capability interface and use the
stable base for existing tile hooks. The [custom tile-trait guide](CUSTOM_TILE_TRAITS.md) provides the complete
registration, helper, state/lifecycle and access pattern. Pass-through registration remains the smaller choice when
a tile should only forward one interface to one implementing part.
[RawTileTraitCalls.java](../../src/functionalTest/java/codechicken/multipart/test/RawTileTraitCalls.java) keeps the two
unsafe caller shapes above as compiled fixtures, so the linkage failures they produce stay reproducible.